diff options
Diffstat (limited to 'lib/Support')
-rw-r--r-- | lib/Support/APFloat.cpp | 284 | ||||
-rw-r--r-- | lib/Support/APInt.cpp | 79 | ||||
-rw-r--r-- | lib/Support/Allocator.cpp | 9 | ||||
-rw-r--r-- | lib/Support/CommandLine.cpp | 4 | ||||
-rw-r--r-- | lib/Support/Debug.cpp | 14 | ||||
-rw-r--r-- | lib/Support/Dwarf.cpp | 3 | ||||
-rw-r--r-- | lib/Support/ErrorHandling.cpp | 34 | ||||
-rw-r--r-- | lib/Support/FoldingSet.cpp | 10 | ||||
-rw-r--r-- | lib/Support/GraphWriter.cpp | 45 | ||||
-rw-r--r-- | lib/Support/MemoryBuffer.cpp | 79 | ||||
-rw-r--r-- | lib/Support/SourceMgr.cpp | 10 | ||||
-rw-r--r-- | lib/Support/Statistic.cpp | 65 | ||||
-rw-r--r-- | lib/Support/Timer.cpp | 502 | ||||
-rw-r--r-- | lib/Support/Triple.cpp | 2 | ||||
-rw-r--r-- | lib/Support/circular_raw_ostream.cpp | 12 | ||||
-rw-r--r-- | lib/Support/raw_ostream.cpp | 53 | ||||
-rw-r--r-- | lib/Support/regengine.inc | 93 | ||||
-rw-r--r-- | lib/Support/regexec.c | 4 |
18 files changed, 675 insertions, 627 deletions
diff --git a/lib/Support/APFloat.cpp b/lib/Support/APFloat.cpp index 8f860a6467..485bf4d6c9 100644 --- a/lib/Support/APFloat.cpp +++ b/lib/Support/APFloat.cpp @@ -65,7 +65,7 @@ namespace llvm { pow(5, power) is power * 815 / (351 * integerPartWidth) + 1 - + However, whilst the result may require only this many parts, because we are multiplying two values to get it, the multiplication may require an extra part with the excess part @@ -100,15 +100,15 @@ hexDigitValue(unsigned int c) unsigned int r; r = c - '0'; - if(r <= 9) + if (r <= 9) return r; r = c - 'A'; - if(r <= 5) + if (r <= 5) return r + 10; r = c - 'a'; - if(r <= 5) + if (r <= 5) return r + 10; return -1U; @@ -116,8 +116,8 @@ hexDigitValue(unsigned int c) static inline void assertArithmeticOK(const llvm::fltSemantics &semantics) { - assert(semantics.arithmeticOK - && "Compile-time arithmetic does not support these semantics"); + assert(semantics.arithmeticOK && + "Compile-time arithmetic does not support these semantics"); } /* Return the value of a decimal exponent of the form @@ -179,37 +179,37 @@ totalExponent(StringRef::iterator p, StringRef::iterator end, assert(p != end && "Exponent has no digits"); negative = *p == '-'; - if(*p == '-' || *p == '+') { + if (*p == '-' || *p == '+') { p++; assert(p != end && "Exponent has no digits"); } unsignedExponent = 0; overflow = false; - for(; p != end; ++p) { + for (; p != end; ++p) { unsigned int value; value = decDigitValue(*p); assert(value < 10U && "Invalid character in exponent"); unsignedExponent = unsignedExponent * 10 + value; - if(unsignedExponent > 65535) + if (unsignedExponent > 65535) overflow = true; } - if(exponentAdjustment > 65535 || exponentAdjustment < -65536) + if (exponentAdjustment > 65535 || exponentAdjustment < -65536) overflow = true; - if(!overflow) { + if (!overflow) { exponent = unsignedExponent; - if(negative) + if (negative) exponent = -exponent; exponent += exponentAdjustment; - if(exponent > 65535 || exponent < -65536) + if (exponent > 65535 || exponent < -65536) overflow = true; } - if(overflow) + if (overflow) exponent = negative ? -65536: 65535; return exponent; @@ -221,15 +221,15 @@ skipLeadingZeroesAndAnyDot(StringRef::iterator begin, StringRef::iterator end, { StringRef::iterator p = begin; *dot = end; - while(*p == '0' && p != end) + while (*p == '0' && p != end) p++; - if(*p == '.') { + if (*p == '.') { *dot = p++; assert(end - begin != 1 && "Significand has no digits"); - while(*p == '0' && p != end) + while (*p == '0' && p != end) p++; } @@ -323,13 +323,13 @@ trailingHexadecimalFraction(StringRef::iterator p, StringRef::iterator end, /* If the first trailing digit isn't 0 or 8 we can work out the fraction immediately. */ - if(digitValue > 8) + if (digitValue > 8) return lfMoreThanHalf; - else if(digitValue < 8 && digitValue > 0) + else if (digitValue < 8 && digitValue > 0) return lfLessThanHalf; /* Otherwise we need to find the first non-zero digit. */ - while(*p == '0') + while (*p == '0') p++; assert(p != end && "Invalid trailing hexadecimal fraction!"); @@ -338,7 +338,7 @@ trailingHexadecimalFraction(StringRef::iterator p, StringRef::iterator end, /* If we ran off the end it is exactly zero or one-half, otherwise a little more. */ - if(hexDigit == -1U) + if (hexDigit == -1U) return digitValue == 0 ? lfExactlyZero: lfExactlyHalf; else return digitValue == 0 ? lfLessThanHalf: lfMoreThanHalf; @@ -356,12 +356,12 @@ lostFractionThroughTruncation(const integerPart *parts, lsb = APInt::tcLSB(parts, partCount); /* Note this is guaranteed true if bits == 0, or LSB == -1U. */ - if(bits <= lsb) + if (bits <= lsb) return lfExactlyZero; - if(bits == lsb + 1) + if (bits == lsb + 1) return lfExactlyHalf; - if(bits <= partCount * integerPartWidth - && APInt::tcExtractBit(parts, bits - 1)) + if (bits <= partCount * integerPartWidth && + APInt::tcExtractBit(parts, bits - 1)) return lfMoreThanHalf; return lfLessThanHalf; @@ -385,10 +385,10 @@ static lostFraction combineLostFractions(lostFraction moreSignificant, lostFraction lessSignificant) { - if(lessSignificant != lfExactlyZero) { - if(moreSignificant == lfExactlyZero) + if (lessSignificant != lfExactlyZero) { + if (moreSignificant == lfExactlyZero) moreSignificant = lfLessThanHalf; - else if(moreSignificant == lfExactlyHalf) + else if (moreSignificant == lfExactlyHalf) moreSignificant = lfMoreThanHalf; } @@ -468,7 +468,7 @@ powerOf5(integerPart *dst, unsigned int power) 15625, 78125 }; integerPart pow5s[maxPowerOfFiveParts * 2 + 5]; pow5s[0] = 78125 * 5; - + unsigned int partsCount[16] = { 1 }; integerPart scratch[maxPowerOfFiveParts], *p1, *p2, *pow5; unsigned int result; @@ -588,14 +588,14 @@ APFloat::initialize(const fltSemantics *ourSemantics) semantics = ourSemantics; count = partCount(); - if(count > 1) + if (count > 1) significand.parts = new integerPart[count]; } void APFloat::freeSignificand() { - if(partCount() > 1) + if (partCount() > 1) delete [] significand.parts; } @@ -609,7 +609,7 @@ APFloat::assign(const APFloat &rhs) exponent = rhs.exponent; sign2 = rhs.sign2; exponent2 = rhs.exponent2; - if(category == fcNormal || category == fcNaN) + if (category == fcNormal || category == fcNaN) copySignificand(rhs); } @@ -683,8 +683,8 @@ APFloat APFloat::makeNaN(const fltSemantics &Sem, bool SNaN, bool Negative, APFloat & APFloat::operator=(const APFloat &rhs) { - if(this != &rhs) { - if(semantics != rhs.semantics) { + if (this != &rhs) { + if (semantics != rhs.semantics) { freeSignificand(); initialize(rhs.semantics); } @@ -881,7 +881,7 @@ APFloat::multiplySignificand(const APFloat &rhs, const APFloat *addend) precision = semantics->precision; newPartsCount = partCountForBits(precision * 2); - if(newPartsCount > 4) + if (newPartsCount > 4) fullSignificand = new integerPart[newPartsCount]; else fullSignificand = scratch; @@ -896,7 +896,7 @@ APFloat::multiplySignificand(const APFloat &rhs, const APFloat *addend) omsb = APInt::tcMSB(fullSignificand, newPartsCount) + 1; exponent += rhs.exponent; - if(addend) { + if (addend) { Significand savedSignificand = significand; const fltSemantics *savedSemantics = semantics; fltSemantics extendedSemantics; @@ -905,18 +905,17 @@ APFloat::multiplySignificand(const APFloat &rhs, const APFloat *addend) /* Normalize our MSB. */ extendedPrecision = precision + precision - 1; - if(omsb != extendedPrecision) - { - APInt::tcShiftLeft(fullSignificand, newPartsCount, - extendedPrecision - omsb); - exponent -= extendedPrecision - omsb; - } + if (omsb != extendedPrecision) { + APInt::tcShiftLeft(fullSignificand, newPartsCount, + extendedPrecision - omsb); + exponent -= extendedPrecision - omsb; + } /* Create new semantics. */ extendedSemantics = *semantics; extendedSemantics.precision = extendedPrecision; - if(newPartsCount == 1) + if (newPartsCount == 1) significand.part = fullSignificand[0]; else significand.parts = fullSignificand; @@ -928,7 +927,7 @@ APFloat::multiplySignificand(const APFloat &rhs, const APFloat *addend) lost_fraction = addOrSubtractSignificand(extendedAddend, false); /* Restore our state. */ - if(newPartsCount == 1) + if (newPartsCount == 1) fullSignificand[0] = significand.part; significand = savedSignificand; semantics = savedSemantics; @@ -938,7 +937,7 @@ APFloat::multiplySignificand(const APFloat &rhs, const APFloat *addend) exponent -= (precision - 1); - if(omsb > precision) { + if (omsb > precision) { unsigned int bits, significantParts; lostFraction lf; @@ -951,7 +950,7 @@ APFloat::multiplySignificand(const APFloat &rhs, const APFloat *addend) APInt::tcAssign(lhsSignificand, fullSignificand, partsCount); - if(newPartsCount > 4) + if (newPartsCount > 4) delete [] fullSignificand; return lost_fraction; @@ -973,7 +972,7 @@ APFloat::divideSignificand(const APFloat &rhs) rhsSignificand = rhs.significandParts(); partsCount = partCount(); - if(partsCount > 2) + if (partsCount > 2) dividend = new integerPart[partsCount * 2]; else dividend = scratch; @@ -981,7 +980,7 @@ APFloat::divideSignificand(const APFloat &rhs) divisor = dividend + partsCount; /* Copy the dividend and divisor as they will be modified in-place. */ - for(i = 0; i < partsCount; i++) { + for (i = 0; i < partsCount; i++) { dividend[i] = lhsSignificand[i]; divisor[i] = rhsSignificand[i]; lhsSignificand[i] = 0; @@ -993,14 +992,14 @@ APFloat::divideSignificand(const APFloat &rhs) /* Normalize the divisor. */ bit = precision - APInt::tcMSB(divisor, partsCount) - 1; - if(bit) { + if (bit) { exponent += bit; APInt::tcShiftLeft(divisor, partsCount, bit); } /* Normalize the dividend. */ bit = precision - APInt::tcMSB(dividend, partsCount) - 1; - if(bit) { + if (bit) { exponent -= bit; APInt::tcShiftLeft(dividend, partsCount, bit); } @@ -1008,15 +1007,15 @@ APFloat::divideSignificand(const APFloat &rhs) /* Ensure the dividend >= divisor initially for the loop below. Incidentally, this means that the division loop below is guaranteed to set the integer bit to one. */ - if(APInt::tcCompare(dividend, divisor, partsCount) < 0) { + if (APInt::tcCompare(dividend, divisor, partsCount) < 0) { exponent--; APInt::tcShiftLeft(dividend, partsCount, 1); assert(APInt::tcCompare(dividend, divisor, partsCount) >= 0); } /* Long division. */ - for(bit = precision; bit; bit -= 1) { - if(APInt::tcCompare(dividend, divisor, partsCount) >= 0) { + for (bit = precision; bit; bit -= 1) { + if (APInt::tcCompare(dividend, divisor, partsCount) >= 0) { APInt::tcSubtract(dividend, divisor, 0, partsCount); APInt::tcSetBit(lhsSignificand, bit - 1); } @@ -1027,16 +1026,16 @@ APFloat::divideSignificand(const APFloat &rhs) /* Figure out the lost fraction. */ int cmp = APInt::tcCompare(dividend, divisor, partsCount); - if(cmp > 0) + if (cmp > 0) lost_fraction = lfMoreThanHalf; - else if(cmp == 0) + else if (cmp == 0) lost_fraction = lfExactlyHalf; - else if(APInt::tcIsZero(dividend, partsCount)) + else if (APInt::tcIsZero(dividend, partsCount)) lost_fraction = lfExactlyZero; else lost_fraction = lfLessThanHalf; - if(partsCount > 2) + if (partsCount > 2) delete [] dividend; return lost_fraction; @@ -1072,7 +1071,7 @@ APFloat::shiftSignificandLeft(unsigned int bits) { assert(bits < semantics->precision); - if(bits) { + if (bits) { unsigned int partsCount = partCount(); APInt::tcShiftLeft(significandParts(), partsCount, bits); @@ -1095,13 +1094,13 @@ APFloat::compareAbsoluteValue(const APFloat &rhs) const /* If exponents are equal, do an unsigned bignum comparison of the significands. */ - if(compare == 0) + if (compare == 0) compare = APInt::tcCompare(significandParts(), rhs.significandParts(), partCount()); - if(compare > 0) + if (compare > 0) return cmpGreaterThan; - else if(compare < 0) + else if (compare < 0) return cmpLessThan; else return cmpEqual; @@ -1113,14 +1112,13 @@ APFloat::opStatus APFloat::handleOverflow(roundingMode rounding_mode) { /* Infinity? */ - if(rounding_mode == rmNearestTiesToEven - || rounding_mode == rmNearestTiesToAway - || (rounding_mode == rmTowardPositive && !sign) - || (rounding_mode == rmTowardNegative && sign)) - { - category = fcInfinity; - return (opStatus) (opOverflow | opInexact); - } + if (rounding_mode == rmNearestTiesToEven || + rounding_mode == rmNearestTiesToAway || + (rounding_mode == rmTowardPositive && !sign) || + (rounding_mode == rmTowardNegative && sign)) { + category = fcInfinity; + return (opStatus) (opOverflow | opInexact); + } /* Otherwise we become the largest finite number. */ category = fcNormal; @@ -1155,11 +1153,11 @@ APFloat::roundAwayFromZero(roundingMode rounding_mode, return lost_fraction == lfExactlyHalf || lost_fraction == lfMoreThanHalf; case rmNearestTiesToEven: - if(lost_fraction == lfMoreThanHalf) + if (lost_fraction == lfMoreThanHalf) return true; /* Our zeroes don't have a significand to test. */ - if(lost_fraction == lfExactlyHalf && category != fcZero) + if (lost_fraction == lfExactlyHalf && category != fcZero) return APInt::tcExtractBit(significandParts(), bit); return false; @@ -1182,13 +1180,13 @@ APFloat::normalize(roundingMode rounding_mode, unsigned int omsb; /* One, not zero, based MSB. */ int exponentChange; - if(category != fcNormal) + if (category != fcNormal) return opOK; /* Before rounding normalize the exponent of fcNormal numbers. */ omsb = significandMSB() + 1; - if(omsb) { + if (omsb) { /* OMSB is numbered from 1. We want to place it in the integer bit numbered PRECISON if possible, with a compensating change in the exponent. */ @@ -1196,16 +1194,16 @@ APFloat::normalize(roundingMode rounding_mode, /* If the resulting exponent is too high, overflow according to the rounding mode. */ - if(exponent + exponentChange > semantics->maxExponent) + if (exponent + exponentChange > semantics->maxExponent) return handleOverflow(rounding_mode); /* Subnormal numbers have exponent minExponent, and their MSB is forced based on that. */ - if(exponent + exponentChange < semantics->minExponent) + if (exponent + exponentChange < semantics->minExponent) exponentChange = semantics->minExponent - exponent; /* Shifting left is easy as we don't lose precision. */ - if(exponentChange < 0) { + if (exponentChange < 0) { assert(lost_fraction == lfExactlyZero); shiftSignificandLeft(-exponentChange); @@ -1213,7 +1211,7 @@ APFloat::normalize(roundingMode rounding_mode, return opOK; } - if(exponentChange > 0) { + if (exponentChange > 0) { lostFraction lf; /* Shift right and capture any new lost fraction. */ @@ -1222,7 +1220,7 @@ APFloat::normalize(roundingMode rounding_mode, lost_fraction = combineLostFractions(lf, lost_fraction); /* Keep OMSB up-to-date. */ - if(omsb > (unsigned) exponentChange) + if (omsb > (unsigned) exponentChange) omsb -= exponentChange; else omsb = 0; @@ -1234,28 +1232,28 @@ APFloat::normalize(roundingMode rounding_mode, /* As specified in IEEE 754, since we do not trap we do not report underflow for exact results. */ - if(lost_fraction == lfExactlyZero) { + if (lost_fraction == lfExactlyZero) { /* Canonicalize zeroes. */ - if(omsb == 0) + if (omsb == 0) category = fcZero; return opOK; } /* Increment the significand if we're rounding away from zero. */ - if(roundAwayFromZero(rounding_mode, lost_fraction, 0)) { - if(omsb == 0) + if (roundAwayFromZero(rounding_mode, lost_fraction, 0)) { + if (omsb == 0) exponent = semantics->minExponent; incrementSignificand(); omsb = significandMSB() + 1; /* Did the significand increment overflow? */ - if(omsb == (unsigned) semantics->precision + 1) { + if (omsb == (unsigned) semantics->precision + 1) { /* Renormalize by incrementing the exponent and shifting our significand right one. However if we already have the maximum exponent we overflow to infinity. */ - if(exponent == semantics->maxExponent) { + if (exponent == semantics->maxExponent) { category = fcInfinity; return (opStatus) (opOverflow | opInexact); @@ -1269,14 +1267,14 @@ APFloat::normalize(roundingMode rounding_mode, /* The normal case - we were and are not denormal, and any significand increment above didn't overflow. */ - if(omsb == semantics->precision) + if (omsb == semantics->precision) return opInexact; /* We have a non-zero denormal. */ assert(omsb < semantics->precision); /* Canonicalize zeroes. */ - if(omsb == 0) + if (omsb == 0) category = fcZero; /* The fcZero case is a denormal that underflowed to zero. */ @@ -1324,7 +1322,7 @@ APFloat::addOrSubtractSpecials(const APFloat &rhs, bool subtract) case convolve(fcInfinity, fcInfinity): /* Differently signed infinities can only be validly subtracted. */ - if(((sign ^ rhs.sign)!=0) != subtract) { + if (((sign ^ rhs.sign)!=0) != subtract) { makeNaN(); return opInvalidOp; } @@ -1352,7 +1350,7 @@ APFloat::addOrSubtractSignificand(const APFloat &rhs, bool subtract) bits = exponent - rhs.exponent; /* Subtraction is more subtle than one might naively expect. */ - if(subtract) { + if (subtract) { APFloat temp_rhs(rhs); bool reverse; @@ -1381,16 +1379,16 @@ APFloat::addOrSubtractSignificand(const APFloat &rhs, bool subtract) /* Invert the lost fraction - it was on the RHS and subtracted. */ - if(lost_fraction == lfLessThanHalf) + if (lost_fraction == lfLessThanHalf) lost_fraction = lfMoreThanHalf; - else if(lost_fraction == lfMoreThanHalf) + else if (lost_fraction == lfMoreThanHalf) lost_fraction = lfLessThanHalf; /* The code above is intended to ensure that no borrow is necessary. */ assert(!carry); } else { - if(bits > 0) { + if (bits > 0) { APFloat temp_rhs(rhs); lost_fraction = temp_rhs.shiftSignificandRight(bits); @@ -1561,7 +1559,7 @@ APFloat::addOrSubtract(const APFloat &rhs, roundingMode rounding_mode, fs = addOrSubtractSpecials(rhs, subtract); /* This return code means it was not a simple case. */ - if(fs == opDivByZero) { + if (fs == opDivByZero) { lostFraction lost_fraction; lost_fraction = addOrSubtractSignificand(rhs, subtract); @@ -1574,8 +1572,8 @@ APFloat::addOrSubtract(const APFloat &rhs, roundingMode rounding_mode, /* If two numbers add (exactly) to zero, IEEE 754 decrees it is a positive zero unless rounding to minus infinity, except that adding two like-signed zeroes gives that zero. */ - if(category == fcZero) { - if(rhs.category != fcZero || (sign == rhs.sign) == subtract) + if (category == fcZero) { + if (rhs.category != fcZero || (sign == rhs.sign) == subtract) sign = (rounding_mode == rmTowardNegative); } @@ -1606,10 +1604,10 @@ APFloat::multiply(const APFloat &rhs, roundingMode rounding_mode) sign ^= rhs.sign; fs = multiplySpecials(rhs); - if(category == fcNormal) { + if (category == fcNormal) { lostFraction lost_fraction = multiplySignificand(rhs, 0); fs = normalize(rounding_mode, lost_fraction); - if(lost_fraction != lfExactlyZero) + if (lost_fraction != lfExactlyZero) fs = (opStatus) (fs | opInexact); } @@ -1626,10 +1624,10 @@ APFloat::divide(const APFloat &rhs, roundingMode rounding_mode) sign ^= rhs.sign; fs = divideSpecials(rhs); - if(category == fcNormal) { + if (category == fcNormal) { lostFraction lost_fraction = divideSignificand(rhs); fs = normalize(rounding_mode, lost_fraction); - if(lost_fraction != lfExactlyZero) + if (lost_fraction != lfExactlyZero) fs = (opStatus) (fs | opInexact); } @@ -1673,7 +1671,7 @@ APFloat::remainder(const APFloat &rhs) return fs; } -/* Normalized llvm frem (C fmod). +/* Normalized llvm frem (C fmod). This is not currently correct in all cases. */ APFloat::opStatus APFloat::mod(const APFloat &rhs, roundingMode rounding_mode) @@ -1730,20 +1728,20 @@ APFloat::fusedMultiplyAdd(const APFloat &multiplicand, /* If and only if all arguments are normal do we need to do an extended-precision calculation. */ - if(category == fcNormal - && multiplicand.category == fcNormal - && addend.category == fcNormal) { + if (category == fcNormal && + multiplicand.category == fcNormal && + addend.category == fcNormal) { lostFraction lost_fraction; lost_fraction = multiplySignificand(multiplicand, &addend); fs = normalize(rounding_mode, lost_fraction); - if(lost_fraction != lfExactlyZero) + if (lost_fraction != lfExactlyZero) fs = (opStatus) (fs | opInexact); /* If two numbers add (exactly) to zero, IEEE 754 decrees it is a positive zero unless rounding to minus infinity, except that adding two like-signed zeroes gives that zero. */ - if(category == fcZero && sign != addend.sign) + if (category == fcZero && sign != addend.sign) sign = (rounding_mode == rmTowardNegative); } else { fs = multiplySpecials(multiplicand); @@ -1755,7 +1753,7 @@ APFloat::fusedMultiplyAdd(const APFloat &multiplicand, If we need to do the addition we can do so with normal precision. */ - if(fs == opOK) + if (fs == opOK) fs = addOrSubtract(addend, rounding_mode, false); } @@ -1787,7 +1785,7 @@ APFloat::compare(const APFloat &rhs) const case convolve(fcInfinity, fcNormal): case convolve(fcInfinity, fcZero): case convolve(fcNormal, fcZero): - if(sign) + if (sign) return cmpLessThan; else return cmpGreaterThan; @@ -1795,15 +1793,15 @@ APFloat::compare(const APFloat &rhs) const case convolve(fcNormal, fcInfinity): case convolve(fcZero, fcInfinity): case convolve(fcZero, fcNormal): - if(rhs.sign) + if (rhs.sign) return cmpGreaterThan; else return cmpLessThan; case convolve(fcInfinity, fcInfinity): - if(sign == rhs.sign) + if (sign == rhs.sign) return cmpEqual; - else if(sign) + else if (sign) return cmpLessThan; else return cmpGreaterThan; @@ -1816,8 +1814,8 @@ APFloat::compare(const APFloat &rhs) const } /* Two normal numbers. Do they have the same sign? */ - if(sign != rhs.sign) { - if(sign) + if (sign != rhs.sign) { + if (sign) result = cmpLessThan; else result = cmpGreaterThan; @@ -1825,10 +1823,10 @@ APFloat::compare(const APFloat &rhs) const /* Compare absolute values; invert result if negative. */ result = compareAbsoluteValue(rhs); - if(sign) { - if(result == cmpLessThan) + if (sign) { + if (result == cmpLessThan) result = cmpGreaterThan; - else if(result == cmpGreaterThan) + else if (result == cmpGreaterThan) result = cmpLessThan; } } @@ -1886,7 +1884,7 @@ APFloat::convert(const fltSemantics &toSemantics, } } - if(category == fcNormal) { + if (category == fcNormal) { /* Re-interpret our bit-pattern. */ exponent += toSemantics.precision - semantics->precision; semantics = &toSemantics; @@ -1911,7 +1909,7 @@ APFloat::convert(const fltSemantics &toSemantics, // x87 long double). if (APInt::tcLSB(significandParts(), newPartCount) < ushift) *losesInfo = true; - if (oldSemantics == &APFloat::x87DoubleExtended && + if (oldSemantics == &APFloat::x87DoubleExtended && (!(*significandParts() & 0x8000000000000000ULL) || !(*significandParts() & 0x4000000000000000ULL))) *losesInfo = true; @@ -1956,12 +1954,12 @@ APFloat::convertToSignExtendedInteger(integerPart *parts, unsigned int width, *isExact = false; /* Handle the three special cases first. */ - if(category == fcInfinity || category == fcNaN) + if (category == fcInfinity || category == fcNaN) return opInvalidOp; dstPartsCount = partCountForBits(width); - if(category == fcZero) { + if (category == fcZero) { APInt::tcSet(parts, 0, dstPartsCount); // Negative zero can't be represented as an int. *isExact = !sign; @@ -2004,8 +2002,8 @@ APFloat::convertToSignExtendedInteger(integerPart *parts, unsigned int width, if (truncatedBits) { lost_fraction = lostFractionThroughTruncation(src, partCount(), truncatedBits); - if (lost_fraction != lfExactlyZero - && roundAwayFromZero(rounding_mode, lost_fraction, truncatedBits)) { + if (lost_fraction != lfExactlyZero && + roundAwayFromZero(rounding_mode, lost_fraction, truncatedBits)) { if (APInt::tcIncrement(parts, dstPartsCount)) return opInvalidOp; /* Overflow. */ } @@ -2062,7 +2060,7 @@ APFloat::convertToInteger(integerPart *parts, unsigned int width, { opStatus fs; - fs = convertToSignExtendedInteger(parts, width, isSigned, rounding_mode, + fs = convertToSignExtendedInteger(parts, width, isSigned, rounding_mode, isExact); if (fs == opInvalidOp) { @@ -2149,8 +2147,8 @@ APFloat::convertFromSignExtendedInteger(const integerPart *src, opStatus status; assertArithmeticOK(*semantics); - if (isSigned - && APInt::tcExtractBit(src, srcCount * integerPartWidth - 1)) { + if (isSigned && + APInt::tcExtractBit(src, srcCount * integerPartWidth - 1)) { integerPart *copy; /* If we're signed and negative negate a copy. */ @@ -2178,7 +2176,7 @@ APFloat::convertFromZeroExtendedInteger(const integerPart *parts, APInt api = APInt(width, partCount, parts); sign = false; - if(isSigned && APInt::tcExtractBit(parts, width - 1)) { + if (isSigned && APInt::tcExtractBit(parts, width - 1)) { sign = true; api = -api; } @@ -2209,10 +2207,10 @@ APFloat::convertFromHexadecimalString(const StringRef &s, StringRef::iterator p = skipLeadingZeroesAndAnyDot(begin, end, &dot); firstSignificantDigit = p; - for(; p != end;) { + for (; p != end;) { integerPart hex_value; - if(*p == '.') { + if (*p == '.') { assert(dot == end && "String contains multiple dots"); dot = p++; if (p == end) { @@ -2221,7 +2219,7 @@ APFloat::convertFromHexadecimalString(const StringRef &s, } hex_value = hexDigitValue(*p); - if(hex_value == -1U) { + if (hex_value == -1U) { break; } @@ -2231,13 +2229,13 @@ APFloat::convertFromHexadecimalString(const StringRef &s, break; } else { /* Store the number whilst 4-bit nibbles remain. */ - if(bitPos) { + if (bitPos) { bitPos -= 4; hex_value <<= bitPos % integerPartWidth; significand[bitPos / integerPartWidth] |= hex_value; } else { lost_fraction = trailingHexadecimalFraction(p, end, hex_value); - while(p != end && hexDigitValue(*p) != -1U) + while (p != end && hexDigitValue(*p) != -1U) p++; break; } @@ -2251,7 +2249,7 @@ APFloat::convertFromHexadecimalString(const StringRef &s, assert((dot == end || p - begin != 1) && "Significand has no digits"); /* Ignore the exponent if we are zero. */ - if(p != firstSignificantDigit) { + if (p != firstSignificantDigit) { int expAdjustment; /* Implicit hexadecimal point? */ @@ -2261,7 +2259,7 @@ APFloat::convertFromHexadecimalString(const StringRef &s, /* Calculate the exponent adjustment implicit in the number of significant digits. */ expAdjustment = static_cast<int>(dot - firstSignificantDigit); - if(expAdjustment < 0) + if (expAdjustment < 0) expAdjustment++; expAdjustment = expAdjustment * 4 - 1; @@ -2287,8 +2285,8 @@ APFloat::roundSignificandWithExponent(const integerPart *decSigParts, integerPart pow5Parts[maxPowerOfFiveParts]; bool isNearest; - isNearest = (rounding_mode == rmNearestTiesToEven - || rounding_mode == rmNearestTiesToAway); + isNearest = (rounding_mode == rmNearestTiesToEven || + rounding_mode == rmNearestTiesToAway); parts = partCountForBits(semantics->precision + 11); @@ -2482,13 +2480,13 @@ APFloat::convertFromString(const StringRef &str, roundingMode rounding_mode) StringRef::iterator p = str.begin(); size_t slen = str.size(); sign = *p == '-' ? 1 : 0; - if(*p == '-' || *p == '+') { + if (*p == '-' || *p == '+') { p++; slen--; assert(slen && "String has no digits"); } - if(slen >= 2 && p[0] == '0' && (p[1] == 'x' || p[1] == 'X')) { + if (slen >= 2 && p[0] == '0' && (p[1] == 'x' || p[1] == 'X')) { assert(slen - 2 && "Invalid string"); return convertFromHexadecimalString(StringRef(p + 2, slen - 2), rounding_mode); @@ -3013,7 +3011,7 @@ APFloat::initFromPPCDoubleDoubleAPInt(const APInt &api) // exponent2 and significand2 are required to be 0; we don't check category = fcInfinity; } else if (myexponent==0x7ff && mysignificand!=0) { - // exponent meaningless. So is the whole second word, but keep it + // exponent meaningless. So is the whole second word, but keep it // for determinism. category = fcNaN; exponent2 = myexponent2; @@ -3031,7 +3029,7 @@ APFloat::initFromPPCDoubleDoubleAPInt(const APInt &api) exponent = -1022; else significandParts()[0] |= 0x10000000000000LL; // integer bit - if (myexponent2==0) + if (myexponent2==0) exponent2 = -1022; else significandParts()[1] |= 0x10000000000000LL; // integer bit @@ -3217,8 +3215,8 @@ APFloat APFloat::getLargest(const fltSemantics &Sem, bool Negative) { significand[i] = ~((integerPart) 0); // ...and then clear the top bits for internal consistency. - significand[N-1] - &= (((integerPart) 1) << ((Sem.precision % integerPartWidth) - 1)) - 1; + significand[N-1] &= + (((integerPart) 1) << ((Sem.precision % integerPartWidth) - 1)) - 1; return Val; } @@ -3247,8 +3245,8 @@ APFloat APFloat::getSmallestNormalized(const fltSemantics &Sem, bool Negative) { Val.exponent = Sem.minExponent; Val.zeroSignificand(); - Val.significandParts()[partCountForBits(Sem.precision)-1] - |= (((integerPart) 1) << ((Sem.precision % integerPartWidth) - 1)); + Val.significandParts()[partCountForBits(Sem.precision)-1] |= + (((integerPart) 1) << ((Sem.precision % integerPartWidth) - 1)); return Val; } @@ -3433,7 +3431,7 @@ void APFloat::toString(SmallVectorImpl<char> &Str, // log2(N * 5^e) == log2(N) + e * log2(5) // <= semantics->precision + e * 137 / 59 // (log_2(5) ~ 2.321928 < 2.322034 ~ 137/59) - + unsigned precision = semantics->precision + 137 * texp / 59; // Multiply significand by 5^e. @@ -3442,7 +3440,7 @@ void APFloat::toString(SmallVectorImpl<char> &Str, APInt five_to_the_i(precision, 5); while (true) { if (texp & 1) significand *= five_to_the_i; - + texp >>= 1; if (!texp) break; five_to_the_i *= five_to_the_i; diff --git a/lib/Support/APInt.cpp b/lib/Support/APInt.cpp index 6a6384aa3f..50025d214b 100644 --- a/lib/Support/APInt.cpp +++ b/lib/Support/APInt.cpp @@ -702,15 +702,14 @@ static inline uint32_t hashword(const uint64_t *k64, size_t length) a = b = c = 0xdeadbeef + (((uint32_t)length)<<2); /*------------------------------------------------- handle most of the key */ - while (length > 3) - { - a += k[0]; - b += k[1]; - c += k[2]; - mix(a,b,c); - length -= 3; - k += 3; - } + while (length > 3) { + a += k[0]; + b += k[1]; + c += k[2]; + mix(a,b,c); + length -= 3; + k += 3; + } /*------------------------------------------- handle the last 3 uint32_t's */ switch (length) { /* all the case statements fall through */ @@ -1383,8 +1382,8 @@ APInt APInt::sqrt() const { // libc sqrt function which will probably use a hardware sqrt computation. // This should be faster than the algorithm below. if (magnitude < 52) { -#ifdef _MSC_VER - // Amazingly, VC++ doesn't have round(). +#if defined( _MSC_VER ) || defined(_MINIX) + // Amazingly, VC++ and Minix don't have round(). return APInt(BitWidth, uint64_t(::sqrt(double(isSingleWord()?VAL:pVal[0]))) + 0.5); #else @@ -2065,8 +2064,8 @@ void APInt::fromString(unsigned numbits, const StringRef& str, uint8_t radix) { assert((slen <= numbits || radix != 2) && "Insufficient bit width"); assert(((slen-1)*3 <= numbits || radix != 8) && "Insufficient bit width"); assert(((slen-1)*4 <= numbits || radix != 16) && "Insufficient bit width"); - assert((((slen-1)*64)/22 <= numbits || radix != 10) - && "Insufficient bit width"); + assert((((slen-1)*64)/22 <= numbits || radix != 10) && + "Insufficient bit width"); // Allocate memory if (!isSingleWord()) @@ -2229,7 +2228,7 @@ namespace { static inline integerPart lowBitMask(unsigned int bits) { - assert (bits != 0 && bits <= integerPartWidth); + assert(bits != 0 && bits <= integerPartWidth); return ~(integerPart) 0 >> (integerPartWidth - bits); } @@ -2306,10 +2305,10 @@ APInt::tcSet(integerPart *dst, integerPart part, unsigned int parts) { unsigned int i; - assert (parts > 0); + assert(parts > 0); dst[0] = part; - for(i = 1; i < parts; i++) + for (i = 1; i < parts; i++) dst[i] = 0; } @@ -2319,7 +2318,7 @@ APInt::tcAssign(integerPart *dst, const integerPart *src, unsigned int parts) { unsigned int i; - for(i = 0; i < parts; i++) + for (i = 0; i < parts; i++) dst[i] = src[i]; } @@ -2329,7 +2328,7 @@ APInt::tcIsZero(const integerPart *src, unsigned int parts) { unsigned int i; - for(i = 0; i < parts; i++) + for (i = 0; i < parts; i++) if (src[i]) return false; @@ -2340,8 +2339,8 @@ APInt::tcIsZero(const integerPart *src, unsigned int parts) int APInt::tcExtractBit(const integerPart *parts, unsigned int bit) { - return(parts[bit / integerPartWidth] - & ((integerPart) 1 << bit % integerPartWidth)) != 0; + return (parts[bit / integerPartWidth] & + ((integerPart) 1 << bit % integerPartWidth)) != 0; } /* Set the given bit of a bignum. */ @@ -2366,7 +2365,7 @@ APInt::tcLSB(const integerPart *parts, unsigned int n) { unsigned int i, lsb; - for(i = 0; i < n; i++) { + for (i = 0; i < n; i++) { if (parts[i] != 0) { lsb = partLSB(parts[i]); @@ -2385,13 +2384,13 @@ APInt::tcMSB(const integerPart *parts, unsigned int n) unsigned int msb; do { - --n; + --n; - if (parts[n] != 0) { - msb = partMSB(parts[n]); + if (parts[n] != 0) { + msb = partMSB(parts[n]); - return msb + n * integerPartWidth; - } + return msb + n * integerPartWidth; + } } while (n); return -1U; @@ -2408,7 +2407,7 @@ APInt::tcExtract(integerPart *dst, unsigned int dstCount,const integerPart *src, unsigned int firstSrcPart, dstParts, shift, n; dstParts = (srcBits + integerPartWidth - 1) / integerPartWidth; - assert (dstParts <= dstCount); + assert(dstParts <= dstCount); firstSrcPart = srcLSB / integerPartWidth; tcAssign (dst, src + firstSrcPart, dstParts); @@ -2443,7 +2442,7 @@ APInt::tcAdd(integerPart *dst, const integerPart *rhs, assert(c <= 1); - for(i = 0; i < parts; i++) { + for (i = 0; i < parts; i++) { integerPart l; l = dst[i]; @@ -2468,7 +2467,7 @@ APInt::tcSubtract(integerPart *dst, const integerPart *rhs, assert(c <= 1); - for(i = 0; i < parts; i++) { + for (i = 0; i < parts; i++) { integerPart l; l = dst[i]; @@ -2518,7 +2517,7 @@ APInt::tcMultiplyPart(integerPart *dst, const integerPart *src, /* N loops; minimum of dstParts and srcParts. */ n = dstParts < srcParts ? dstParts: srcParts; - for(i = 0; i < n; i++) { + for (i = 0; i < n; i++) { integerPart low, mid, high, srcPart; /* [ LOW, HIGH ] = MULTIPLIER * SRC[i] + DST[i] + CARRY. @@ -2583,7 +2582,7 @@ APInt::tcMultiplyPart(integerPart *dst, const integerPart *src, non-zero. This is true if any remaining src parts are non-zero and the multiplier is non-zero. */ if (multiplier) - for(; i < srcParts; i++) + for (; i < srcParts; i++) if (src[i]) return 1; @@ -2608,7 +2607,7 @@ APInt::tcMultiply(integerPart *dst, const integerPart *lhs, overflow = 0; tcSet(dst, 0, parts); - for(i = 0; i < parts; i++) + for (i = 0; i < parts; i++) overflow |= tcMultiplyPart(&dst[i], lhs, rhs[i], 0, parts, parts - i, true); @@ -2634,7 +2633,7 @@ APInt::tcFullMultiply(integerPart *dst, const integerPart *lhs, tcSet(dst, 0, rhsParts); - for(n = 0; n < lhsParts; n++) + for (n = 0; n < lhsParts; n++) tcMultiplyPart(&dst[n], rhs, lhs[n], 0, rhsParts, rhsParts + 1, true); n = lhsParts + rhsParts; @@ -2678,7 +2677,7 @@ APInt::tcDivide(integerPart *lhs, const integerPart *rhs, /* Loop, subtracting SRHS if REMAINDER is greater and adding that to the total. */ - for(;;) { + for (;;) { int compare; compare = tcCompare(remainder, srhs, parts); @@ -2746,7 +2745,7 @@ APInt::tcShiftRight(integerPart *dst, unsigned int parts, unsigned int count) /* Perform the shift. This leaves the most significant COUNT bits of the result at zero. */ - for(i = 0; i < parts; i++) { + for (i = 0; i < parts; i++) { integerPart part; if (i + jump >= parts) { @@ -2771,7 +2770,7 @@ APInt::tcAnd(integerPart *dst, const integerPart *rhs, unsigned int parts) { unsigned int i; - for(i = 0; i < parts; i++) + for (i = 0; i < parts; i++) dst[i] &= rhs[i]; } @@ -2781,7 +2780,7 @@ APInt::tcOr(integerPart *dst, const integerPart *rhs, unsigned int parts) { unsigned int i; - for(i = 0; i < parts; i++) + for (i = 0; i < parts; i++) dst[i] |= rhs[i]; } @@ -2791,7 +2790,7 @@ APInt::tcXor(integerPart *dst, const integerPart *rhs, unsigned int parts) { unsigned int i; - for(i = 0; i < parts; i++) + for (i = 0; i < parts; i++) dst[i] ^= rhs[i]; } @@ -2801,7 +2800,7 @@ APInt::tcComplement(integerPart *dst, unsigned int parts) { unsigned int i; - for(i = 0; i < parts; i++) + for (i = 0; i < parts; i++) dst[i] = ~dst[i]; } @@ -2830,7 +2829,7 @@ APInt::tcIncrement(integerPart *dst, unsigned int parts) { unsigned int i; - for(i = 0; i < parts; i++) + for (i = 0; i < parts; i++) if (++dst[i] != 0) break; diff --git a/lib/Support/Allocator.cpp b/lib/Support/Allocator.cpp index 31b45c8d4a..90df262336 100644 --- a/lib/Support/Allocator.cpp +++ b/lib/Support/Allocator.cpp @@ -23,9 +23,7 @@ namespace llvm { BumpPtrAllocator::BumpPtrAllocator(size_t size, size_t threshold, SlabAllocator &allocator) : SlabSize(size), SizeThreshold(threshold), Allocator(allocator), - CurSlab(0), BytesAllocated(0) { - StartNewSlab(); -} + CurSlab(0), BytesAllocated(0) { } BumpPtrAllocator::~BumpPtrAllocator() { DeallocateSlabs(CurSlab); @@ -72,6 +70,8 @@ void BumpPtrAllocator::DeallocateSlabs(MemSlab *Slab) { /// Reset - Deallocate all but the current slab and reset the current pointer /// to the beginning of it, freeing all memory allocated so far. void BumpPtrAllocator::Reset() { + if (!CurSlab) + return; DeallocateSlabs(CurSlab->NextPtr); CurSlab->NextPtr = 0; CurPtr = (char*)(CurSlab + 1); @@ -81,6 +81,9 @@ void BumpPtrAllocator::Reset() { /// Allocate - Allocate space at the specified alignment. /// void *BumpPtrAllocator::Allocate(size_t Size, size_t Alignment) { + if (!CurSlab) // Start a new slab if we haven't allocated one already. + StartNewSlab(); + // Keep track of how many bytes we've allocated. BytesAllocated += Size; diff --git a/lib/Support/CommandLine.cpp b/lib/Support/CommandLine.cpp index 2ab4103de2..d31f34ed66 100644 --- a/lib/Support/CommandLine.cpp +++ b/lib/Support/CommandLine.cpp @@ -676,8 +676,8 @@ void cl::ParseCommandLineOptions(int argc, char **argv, << " positional arguments: See: " << argv[0] << " -help\n"; ErrorParsing = true; - } else if (!HasUnlimitedPositionals - && PositionalVals.size() > PositionalOpts.size()) { + } else if (!HasUnlimitedPositionals && + PositionalVals.size() > PositionalOpts.size()) { errs() << ProgramName << ": Too many positional arguments specified!\n" << "Can specify at most " << PositionalOpts.size() diff --git a/lib/Support/Debug.cpp b/lib/Support/Debug.cpp index 82b4b8ce16..7f48f8aae7 100644 --- a/lib/Support/Debug.cpp +++ b/lib/Support/Debug.cpp @@ -51,12 +51,19 @@ DebugBufferSize("debug-buffer-size", cl::init(0)); static std::string CurrentDebugType; -static struct DebugOnlyOpt { + +namespace { + +struct DebugOnlyOpt { void operator=(const std::string &Val) const { DebugFlag |= !Val.empty(); CurrentDebugType = Val; } -} DebugOnlyOptLoc; +}; + +} + +static DebugOnlyOpt DebugOnlyOptLoc; static cl::opt<DebugOnlyOpt, true, cl::parser<std::string> > DebugOnly("debug-only", cl::desc("Enable a specific type of debug output"), @@ -64,8 +71,7 @@ DebugOnly("debug-only", cl::desc("Enable a specific type of debug output"), cl::location(DebugOnlyOptLoc), cl::ValueRequired); // Signal handlers - dump debug output on termination. -static void debug_user_sig_handler(void *Cookie) -{ +static void debug_user_sig_handler(void *Cookie) { // This is a bit sneaky. Since this is under #ifndef NDEBUG, we // know that debug mode is enabled and dbgs() really is a // circular_raw_ostream. If NDEBUG is defined, then dbgs() == diff --git a/lib/Support/Dwarf.cpp b/lib/Support/Dwarf.cpp index d1230b9de8..c19c2d6b08 100644 --- a/lib/Support/Dwarf.cpp +++ b/lib/Support/Dwarf.cpp @@ -196,8 +196,9 @@ const char *llvm::dwarf::AttributeString(unsigned Attribute) { case DW_AT_APPLE_flags: return "DW_AT_APPLE_flags"; case DW_AT_APPLE_isa: return "DW_AT_APPLE_isa"; case DW_AT_APPLE_block: return "DW_AT_APPLE_block"; - case DW_AT_APPLE_major_runtime_vers: return "DW_AT_APPLE_major_runtime_vers"; + case DW_AT_APPLE_major_runtime_vers: return "DW_AT_APPLE_major_runtime_vers"; case DW_AT_APPLE_runtime_class: return "DW_AT_APPLE_runtime_class"; + case DW_AT_APPLE_omit_frame_ptr: return "DW_AT_APPLE_omit_frame_ptr"; } return 0; } diff --git a/lib/Support/ErrorHandling.cpp b/lib/Support/ErrorHandling.cpp index 8bb156653a..56a171cb7d 100644 --- a/lib/Support/ErrorHandling.cpp +++ b/lib/Support/ErrorHandling.cpp @@ -1,4 +1,4 @@ -//===- lib/Support/ErrorHandling.cpp - Callbacks for errors -----*- C++ -*-===// +//===- lib/Support/ErrorHandling.cpp - Callbacks for errors ---------------===// // // The LLVM Compiler Infrastructure // @@ -7,9 +7,9 @@ // //===----------------------------------------------------------------------===// // -// This file defines an API for error handling, it supersedes cerr+abort(), and -// cerr+exit() style error handling. -// Callbacks can be registered for these errors through this API. +// This file defines an API used to indicate fatal error conditions. Non-fatal +// errors (most of them) should be handled through LLVMContext. +// //===----------------------------------------------------------------------===// #include "llvm/ADT/Twine.h" @@ -19,16 +19,14 @@ #include "llvm/System/Threading.h" #include <cassert> #include <cstdlib> - using namespace llvm; using namespace std; -static llvm_error_handler_t ErrorHandler = 0; +static fatal_error_handler_t ErrorHandler = 0; static void *ErrorHandlerUserData = 0; -namespace llvm { -void llvm_install_error_handler(llvm_error_handler_t handler, - void *user_data) { +void llvm::install_fatal_error_handler(fatal_error_handler_t handler, + void *user_data) { assert(!llvm_is_multithreaded() && "Cannot register error handlers after starting multithreaded mode!\n"); assert(!ErrorHandler && "Error handler already registered!\n"); @@ -36,19 +34,19 @@ void llvm_install_error_handler(llvm_error_handler_t handler, ErrorHandlerUserData = user_data; } -void llvm_remove_error_handler() { +void llvm::remove_fatal_error_handler() { ErrorHandler = 0; } -void llvm_report_error(const char *reason) { - llvm_report_error(Twine(reason)); +void llvm::report_fatal_error(const char *reason) { + report_fatal_error(Twine(reason)); } -void llvm_report_error(const std::string &reason) { - llvm_report_error(Twine(reason)); +void llvm::report_fatal_error(const std::string &reason) { + report_fatal_error(Twine(reason)); } -void llvm_report_error(const Twine &reason) { +void llvm::report_fatal_error(const Twine &reason) { if (!ErrorHandler) { errs() << "LLVM ERROR: " << reason << "\n"; } else { @@ -57,8 +55,8 @@ void llvm_report_error(const Twine &reason) { exit(1); } -void llvm_unreachable_internal(const char *msg, const char *file, - unsigned line) { +void llvm::llvm_unreachable_internal(const char *msg, const char *file, + unsigned line) { // This code intentionally doesn't call the ErrorHandler callback, because // llvm_unreachable is intended to be used to indicate "impossible" // situations, and not legitimate runtime errors. @@ -70,5 +68,3 @@ void llvm_unreachable_internal(const char *msg, const char *file, dbgs() << "!\n"; abort(); } -} - diff --git a/lib/Support/FoldingSet.cpp b/lib/Support/FoldingSet.cpp index 954dc77dff..3f467fe1b6 100644 --- a/lib/Support/FoldingSet.cpp +++ b/lib/Support/FoldingSet.cpp @@ -15,6 +15,7 @@ //===----------------------------------------------------------------------===// #include "llvm/ADT/FoldingSet.h" +#include "llvm/Support/Allocator.h" #include "llvm/Support/ErrorHandling.h" #include "llvm/Support/MathExtras.h" #include <cassert> @@ -130,6 +131,15 @@ bool FoldingSetNodeID::operator==(const FoldingSetNodeID &RHS)const{ return memcmp(&Bits[0], &RHS.Bits[0], Bits.size()*sizeof(Bits[0])) == 0; } +/// Intern - Copy this node's data to a memory region allocated from the +/// given allocator and return a FoldingSetNodeIDRef describing the +/// interned data. +FoldingSetNodeIDRef +FoldingSetNodeID::Intern(BumpPtrAllocator &Allocator) const { + unsigned *New = Allocator.Allocate<unsigned>(Bits.size()); + std::uninitialized_copy(Bits.begin(), Bits.end(), New); + return FoldingSetNodeIDRef(New, Bits.size()); +} //===----------------------------------------------------------------------===// /// Helper functions for FoldingSetImpl. diff --git a/lib/Support/GraphWriter.cpp b/lib/Support/GraphWriter.cpp index ec84f9beca..fdd6285a8c 100644 --- a/lib/Support/GraphWriter.cpp +++ b/lib/Support/GraphWriter.cpp @@ -130,28 +130,28 @@ void llvm::DisplayGraph(const sys::Path &Filename, bool wait, if (sys::Program::ExecuteAndWait(prog, &args[0], 0, 0, 0, 0, &ErrMsg)) { errs() << "Error viewing graph " << Filename.str() << ": '" << ErrMsg << "\n"; - } else { - errs() << " done. \n"; + return; + } + errs() << " done. \n"; - sys::Path gv(LLVM_PATH_GV); - args.clear(); - args.push_back(gv.c_str()); - args.push_back(PSFilename.c_str()); - args.push_back("--spartan"); - args.push_back(0); - - ErrMsg.clear(); - if (wait) { - if (sys::Program::ExecuteAndWait(gv, &args[0],0,0,0,0,&ErrMsg)) - errs() << "Error viewing graph: " << ErrMsg << "\n"; - Filename.eraseFromDisk(); - PSFilename.eraseFromDisk(); - } - else { - sys::Program::ExecuteNoWait(gv, &args[0],0,0,0,&ErrMsg); - errs() << "Remember to erase graph files: " << Filename.str() << " " - << PSFilename.str() << "\n"; - } + sys::Path gv(LLVM_PATH_GV); + args.clear(); + args.push_back(gv.c_str()); + args.push_back(PSFilename.c_str()); + args.push_back("--spartan"); + args.push_back(0); + + ErrMsg.clear(); + if (wait) { + if (sys::Program::ExecuteAndWait(gv, &args[0],0,0,0,0,&ErrMsg)) + errs() << "Error viewing graph: " << ErrMsg << "\n"; + Filename.eraseFromDisk(); + PSFilename.eraseFromDisk(); + } + else { + sys::Program::ExecuteNoWait(gv, &args[0],0,0,0,&ErrMsg); + errs() << "Remember to erase graph files: " << Filename.str() << " " + << PSFilename.str() << "\n"; } #elif HAVE_DOTTY sys::Path dotty(LLVM_PATH_DOTTY); @@ -166,7 +166,8 @@ void llvm::DisplayGraph(const sys::Path &Filename, bool wait, errs() << "Error viewing graph " << Filename.str() << ": " << ErrMsg << "\n"; } else { -#ifdef __MINGW32__ // Dotty spawns another app and doesn't wait until it returns +// Dotty spawns another app and doesn't wait until it returns +#if defined (__MINGW32__) || defined (_WINDOWS) return; #endif Filename.eraseFromDisk(); diff --git a/lib/Support/MemoryBuffer.cpp b/lib/Support/MemoryBuffer.cpp index eb046d0eaf..2b95089b52 100644 --- a/lib/Support/MemoryBuffer.cpp +++ b/lib/Support/MemoryBuffer.cpp @@ -14,6 +14,7 @@ #include "llvm/Support/MemoryBuffer.h" #include "llvm/ADT/OwningPtr.h" #include "llvm/ADT/SmallString.h" +#include "llvm/System/Errno.h" #include "llvm/System/Path.h" #include "llvm/System/Process.h" #include "llvm/System/Program.h" @@ -70,13 +71,12 @@ namespace { class MemoryBufferMem : public MemoryBuffer { std::string FileID; public: - MemoryBufferMem(const char *Start, const char *End, StringRef FID, - bool Copy = false) + MemoryBufferMem(StringRef InputData, StringRef FID, bool Copy = false) : FileID(FID) { if (!Copy) - init(Start, End); + init(InputData.data(), InputData.data()+InputData.size()); else - initCopyOf(Start, End); + initCopyOf(InputData.data(), InputData.data()+InputData.size()); } virtual const char *getBufferIdentifier() const { @@ -87,19 +87,17 @@ public: /// getMemBuffer - Open the specified memory range as a MemoryBuffer. Note /// that EndPtr[0] must be a null byte and be accessible! -MemoryBuffer *MemoryBuffer::getMemBuffer(const char *StartPtr, - const char *EndPtr, +MemoryBuffer *MemoryBuffer::getMemBuffer(StringRef InputData, const char *BufferName) { - return new MemoryBufferMem(StartPtr, EndPtr, BufferName); + return new MemoryBufferMem(InputData, BufferName); } /// getMemBufferCopy - Open the specified memory range as a MemoryBuffer, /// copying the contents and taking ownership of it. This has no requirements /// on EndPtr[0]. -MemoryBuffer *MemoryBuffer::getMemBufferCopy(const char *StartPtr, - const char *EndPtr, +MemoryBuffer *MemoryBuffer::getMemBufferCopy(StringRef InputData, const char *BufferName) { - return new MemoryBufferMem(StartPtr, EndPtr, BufferName, true); + return new MemoryBufferMem(InputData, BufferName, true); } /// getNewUninitMemBuffer - Allocate a new MemoryBuffer of the specified size @@ -111,7 +109,7 @@ MemoryBuffer *MemoryBuffer::getNewUninitMemBuffer(size_t Size, char *Buf = (char *)malloc(Size+1); if (!Buf) return 0; Buf[Size] = 0; - MemoryBufferMem *SB = new MemoryBufferMem(Buf, Buf+Size, BufferName); + MemoryBufferMem *SB = new MemoryBufferMem(StringRef(Buf, Size), BufferName); // The memory for this buffer is owned by the MemoryBuffer. SB->MustDeleteBuffer = true; return SB; @@ -136,10 +134,11 @@ MemoryBuffer *MemoryBuffer::getNewMemBuffer(size_t Size, /// returns an empty buffer. MemoryBuffer *MemoryBuffer::getFileOrSTDIN(StringRef Filename, std::string *ErrStr, - int64_t FileSize) { + int64_t FileSize, + struct stat *FileInfo) { if (Filename == "-") return getSTDIN(); - return getFile(Filename, ErrStr, FileSize); + return getFile(Filename, ErrStr, FileSize, FileInfo); } //===----------------------------------------------------------------------===// @@ -166,10 +165,18 @@ public: sys::Path::UnMapFilePages(getBufferStart(), getBufferSize()); } }; + +/// FileCloser - RAII object to make sure an FD gets closed properly. +class FileCloser { + int FD; +public: + FileCloser(int FD) : FD(FD) {} + ~FileCloser() { ::close(FD); } +}; } MemoryBuffer *MemoryBuffer::getFile(StringRef Filename, std::string *ErrStr, - int64_t FileSize) { + int64_t FileSize, struct stat *FileInfo) { int OpenFlags = 0; #ifdef O_BINARY OpenFlags |= O_BINARY; // Open input file in binary mode on win32. @@ -177,21 +184,23 @@ MemoryBuffer *MemoryBuffer::getFile(StringRef Filename, std::string *ErrStr, SmallString<256> PathBuf(Filename.begin(), Filename.end()); int FD = ::open(PathBuf.c_str(), O_RDONLY|OpenFlags); if (FD == -1) { - if (ErrStr) *ErrStr = strerror(errno); + if (ErrStr) *ErrStr = sys::StrError(); return 0; } + FileCloser FC(FD); // Close FD on return. // If we don't know the file size, use fstat to find out. fstat on an open // file descriptor is cheaper than stat on a random path. - if (FileSize == -1) { - struct stat FileInfo; + if (FileSize == -1 || FileInfo) { + struct stat MyFileInfo; + struct stat *FileInfoPtr = FileInfo? FileInfo : &MyFileInfo; + // TODO: This should use fstat64 when available. - if (fstat(FD, &FileInfo) == -1) { - if (ErrStr) *ErrStr = strerror(errno); - ::close(FD); + if (fstat(FD, FileInfoPtr) == -1) { + if (ErrStr) *ErrStr = sys::StrError(); return 0; } - FileSize = FileInfo.st_size; + FileSize = FileInfoPtr->st_size; } @@ -205,7 +214,6 @@ MemoryBuffer *MemoryBuffer::getFile(StringRef Filename, std::string *ErrStr, (FileSize & (sys::Process::GetPageSize()-1)) != 0) { if (const char *Pages = sys::Path::MapInFilePages(FD, FileSize)) { // Close the file descriptor, now that the whole file is in memory. - ::close(FD); return new MemoryBufferMMapFile(Filename, Pages, FileSize); } } @@ -214,30 +222,31 @@ MemoryBuffer *MemoryBuffer::getFile(StringRef Filename, std::string *ErrStr, if (!Buf) { // Failed to create a buffer. if (ErrStr) *ErrStr = "could not allocate buffer"; - ::close(FD); return 0; } OwningPtr<MemoryBuffer> SB(Buf); char *BufPtr = const_cast<char*>(SB->getBufferStart()); - + size_t BytesLeft = FileSize; while (BytesLeft) { ssize_t NumRead = ::read(FD, BufPtr, BytesLeft); - if (NumRead > 0) { - BytesLeft -= NumRead; - BufPtr += NumRead; - } else if (NumRead == -1 && errno == EINTR) { - // try again - } else { - // error reading. - if (ErrStr) *ErrStr = strerror(errno); - close(FD); + if (NumRead == -1) { + if (errno == EINTR) + continue; + // Error while reading. + if (ErrStr) *ErrStr = sys::StrError(); return 0; + } else if (NumRead == 0) { + // We hit EOF early, truncate and terminate buffer. + Buf->BufferEnd = BufPtr; + *BufPtr = 0; + return SB.take(); } + BytesLeft -= NumRead; + BufPtr += NumRead; } - close(FD); - + return SB.take(); } diff --git a/lib/Support/SourceMgr.cpp b/lib/Support/SourceMgr.cpp index 83c7964ca0..da5681c5bc 100644 --- a/lib/Support/SourceMgr.cpp +++ b/lib/Support/SourceMgr.cpp @@ -168,13 +168,21 @@ SMDiagnostic SourceMgr::GetMessage(SMLoc Loc, const std::string &Msg, } PrintedMsg += Msg; - return SMDiagnostic(CurMB->getBufferIdentifier(), FindLineNumber(Loc, CurBuf), + return SMDiagnostic(*this, Loc, + CurMB->getBufferIdentifier(), FindLineNumber(Loc, CurBuf), Loc.getPointer()-LineStart, PrintedMsg, LineStr, ShowLine); } void SourceMgr::PrintMessage(SMLoc Loc, const std::string &Msg, const char *Type, bool ShowLine) const { + // Report the message with the diagnostic handler if present. + if (DiagHandler) { + DiagHandler(GetMessage(Loc, Msg, Type, ShowLine), + DiagContext, DiagLocCookie); + return; + } + raw_ostream &OS = errs(); int CurBuf = FindBufferContainingLoc(Loc); diff --git a/lib/Support/Statistic.cpp b/lib/Support/Statistic.cpp index e787670459..7d5f65af28 100644 --- a/lib/Support/Statistic.cpp +++ b/lib/Support/Statistic.cpp @@ -32,8 +32,8 @@ #include <cstring> using namespace llvm; -// GetLibSupportInfoOutputFile - Return a file stream to print our output on. -namespace llvm { extern raw_ostream *GetLibSupportInfoOutputFile(); } +// CreateInfoOutputFile - Return a file stream to print our output on. +namespace llvm { extern raw_ostream *CreateInfoOutputFile(); } /// -stats - Command line option to cause transformations to emit stats about /// what they did. @@ -48,6 +48,8 @@ namespace { /// llvm_shutdown is called. We print statistics from the destructor. class StatisticInfo { std::vector<const Statistic*> Stats; + friend void llvm::PrintStatistics(); + friend void llvm::PrintStatistics(raw_ostream &OS); public: ~StatisticInfo(); @@ -92,42 +94,55 @@ struct NameCompare { // Print information when destroyed, iff command line option is specified. StatisticInfo::~StatisticInfo() { - // Statistics not enabled? - if (Stats.empty()) return; + llvm::PrintStatistics(); +} - // Get the stream to write to. - raw_ostream &OutStream = *GetLibSupportInfoOutputFile(); +void llvm::EnableStatistics() { + Enabled.setValue(true); +} + +void llvm::PrintStatistics(raw_ostream &OS) { + StatisticInfo &Stats = *StatInfo; // Figure out how long the biggest Value and Name fields are. unsigned MaxNameLen = 0, MaxValLen = 0; - for (size_t i = 0, e = Stats.size(); i != e; ++i) { + for (size_t i = 0, e = Stats.Stats.size(); i != e; ++i) { MaxValLen = std::max(MaxValLen, - (unsigned)utostr(Stats[i]->getValue()).size()); + (unsigned)utostr(Stats.Stats[i]->getValue()).size()); MaxNameLen = std::max(MaxNameLen, - (unsigned)std::strlen(Stats[i]->getName())); + (unsigned)std::strlen(Stats.Stats[i]->getName())); } // Sort the fields by name. - std::stable_sort(Stats.begin(), Stats.end(), NameCompare()); + std::stable_sort(Stats.Stats.begin(), Stats.Stats.end(), NameCompare()); // Print out the statistics header... - OutStream << "===" << std::string(73, '-') << "===\n" - << " ... Statistics Collected ...\n" - << "===" << std::string(73, '-') << "===\n\n"; + OS << "===" << std::string(73, '-') << "===\n" + << " ... Statistics Collected ...\n" + << "===" << std::string(73, '-') << "===\n\n"; // Print all of the statistics. - for (size_t i = 0, e = Stats.size(); i != e; ++i) { - std::string CountStr = utostr(Stats[i]->getValue()); - OutStream << std::string(MaxValLen-CountStr.size(), ' ') - << CountStr << " " << Stats[i]->getName() - << std::string(MaxNameLen-std::strlen(Stats[i]->getName()), ' ') - << " - " << Stats[i]->getDesc() << "\n"; - + for (size_t i = 0, e = Stats.Stats.size(); i != e; ++i) { + std::string CountStr = utostr(Stats.Stats[i]->getValue()); + OS << std::string(MaxValLen-CountStr.size(), ' ') + << CountStr << " " << Stats.Stats[i]->getName() + << std::string(MaxNameLen-std::strlen(Stats.Stats[i]->getName()), ' ') + << " - " << Stats.Stats[i]->getDesc() << "\n"; } - OutStream << '\n'; // Flush the output stream... - OutStream.flush(); - - if (&OutStream != &outs() && &OutStream != &errs() && &OutStream != &dbgs()) - delete &OutStream; // Close the file. + OS << '\n'; // Flush the output stream. + OS.flush(); + +} + +void llvm::PrintStatistics() { + StatisticInfo &Stats = *StatInfo; + + // Statistics not enabled? + if (Stats.Stats.empty()) return; + + // Get the stream to write to. + raw_ostream &OutStream = *CreateInfoOutputFile(); + PrintStatistics(OutStream); + delete &OutStream; // Close the file. } diff --git a/lib/Support/Timer.cpp b/lib/Support/Timer.cpp index 4bdfac298c..3a8cb74a1d 100644 --- a/lib/Support/Timer.cpp +++ b/lib/Support/Timer.cpp @@ -11,20 +11,20 @@ // //===----------------------------------------------------------------------===// -#include "llvm/Support/Debug.h" #include "llvm/Support/Timer.h" #include "llvm/Support/CommandLine.h" +#include "llvm/Support/Debug.h" #include "llvm/Support/ManagedStatic.h" #include "llvm/Support/raw_ostream.h" #include "llvm/Support/Format.h" +#include "llvm/System/Mutex.h" #include "llvm/System/Process.h" -#include <algorithm> -#include <functional> -#include <map> +#include "llvm/ADT/OwningPtr.h" +#include "llvm/ADT/StringMap.h" using namespace llvm; -// GetLibSupportInfoOutputFile - Return a file stream to print our output on. -namespace llvm { extern raw_ostream *GetLibSupportInfoOutputFile(); } +// CreateInfoOutputFile - Return a file stream to print our output on. +namespace llvm { extern raw_ostream *CreateInfoOutputFile(); } // getLibSupportInfoOutputFilename - This ugly hack is brought to you courtesy // of constructor/destructor ordering being unspecified by C++. Basically the @@ -53,117 +53,103 @@ namespace { cl::Hidden, cl::location(getLibSupportInfoOutputFilename())); } +// CreateInfoOutputFile - Return a file stream to print our output on. +raw_ostream *llvm::CreateInfoOutputFile() { + const std::string &OutputFilename = getLibSupportInfoOutputFilename(); + if (OutputFilename.empty()) + return new raw_fd_ostream(2, false); // stderr. + if (OutputFilename == "-") + return new raw_fd_ostream(1, false); // stdout. + + std::string Error; + raw_ostream *Result = new raw_fd_ostream(OutputFilename.c_str(), + Error, raw_fd_ostream::F_Append); + if (Error.empty()) + return Result; + + errs() << "Error opening info-output-file '" + << OutputFilename << " for appending!\n"; + delete Result; + return new raw_fd_ostream(2, false); // stderr. +} + + static TimerGroup *DefaultTimerGroup = 0; static TimerGroup *getDefaultTimerGroup() { - TimerGroup* tmp = DefaultTimerGroup; + TimerGroup *tmp = DefaultTimerGroup; sys::MemoryFence(); + if (tmp) return tmp; + + llvm_acquire_global_lock(); + tmp = DefaultTimerGroup; if (!tmp) { - llvm_acquire_global_lock(); - tmp = DefaultTimerGroup; - if (!tmp) { - tmp = new TimerGroup("Miscellaneous Ungrouped Timers"); - sys::MemoryFence(); - DefaultTimerGroup = tmp; - } - llvm_release_global_lock(); + tmp = new TimerGroup("Miscellaneous Ungrouped Timers"); + sys::MemoryFence(); + DefaultTimerGroup = tmp; } + llvm_release_global_lock(); return tmp; } -Timer::Timer(const std::string &N) - : Elapsed(0), UserTime(0), SystemTime(0), MemUsed(0), PeakMem(0), Name(N), - Started(false), TG(getDefaultTimerGroup()) { - TG->addTimer(); -} - -Timer::Timer(const std::string &N, TimerGroup &tg) - : Elapsed(0), UserTime(0), SystemTime(0), MemUsed(0), PeakMem(0), Name(N), - Started(false), TG(&tg) { - TG->addTimer(); -} +//===----------------------------------------------------------------------===// +// Timer Implementation +//===----------------------------------------------------------------------===// -Timer::Timer(const Timer &T) { - TG = T.TG; - if (TG) TG->addTimer(); - operator=(T); +void Timer::init(StringRef N) { + assert(TG == 0 && "Timer already initialized"); + Name.assign(N.begin(), N.end()); + Started = false; + TG = getDefaultTimerGroup(); + TG->addTimer(*this); } - -// Copy ctor, initialize with no TG member. -Timer::Timer(bool, const Timer &T) { - TG = T.TG; // Avoid assertion in operator= - operator=(T); // Copy contents - TG = 0; +void Timer::init(StringRef N, TimerGroup &tg) { + assert(TG == 0 && "Timer already initialized"); + Name.assign(N.begin(), N.end()); + Started = false; + TG = &tg; + TG->addTimer(*this); } - Timer::~Timer() { - if (TG) { - if (Started) { - Started = false; - TG->addTimerToPrint(*this); - } - TG->removeTimer(); - } + if (!TG) return; // Never initialized, or already cleared. + TG->removeTimer(*this); } static inline size_t getMemUsage() { - if (TrackSpace) - return sys::Process::GetMallocUsage(); - return 0; + if (!TrackSpace) return 0; + return sys::Process::GetMallocUsage(); } -struct TimeRecord { - double Elapsed, UserTime, SystemTime; - ssize_t MemUsed; -}; - -static TimeRecord getTimeRecord(bool Start) { +TimeRecord TimeRecord::getCurrentTime(bool Start) { TimeRecord Result; - - sys::TimeValue now(0,0); - sys::TimeValue user(0,0); - sys::TimeValue sys(0,0); - - ssize_t MemUsed = 0; + sys::TimeValue now(0,0), user(0,0), sys(0,0); + if (Start) { - MemUsed = getMemUsage(); - sys::Process::GetTimeUsage(now,user,sys); + Result.MemUsed = getMemUsage(); + sys::Process::GetTimeUsage(now, user, sys); } else { - sys::Process::GetTimeUsage(now,user,sys); - MemUsed = getMemUsage(); + sys::Process::GetTimeUsage(now, user, sys); + Result.MemUsed = getMemUsage(); } - Result.Elapsed = now.seconds() + now.microseconds() / 1000000.0; - Result.UserTime = user.seconds() + user.microseconds() / 1000000.0; - Result.SystemTime = sys.seconds() + sys.microseconds() / 1000000.0; - Result.MemUsed = MemUsed; - + Result.WallTime = now.seconds() + now.microseconds() / 1000000.0; + Result.UserTime = user.seconds() + user.microseconds() / 1000000.0; + Result.SystemTime = sys.seconds() + sys.microseconds() / 1000000.0; return Result; } static ManagedStatic<std::vector<Timer*> > ActiveTimers; void Timer::startTimer() { - sys::SmartScopedLock<true> L(*TimerLock); Started = true; ActiveTimers->push_back(this); - TimeRecord TR = getTimeRecord(true); - Elapsed -= TR.Elapsed; - UserTime -= TR.UserTime; - SystemTime -= TR.SystemTime; - MemUsed -= TR.MemUsed; - PeakMemBase = TR.MemUsed; + Time -= TimeRecord::getCurrentTime(true); } void Timer::stopTimer() { - sys::SmartScopedLock<true> L(*TimerLock); - TimeRecord TR = getTimeRecord(false); - Elapsed += TR.Elapsed; - UserTime += TR.UserTime; - SystemTime += TR.SystemTime; - MemUsed += TR.MemUsed; + Time += TimeRecord::getCurrentTime(false); if (ActiveTimers->back() == this) { ActiveTimers->pop_back(); @@ -175,217 +161,227 @@ void Timer::stopTimer() { } } -void Timer::sum(const Timer &T) { - Elapsed += T.Elapsed; - UserTime += T.UserTime; - SystemTime += T.SystemTime; - MemUsed += T.MemUsed; - PeakMem += T.PeakMem; +static void printVal(double Val, double Total, raw_ostream &OS) { + if (Total < 1e-7) // Avoid dividing by zero. + OS << " ----- "; + else { + OS << " " << format("%7.4f", Val) << " ("; + OS << format("%5.1f", Val*100/Total) << "%)"; + } } -/// addPeakMemoryMeasurement - This method should be called whenever memory -/// usage needs to be checked. It adds a peak memory measurement to the -/// currently active timers, which will be printed when the timer group prints -/// -void Timer::addPeakMemoryMeasurement() { - sys::SmartScopedLock<true> L(*TimerLock); - size_t MemUsed = getMemUsage(); - - for (std::vector<Timer*>::iterator I = ActiveTimers->begin(), - E = ActiveTimers->end(); I != E; ++I) - (*I)->PeakMem = std::max((*I)->PeakMem, MemUsed-(*I)->PeakMemBase); +void TimeRecord::print(const TimeRecord &Total, raw_ostream &OS) const { + if (Total.getUserTime()) + printVal(getUserTime(), Total.getUserTime(), OS); + if (Total.getSystemTime()) + printVal(getSystemTime(), Total.getSystemTime(), OS); + if (Total.getProcessTime()) + printVal(getProcessTime(), Total.getProcessTime(), OS); + printVal(getWallTime(), Total.getWallTime(), OS); + + OS << " "; + + if (Total.getMemUsed()) + OS << format("%9lld", (long long)getMemUsed()) << " "; } + //===----------------------------------------------------------------------===// // NamedRegionTimer Implementation //===----------------------------------------------------------------------===// namespace { -typedef std::map<std::string, Timer> Name2Timer; -typedef std::map<std::string, std::pair<TimerGroup, Name2Timer> > Name2Pair; +typedef StringMap<Timer> Name2TimerMap; -} - -static ManagedStatic<Name2Timer> NamedTimers; - -static ManagedStatic<Name2Pair> NamedGroupedTimers; - -static Timer &getNamedRegionTimer(const std::string &Name) { - sys::SmartScopedLock<true> L(*TimerLock); - Name2Timer::iterator I = NamedTimers->find(Name); - if (I != NamedTimers->end()) - return I->second; +class Name2PairMap { + StringMap<std::pair<TimerGroup*, Name2TimerMap> > Map; +public: + ~Name2PairMap() { + for (StringMap<std::pair<TimerGroup*, Name2TimerMap> >::iterator + I = Map.begin(), E = Map.end(); I != E; ++I) + delete I->second.first; + } + + Timer &get(StringRef Name, StringRef GroupName) { + sys::SmartScopedLock<true> L(*TimerLock); + + std::pair<TimerGroup*, Name2TimerMap> &GroupEntry = Map[GroupName]; + + if (!GroupEntry.first) + GroupEntry.first = new TimerGroup(GroupName); + + Timer &T = GroupEntry.second[Name]; + if (!T.isInitialized()) + T.init(Name, *GroupEntry.first); + return T; + } +}; - return NamedTimers->insert(I, std::make_pair(Name, Timer(Name)))->second; } -static Timer &getNamedRegionTimer(const std::string &Name, - const std::string &GroupName) { - sys::SmartScopedLock<true> L(*TimerLock); - - Name2Pair::iterator I = NamedGroupedTimers->find(GroupName); - if (I == NamedGroupedTimers->end()) { - TimerGroup TG(GroupName); - std::pair<TimerGroup, Name2Timer> Pair(TG, Name2Timer()); - I = NamedGroupedTimers->insert(I, std::make_pair(GroupName, Pair)); - } +static ManagedStatic<Name2TimerMap> NamedTimers; +static ManagedStatic<Name2PairMap> NamedGroupedTimers; - Name2Timer::iterator J = I->second.second.find(Name); - if (J == I->second.second.end()) - J = I->second.second.insert(J, - std::make_pair(Name, - Timer(Name, - I->second.first))); - - return J->second; +static Timer &getNamedRegionTimer(StringRef Name) { + sys::SmartScopedLock<true> L(*TimerLock); + + Timer &T = (*NamedTimers)[Name]; + if (!T.isInitialized()) + T.init(Name); + return T; } -NamedRegionTimer::NamedRegionTimer(const std::string &Name) +NamedRegionTimer::NamedRegionTimer(StringRef Name) : TimeRegion(getNamedRegionTimer(Name)) {} -NamedRegionTimer::NamedRegionTimer(const std::string &Name, - const std::string &GroupName) - : TimeRegion(getNamedRegionTimer(Name, GroupName)) {} +NamedRegionTimer::NamedRegionTimer(StringRef Name, StringRef GroupName) + : TimeRegion(NamedGroupedTimers->get(Name, GroupName)) {} //===----------------------------------------------------------------------===// // TimerGroup Implementation //===----------------------------------------------------------------------===// +/// TimerGroupList - This is the global list of TimerGroups, maintained by the +/// TimerGroup ctor/dtor and is protected by the TimerLock lock. +static TimerGroup *TimerGroupList = 0; -static void printVal(double Val, double Total, raw_ostream &OS) { - if (Total < 1e-7) // Avoid dividing by zero... - OS << " ----- "; - else { - OS << " " << format("%7.4f", Val) << " ("; - OS << format("%5.1f", Val*100/Total) << "%)"; - } +TimerGroup::TimerGroup(StringRef name) + : Name(name.begin(), name.end()), FirstTimer(0) { + + // Add the group to TimerGroupList. + sys::SmartScopedLock<true> L(*TimerLock); + if (TimerGroupList) + TimerGroupList->Prev = &Next; + Next = TimerGroupList; + Prev = &TimerGroupList; + TimerGroupList = this; } -void Timer::print(const Timer &Total, raw_ostream &OS) { +TimerGroup::~TimerGroup() { + // If the timer group is destroyed before the timers it owns, accumulate and + // print the timing data. + while (FirstTimer != 0) + removeTimer(*FirstTimer); + + // Remove the group from the TimerGroupList. sys::SmartScopedLock<true> L(*TimerLock); - if (Total.UserTime) - printVal(UserTime, Total.UserTime, OS); - if (Total.SystemTime) - printVal(SystemTime, Total.SystemTime, OS); - if (Total.getProcessTime()) - printVal(getProcessTime(), Total.getProcessTime(), OS); - printVal(Elapsed, Total.Elapsed, OS); - - OS << " "; - - if (Total.MemUsed) { - OS << format("%9lld", (long long)MemUsed) << " "; - } - if (Total.PeakMem) { - if (PeakMem) { - OS << format("%9lld", (long long)PeakMem) << " "; - } else - OS << " "; - } - OS << Name << "\n"; - - Started = false; // Once printed, don't print again + *Prev = Next; + if (Next) + Next->Prev = Prev; } -// GetLibSupportInfoOutputFile - Return a file stream to print our output on... -raw_ostream * -llvm::GetLibSupportInfoOutputFile() { - std::string &LibSupportInfoOutputFilename = getLibSupportInfoOutputFilename(); - if (LibSupportInfoOutputFilename.empty()) - return &errs(); - if (LibSupportInfoOutputFilename == "-") - return &outs(); - - std::string Error; - raw_ostream *Result = new raw_fd_ostream(LibSupportInfoOutputFilename.c_str(), - Error, raw_fd_ostream::F_Append); - if (Error.empty()) - return Result; - - errs() << "Error opening info-output-file '" - << LibSupportInfoOutputFilename << " for appending!\n"; - delete Result; - return &errs(); +void TimerGroup::removeTimer(Timer &T) { + sys::SmartScopedLock<true> L(*TimerLock); + + // If the timer was started, move its data to TimersToPrint. + if (T.Started) + TimersToPrint.push_back(TimersToPrintEntry(T.Time, T.Name)); + + T.TG = 0; + + // Unlink the timer from our list. + *T.Prev = T.Next; + if (T.Next) + T.Next->Prev = T.Prev; + + // Print the report when all timers in this group are destroyed if some of + // them were started. + if (FirstTimer != 0 || TimersToPrint.empty()) + return; + + raw_ostream *OutStream = CreateInfoOutputFile(); + PrintQueuedTimers(*OutStream); + delete OutStream; // Close the file. } - -void TimerGroup::removeTimer() { +void TimerGroup::addTimer(Timer &T) { sys::SmartScopedLock<true> L(*TimerLock); - if (--NumTimers == 0 && !TimersToPrint.empty()) { // Print timing report... - // Sort the timers in descending order by amount of time taken... - std::sort(TimersToPrint.begin(), TimersToPrint.end(), - std::greater<Timer>()); - - // Figure out how many spaces to indent TimerGroup name... - unsigned Padding = (80-Name.length())/2; - if (Padding > 80) Padding = 0; // Don't allow "negative" numbers - - raw_ostream *OutStream = GetLibSupportInfoOutputFile(); - - ++NumTimers; - { // Scope to contain Total timer... don't allow total timer to drop us to - // zero timers... - Timer Total("TOTAL"); - - for (unsigned i = 0, e = TimersToPrint.size(); i != e; ++i) - Total.sum(TimersToPrint[i]); - - // Print out timing header... - *OutStream << "===" << std::string(73, '-') << "===\n" - << std::string(Padding, ' ') << Name << "\n" - << "===" << std::string(73, '-') - << "===\n"; - - // If this is not an collection of ungrouped times, print the total time. - // Ungrouped timers don't really make sense to add up. We still print the - // TOTAL line to make the percentages make sense. - if (this != DefaultTimerGroup) { - *OutStream << " Total Execution Time: "; - - *OutStream << format("%5.4f", Total.getProcessTime()) << " seconds ("; - *OutStream << format("%5.4f", Total.getWallTime()) << " wall clock)\n"; - } - *OutStream << "\n"; - - if (Total.UserTime) - *OutStream << " ---User Time---"; - if (Total.SystemTime) - *OutStream << " --System Time--"; - if (Total.getProcessTime()) - *OutStream << " --User+System--"; - *OutStream << " ---Wall Time---"; - if (Total.getMemUsed()) - *OutStream << " ---Mem---"; - if (Total.getPeakMem()) - *OutStream << " -PeakMem-"; - *OutStream << " --- Name ---\n"; - - // Loop through all of the timing data, printing it out... - for (unsigned i = 0, e = TimersToPrint.size(); i != e; ++i) - TimersToPrint[i].print(Total, *OutStream); - - Total.print(Total, *OutStream); - *OutStream << '\n'; - OutStream->flush(); - } - --NumTimers; - - TimersToPrint.clear(); - - if (OutStream != &errs() && OutStream != &outs() && OutStream != &dbgs()) - delete OutStream; // Close the file... + + // Add the timer to our list. + if (FirstTimer) + FirstTimer->Prev = &T.Next; + T.Next = FirstTimer; + T.Prev = &FirstTimer; + FirstTimer = &T; +} + +void TimerGroup::PrintQueuedTimers(raw_ostream &OS) { + // Sort the timers in descending order by amount of time taken. + std::sort(TimersToPrint.begin(), TimersToPrint.end()); + + TimeRecord Total; + for (unsigned i = 0, e = TimersToPrint.size(); i != e; ++i) + Total += TimersToPrint[i].Time; + + // Print out timing header. + OS << "===" << std::string(73, '-') << "===\n"; + // Figure out how many spaces to indent TimerGroup name. + unsigned Padding = (80-Name.length())/2; + if (Padding > 80) Padding = 0; // Don't allow "negative" numbers + OS.indent(Padding) << Name << '\n'; + OS << "===" << std::string(73, '-') << "===\n"; + + // If this is not an collection of ungrouped times, print the total time. + // Ungrouped timers don't really make sense to add up. We still print the + // TOTAL line to make the percentages make sense. + if (this != DefaultTimerGroup) { + OS << " Total Execution Time: "; + OS << format("%5.4f", Total.getProcessTime()) << " seconds ("; + OS << format("%5.4f", Total.getWallTime()) << " wall clock)\n"; + } + OS << '\n'; + + if (Total.getUserTime()) + OS << " ---User Time---"; + if (Total.getSystemTime()) + OS << " --System Time--"; + if (Total.getProcessTime()) + OS << " --User+System--"; + OS << " ---Wall Time---"; + if (Total.getMemUsed()) + OS << " ---Mem---"; + OS << " --- Name ---\n"; + + // Loop through all of the timing data, printing it out. + for (unsigned i = 0, e = TimersToPrint.size(); i != e; ++i) { + const TimersToPrintEntry &Entry = TimersToPrint[e-i-1]; + Entry.Time.print(Total, OS); + OS << Entry.Name << '\n'; } + + Total.print(Total, OS); + OS << "Total\n\n"; + OS.flush(); + + TimersToPrint.clear(); } -void TimerGroup::addTimer() { +/// print - Print any started timers in this group and zero them. +void TimerGroup::print(raw_ostream &OS) { sys::SmartScopedLock<true> L(*TimerLock); - ++NumTimers; + + // See if any of our timers were started, if so add them to TimersToPrint and + // reset them. + for (Timer *T = FirstTimer; T; T = T->Next) { + if (!T->Started) continue; + TimersToPrint.push_back(TimersToPrintEntry(T->Time, T->Name)); + + // Clear out the time. + T->Started = 0; + T->Time = TimeRecord(); + } + + // If any timers were started, print the group. + if (!TimersToPrint.empty()) + PrintQueuedTimers(OS); } -void TimerGroup::addTimerToPrint(const Timer &T) { +/// printAll - This static method prints all timers and clears them all out. +void TimerGroup::printAll(raw_ostream &OS) { sys::SmartScopedLock<true> L(*TimerLock); - TimersToPrint.push_back(Timer(true, T)); -} + for (TimerGroup *TG = TimerGroupList; TG; TG = TG->Next) + TG->print(OS); +} diff --git a/lib/Support/Triple.cpp b/lib/Support/Triple.cpp index 61bf0a73c9..9796ca56f4 100644 --- a/lib/Support/Triple.cpp +++ b/lib/Support/Triple.cpp @@ -189,7 +189,7 @@ Triple::ArchType Triple::getArchTypeForDarwinArchName(StringRef Str) { return Triple::UnknownArch; } -// Returns architecture name that is unsderstood by the target assembler. +// Returns architecture name that is understood by the target assembler. const char *Triple::getArchNameForAssembler() { if (getOS() != Triple::Darwin && getVendor() != Triple::Apple) return NULL; diff --git a/lib/Support/circular_raw_ostream.cpp b/lib/Support/circular_raw_ostream.cpp index e52996dc50..ca0d30db38 100644 --- a/lib/Support/circular_raw_ostream.cpp +++ b/lib/Support/circular_raw_ostream.cpp @@ -1,4 +1,4 @@ -//===- circulat_raw_ostream.cpp - Implement the circular_raw_ostream class -===// +//===- circular_raw_ostream.cpp - Implement circular_raw_ostream ----------===// // // The LLVM Compiler Infrastructure // @@ -12,9 +12,7 @@ //===----------------------------------------------------------------------===// #include "llvm/Support/circular_raw_ostream.h" - #include <algorithm> - using namespace llvm; void circular_raw_ostream::write_impl(const char *Ptr, size_t Size) { @@ -25,7 +23,8 @@ void circular_raw_ostream::write_impl(const char *Ptr, size_t Size) { // Write into the buffer, wrapping if necessary. while (Size != 0) { - unsigned Bytes = std::min(Size, BufferSize - (Cur - BufferArray)); + unsigned Bytes = + std::min(unsigned(Size), unsigned(BufferSize - (Cur - BufferArray))); memcpy(Cur, Ptr, Bytes); Size -= Bytes; Cur += Bytes; @@ -37,11 +36,10 @@ void circular_raw_ostream::write_impl(const char *Ptr, size_t Size) { } } -void circular_raw_ostream::flushBufferWithBanner(void) { +void circular_raw_ostream::flushBufferWithBanner() { if (BufferSize != 0) { // Write out the buffer - int num = std::strlen(Banner); - TheStream->write(Banner, num); + TheStream->write(Banner, std::strlen(Banner)); flushBuffer(); } } diff --git a/lib/Support/raw_ostream.cpp b/lib/Support/raw_ostream.cpp index 071c924d91..0b05c5449a 100644 --- a/lib/Support/raw_ostream.cpp +++ b/lib/Support/raw_ostream.cpp @@ -57,11 +57,11 @@ raw_ostream::~raw_ostream() { delete [] OutBufStart; // If there are any pending errors, report them now. Clients wishing - // to avoid llvm_report_error calls should check for errors with + // to avoid report_fatal_error calls should check for errors with // has_error() and clear the error flag with clear_error() before // destructing raw_ostream objects which may have errors. if (Error) - llvm_report_error("IO failure on output stream."); + report_fatal_error("IO failure on output stream."); } // An out of line virtual method to provide a home for the class vtable. @@ -81,9 +81,9 @@ void raw_ostream::SetBuffered() { SetUnbuffered(); } -void raw_ostream::SetBufferAndMode(char *BufferStart, size_t Size, +void raw_ostream::SetBufferAndMode(char *BufferStart, size_t Size, BufferKind Mode) { - assert(((Mode == Unbuffered && BufferStart == 0 && Size == 0) || + assert(((Mode == Unbuffered && BufferStart == 0 && Size == 0) || (Mode != Unbuffered && BufferStart && Size)) && "stream must be unbuffered or have at least one byte"); // Make sure the current buffer is free of content (we can't flush here; the @@ -104,11 +104,11 @@ raw_ostream &raw_ostream::operator<<(unsigned long N) { // Zero is a special case. if (N == 0) return *this << '0'; - + char NumberBuffer[20]; char *EndPtr = NumberBuffer+sizeof(NumberBuffer); char *CurPtr = EndPtr; - + while (N) { *--CurPtr = '0' + char(N % 10); N /= 10; @@ -121,7 +121,7 @@ raw_ostream &raw_ostream::operator<<(long N) { *this << '-'; N = -N; } - + return this->operator<<(static_cast<unsigned long>(N)); } @@ -133,7 +133,7 @@ raw_ostream &raw_ostream::operator<<(unsigned long long N) { char NumberBuffer[20]; char *EndPtr = NumberBuffer+sizeof(NumberBuffer); char *CurPtr = EndPtr; - + while (N) { *--CurPtr = '0' + char(N % 10); N /= 10; @@ -146,7 +146,7 @@ raw_ostream &raw_ostream::operator<<(long long N) { *this << '-'; N = -N; } - + return this->operator<<(static_cast<unsigned long long>(N)); } @@ -297,33 +297,33 @@ raw_ostream &raw_ostream::operator<<(const format_object_base &Fmt) { size_t BufferBytesLeft = OutBufEnd - OutBufCur; if (BufferBytesLeft > 3) { size_t BytesUsed = Fmt.print(OutBufCur, BufferBytesLeft); - + // Common case is that we have plenty of space. if (BytesUsed <= BufferBytesLeft) { OutBufCur += BytesUsed; return *this; } - + // Otherwise, we overflowed and the return value tells us the size to try // again with. NextBufferSize = BytesUsed; } - + // If we got here, we didn't have enough space in the output buffer for the // string. Try printing into a SmallVector that is resized to have enough // space. Iterate until we win. SmallVector<char, 128> V; - + while (1) { V.resize(NextBufferSize); - + // Try formatting into the SmallVector. size_t BytesUsed = Fmt.print(V.data(), NextBufferSize); - + // If BytesUsed fit into the vector, we win. if (BytesUsed <= NextBufferSize) return write(V.data(), BytesUsed); - + // Otherwise, try again with a new size. assert(BytesUsed > NextBufferSize && "Didn't grow buffer!?"); NextBufferSize = BytesUsed; @@ -339,7 +339,7 @@ raw_ostream &raw_ostream::indent(unsigned NumSpaces) { // Usually the indentation is small, handle it with a fastpath. if (NumSpaces < array_lengthof(Spaces)) return write(Spaces, NumSpaces); - + while (NumSpaces) { unsigned NumToWrite = std::min(NumSpaces, (unsigned)array_lengthof(Spaces)-1); @@ -372,7 +372,7 @@ raw_fd_ostream::raw_fd_ostream(const char *Filename, std::string &ErrorInfo, // Verify that we don't have both "append" and "excl". assert((!(Flags & F_Excl) || !(Flags & F_Append)) && "Cannot specify both 'excl' and 'append' file creation flags!"); - + ErrorInfo.clear(); // Handle "-" as stdout. @@ -385,20 +385,20 @@ raw_fd_ostream::raw_fd_ostream(const char *Filename, std::string &ErrorInfo, ShouldClose = false; return; } - + int OpenFlags = O_WRONLY|O_CREAT; #ifdef O_BINARY if (Flags & F_Binary) OpenFlags |= O_BINARY; #endif - + if (Flags & F_Append) OpenFlags |= O_APPEND; else OpenFlags |= O_TRUNC; if (Flags & F_Excl) OpenFlags |= O_EXCL; - + FD = open(Filename, OpenFlags, 0664); if (FD < 0) { ErrorInfo = "Error opening output file '" + std::string(Filename) + "'"; @@ -418,14 +418,14 @@ raw_fd_ostream::~raw_fd_ostream() { void raw_fd_ostream::write_impl(const char *Ptr, size_t Size) { - assert (FD >= 0 && "File already closed."); + assert(FD >= 0 && "File already closed."); pos += Size; if (::write(FD, Ptr, Size) != (ssize_t) Size) error_detected(); } void raw_fd_ostream::close() { - assert (ShouldClose); + assert(ShouldClose); ShouldClose = false; flush(); if (::close(FD) != 0) @@ -438,16 +438,17 @@ uint64_t raw_fd_ostream::seek(uint64_t off) { pos = ::lseek(FD, off, SEEK_SET); if (pos != off) error_detected(); - return pos; + return pos; } size_t raw_fd_ostream::preferred_buffer_size() const { -#if !defined(_MSC_VER) && !defined(__MINGW32__) // Windows has no st_blksize. +#if !defined(_MSC_VER) && !defined(__MINGW32__) && !defined(_MINIX) + // Windows and Minix have no st_blksize. assert(FD >= 0 && "File not yet open!"); struct stat statbuf; if (fstat(FD, &statbuf) != 0) return 0; - + // If this is a terminal, don't use buffering. Line buffering // would be a more traditional thing to do, but it's not worth // the complexity. diff --git a/lib/Support/regengine.inc b/lib/Support/regengine.inc index 0f27cfd4b5..7e41f96f35 100644 --- a/lib/Support/regengine.inc +++ b/lib/Support/regengine.inc @@ -72,11 +72,11 @@ struct match { struct re_guts *g; int eflags; llvm_regmatch_t *pmatch; /* [nsub+1] (0 element unused) */ - char *offp; /* offsets work from here */ - char *beginp; /* start of string -- virtual NUL precedes */ - char *endp; /* end of string -- virtual NUL here */ - char *coldp; /* can be no match starting before here */ - char **lastpos; /* [nplus+1] */ + const char *offp; /* offsets work from here */ + const char *beginp; /* start of string -- virtual NUL precedes */ + const char *endp; /* end of string -- virtual NUL here */ + const char *coldp; /* can be no match starting before here */ + const char **lastpos; /* [nplus+1] */ STATEVARS; states st; /* current states */ states fresh; /* states for a fresh start */ @@ -84,11 +84,14 @@ struct match { states empty; /* empty set of states */ }; -static int matcher(struct re_guts *, char *, size_t, llvm_regmatch_t[], int); -static char *dissect(struct match *, char *, char *, sopno, sopno); -static char *backref(struct match *, char *, char *, sopno, sopno, sopno, int); -static char *fast(struct match *, char *, char *, sopno, sopno); -static char *slow(struct match *, char *, char *, sopno, sopno); +static int matcher(struct re_guts *, const char *, size_t, + llvm_regmatch_t[], int); +static const char *dissect(struct match *, const char *, const char *, sopno, + sopno); +static const char *backref(struct match *, const char *, const char *, sopno, + sopno, sopno, int); +static const char *fast(struct match *, const char *, const char *, sopno, sopno); +static const char *slow(struct match *, const char *, const char *, sopno, sopno); static states step(struct re_guts *, sopno, sopno, states, int, states); #define MAX_RECURSION 100 #define BOL (OUT+1) @@ -125,18 +128,19 @@ static int nope = 0; - matcher - the actual matching engine */ static int /* 0 success, REG_NOMATCH failure */ -matcher(struct re_guts *g, char *string, size_t nmatch, llvm_regmatch_t pmatch[], +matcher(struct re_guts *g, const char *string, size_t nmatch, + llvm_regmatch_t pmatch[], int eflags) { - char *endp; + const char *endp; size_t i; struct match mv; struct match *m = &mv; - char *dp; + const char *dp; const sopno gf = g->firststate+1; /* +1 for OEND */ const sopno gl = g->laststate; - char *start; - char *stop; + const char *start; + const char *stop; /* simplify the situation where possible */ if (g->cflags®_NOSUB) @@ -181,7 +185,7 @@ matcher(struct re_guts *g, char *string, size_t nmatch, llvm_regmatch_t pmatch[] endp = fast(m, start, stop, gf, gl); if (endp == NULL) { /* a miss */ free(m->pmatch); - free(m->lastpos); + free((void*)m->lastpos); STATETEARDOWN(m); return(REG_NOMATCH); } @@ -216,7 +220,7 @@ matcher(struct re_guts *g, char *string, size_t nmatch, llvm_regmatch_t pmatch[] dp = dissect(m, m->coldp, endp, gf, gl); } else { if (g->nplus > 0 && m->lastpos == NULL) - m->lastpos = (char **)malloc((g->nplus+1) * + m->lastpos = (const char **)malloc((g->nplus+1) * sizeof(char *)); if (g->nplus > 0 && m->lastpos == NULL) { free(m->pmatch); @@ -287,21 +291,22 @@ matcher(struct re_guts *g, char *string, size_t nmatch, llvm_regmatch_t pmatch[] /* - dissect - figure out what matched what, no back references */ -static char * /* == stop (success) always */ -dissect(struct match *m, char *start, char *stop, sopno startst, sopno stopst) +static const char * /* == stop (success) always */ +dissect(struct match *m, const char *start, const char *stop, sopno startst, + sopno stopst) { int i; sopno ss; /* start sop of current subRE */ sopno es; /* end sop of current subRE */ - char *sp; /* start of string matched by it */ - char *stp; /* string matched by it cannot pass here */ - char *rest; /* start of rest of string */ - char *tail; /* string unmatched by rest of RE */ + const char *sp; /* start of string matched by it */ + const char *stp; /* string matched by it cannot pass here */ + const char *rest; /* start of rest of string */ + const char *tail; /* string unmatched by rest of RE */ sopno ssub; /* start sop of subsubRE */ sopno esub; /* end sop of subsubRE */ - char *ssp; /* start of string matched by subsubRE */ - char *sep; /* end of string matched by subsubRE */ - char *oldssp; /* previous ssp */ + const char *ssp; /* start of string matched by subsubRE */ + const char *sep; /* end of string matched by subsubRE */ + const char *oldssp; /* previous ssp */ AT("diss", start, stop, startst, stopst); sp = start; @@ -360,7 +365,7 @@ dissect(struct match *m, char *start, char *stop, sopno startst, sopno stopst) esub = es - 1; /* did innards match? */ if (slow(m, sp, rest, ssub, esub) != NULL) { - char *dp = dissect(m, sp, rest, ssub, esub); + const char *dp = dissect(m, sp, rest, ssub, esub); (void)dp; /* avoid warning if assertions off */ assert(dp == rest); } else /* no */ @@ -400,7 +405,7 @@ dissect(struct match *m, char *start, char *stop, sopno startst, sopno stopst) assert(sep == rest); /* must exhaust substring */ assert(slow(m, ssp, sep, ssub, esub) == rest); { - char *dp = dissect(m, ssp, sep, ssub, esub); + const char *dp = dissect(m, ssp, sep, ssub, esub); (void)dp; /* avoid warning if assertions off */ assert(dp == sep); } @@ -438,7 +443,7 @@ dissect(struct match *m, char *start, char *stop, sopno startst, sopno stopst) assert(OP(m->g->strip[esub]) == O_CH); } { - char *dp = dissect(m, sp, rest, ssub, esub); + const char *dp = dissect(m, sp, rest, ssub, esub); (void)dp; /* avoid warning if assertions off */ assert(dp == rest); } @@ -474,17 +479,17 @@ dissect(struct match *m, char *start, char *stop, sopno startst, sopno stopst) /* - backref - figure out what matched what, figuring in back references */ -static char * /* == stop (success) or NULL (failure) */ -backref(struct match *m, char *start, char *stop, sopno startst, sopno stopst, - sopno lev, int rec) /* PLUS nesting level */ +static const char * /* == stop (success) or NULL (failure) */ +backref(struct match *m, const char *start, const char *stop, sopno startst, + sopno stopst, sopno lev, int rec) /* PLUS nesting level */ { int i; sopno ss; /* start sop of current subRE */ - char *sp; /* start of string matched by it */ + const char *sp; /* start of string matched by it */ sopno ssub; /* start sop of subsubRE */ sopno esub; /* end sop of subsubRE */ - char *ssp; /* start of string matched by subsubRE */ - char *dp; + const char *ssp; /* start of string matched by subsubRE */ + const char *dp; size_t len; int hard; sop s; @@ -674,18 +679,19 @@ backref(struct match *m, char *start, char *stop, sopno startst, sopno stopst, /* - fast - step through the string at top speed */ -static char * /* where tentative match ended, or NULL */ -fast(struct match *m, char *start, char *stop, sopno startst, sopno stopst) +static const char * /* where tentative match ended, or NULL */ +fast(struct match *m, const char *start, const char *stop, sopno startst, + sopno stopst) { states st = m->st; states fresh = m->fresh; states tmp = m->tmp; - char *p = start; + const char *p = start; int c = (start == m->beginp) ? OUT : *(start-1); int lastc; /* previous c */ int flagch; int i; - char *coldp; /* last p after which no match was underway */ + const char *coldp; /* last p after which no match was underway */ CLEAR(st); SET1(st, startst); @@ -758,18 +764,19 @@ fast(struct match *m, char *start, char *stop, sopno startst, sopno stopst) /* - slow - step through the string more deliberately */ -static char * /* where it ended */ -slow(struct match *m, char *start, char *stop, sopno startst, sopno stopst) +static const char * /* where it ended */ +slow(struct match *m, const char *start, const char *stop, sopno startst, + sopno stopst) { states st = m->st; states empty = m->empty; states tmp = m->tmp; - char *p = start; + const char *p = start; int c = (start == m->beginp) ? OUT : *(start-1); int lastc; /* previous c */ int flagch; int i; - char *matchp; /* last p at which a match ended */ + const char *matchp; /* last p at which a match ended */ AT("slow", start, stop, startst, stopst); CLEAR(st); diff --git a/lib/Support/regexec.c b/lib/Support/regexec.c index 7d70f6e16c..41fb2ea46c 100644 --- a/lib/Support/regexec.c +++ b/lib/Support/regexec.c @@ -155,7 +155,7 @@ llvm_regexec(const llvm_regex_t *preg, const char *string, size_t nmatch, eflags = GOODFLAGS(eflags); if (g->nstates <= (long)(CHAR_BIT*sizeof(states1)) && !(eflags®_LARGE)) - return(smatcher(g, (char *)string, nmatch, pmatch, eflags)); + return(smatcher(g, string, nmatch, pmatch, eflags)); else - return(lmatcher(g, (char *)string, nmatch, pmatch, eflags)); + return(lmatcher(g, string, nmatch, pmatch, eflags)); } |