Home | History | Annotate | Download | only in Lex
      1 //===--- PPExpressions.cpp - Preprocessor Expression Evaluation -----------===//
      2 //
      3 //                     The LLVM Compiler Infrastructure
      4 //
      5 // This file is distributed under the University of Illinois Open Source
      6 // License. See LICENSE.TXT for details.
      7 //
      8 //===----------------------------------------------------------------------===//
      9 //
     10 // This file implements the Preprocessor::EvaluateDirectiveExpression method,
     11 // which parses and evaluates integer constant expressions for #if directives.
     12 //
     13 //===----------------------------------------------------------------------===//
     14 //
     15 // FIXME: implement testing for #assert's.
     16 //
     17 //===----------------------------------------------------------------------===//
     18 
     19 #include "clang/Lex/Preprocessor.h"
     20 #include "clang/Lex/MacroInfo.h"
     21 #include "clang/Lex/LiteralSupport.h"
     22 #include "clang/Lex/CodeCompletionHandler.h"
     23 #include "clang/Basic/TargetInfo.h"
     24 #include "clang/Lex/LexDiagnostic.h"
     25 #include "llvm/ADT/APSInt.h"
     26 #include "llvm/Support/ErrorHandling.h"
     27 using namespace clang;
     28 
     29 namespace {
     30 
     31 /// PPValue - Represents the value of a subexpression of a preprocessor
     32 /// conditional and the source range covered by it.
     33 class PPValue {
     34   SourceRange Range;
     35 public:
     36   llvm::APSInt Val;
     37 
     38   // Default ctor - Construct an 'invalid' PPValue.
     39   PPValue(unsigned BitWidth) : Val(BitWidth) {}
     40 
     41   unsigned getBitWidth() const { return Val.getBitWidth(); }
     42   bool isUnsigned() const { return Val.isUnsigned(); }
     43 
     44   const SourceRange &getRange() const { return Range; }
     45 
     46   void setRange(SourceLocation L) { Range.setBegin(L); Range.setEnd(L); }
     47   void setRange(SourceLocation B, SourceLocation E) {
     48     Range.setBegin(B); Range.setEnd(E);
     49   }
     50   void setBegin(SourceLocation L) { Range.setBegin(L); }
     51   void setEnd(SourceLocation L) { Range.setEnd(L); }
     52 };
     53 
     54 }
     55 
     56 static bool EvaluateDirectiveSubExpr(PPValue &LHS, unsigned MinPrec,
     57                                      Token &PeekTok, bool ValueLive,
     58                                      Preprocessor &PP);
     59 
     60 /// DefinedTracker - This struct is used while parsing expressions to keep track
     61 /// of whether !defined(X) has been seen.
     62 ///
     63 /// With this simple scheme, we handle the basic forms:
     64 ///    !defined(X)   and !defined X
     65 /// but we also trivially handle (silly) stuff like:
     66 ///    !!!defined(X) and +!defined(X) and !+!+!defined(X) and !(defined(X)).
     67 struct DefinedTracker {
     68   /// Each time a Value is evaluated, it returns information about whether the
     69   /// parsed value is of the form defined(X), !defined(X) or is something else.
     70   enum TrackerState {
     71     DefinedMacro,        // defined(X)
     72     NotDefinedMacro,     // !defined(X)
     73     Unknown              // Something else.
     74   } State;
     75   /// TheMacro - When the state is DefinedMacro or NotDefinedMacro, this
     76   /// indicates the macro that was checked.
     77   IdentifierInfo *TheMacro;
     78 };
     79 
     80 /// EvaluateDefined - Process a 'defined(sym)' expression.
     81 static bool EvaluateDefined(PPValue &Result, Token &PeekTok, DefinedTracker &DT,
     82                             bool ValueLive, Preprocessor &PP) {
     83   IdentifierInfo *II;
     84   Result.setBegin(PeekTok.getLocation());
     85 
     86   // Get the next token, don't expand it.
     87   PP.LexUnexpandedNonComment(PeekTok);
     88 
     89   // Two options, it can either be a pp-identifier or a (.
     90   SourceLocation LParenLoc;
     91   if (PeekTok.is(tok::l_paren)) {
     92     // Found a paren, remember we saw it and skip it.
     93     LParenLoc = PeekTok.getLocation();
     94     PP.LexUnexpandedNonComment(PeekTok);
     95   }
     96 
     97   if (PeekTok.is(tok::code_completion)) {
     98     if (PP.getCodeCompletionHandler())
     99       PP.getCodeCompletionHandler()->CodeCompleteMacroName(false);
    100     PP.setCodeCompletionReached();
    101     PP.LexUnexpandedNonComment(PeekTok);
    102   }
    103 
    104   // If we don't have a pp-identifier now, this is an error.
    105   if ((II = PeekTok.getIdentifierInfo()) == 0) {
    106     PP.Diag(PeekTok, diag::err_pp_defined_requires_identifier);
    107     return true;
    108   }
    109 
    110   // Otherwise, we got an identifier, is it defined to something?
    111   Result.Val = II->hasMacroDefinition();
    112   Result.Val.setIsUnsigned(false);  // Result is signed intmax_t.
    113 
    114   // If there is a macro, mark it used.
    115   if (Result.Val != 0 && ValueLive) {
    116     MacroInfo *Macro = PP.getMacroInfo(II);
    117     PP.markMacroAsUsed(Macro);
    118   }
    119 
    120   // Invoke the 'defined' callback.
    121   if (PPCallbacks *Callbacks = PP.getPPCallbacks())
    122     Callbacks->Defined(PeekTok);
    123 
    124   // If we are in parens, ensure we have a trailing ).
    125   if (LParenLoc.isValid()) {
    126     // Consume identifier.
    127     Result.setEnd(PeekTok.getLocation());
    128     PP.LexUnexpandedNonComment(PeekTok);
    129 
    130     if (PeekTok.isNot(tok::r_paren)) {
    131       PP.Diag(PeekTok.getLocation(), diag::err_pp_missing_rparen) << "defined";
    132       PP.Diag(LParenLoc, diag::note_matching) << "(";
    133       return true;
    134     }
    135     // Consume the ).
    136     Result.setEnd(PeekTok.getLocation());
    137     PP.LexNonComment(PeekTok);
    138   } else {
    139     // Consume identifier.
    140     Result.setEnd(PeekTok.getLocation());
    141     PP.LexNonComment(PeekTok);
    142   }
    143 
    144   // Success, remember that we saw defined(X).
    145   DT.State = DefinedTracker::DefinedMacro;
    146   DT.TheMacro = II;
    147   return false;
    148 }
    149 
    150 /// EvaluateValue - Evaluate the token PeekTok (and any others needed) and
    151 /// return the computed value in Result.  Return true if there was an error
    152 /// parsing.  This function also returns information about the form of the
    153 /// expression in DT.  See above for information on what DT means.
    154 ///
    155 /// If ValueLive is false, then this value is being evaluated in a context where
    156 /// the result is not used.  As such, avoid diagnostics that relate to
    157 /// evaluation.
    158 static bool EvaluateValue(PPValue &Result, Token &PeekTok, DefinedTracker &DT,
    159                           bool ValueLive, Preprocessor &PP) {
    160   DT.State = DefinedTracker::Unknown;
    161 
    162   if (PeekTok.is(tok::code_completion)) {
    163     if (PP.getCodeCompletionHandler())
    164       PP.getCodeCompletionHandler()->CodeCompletePreprocessorExpression();
    165     PP.setCodeCompletionReached();
    166     PP.LexNonComment(PeekTok);
    167   }
    168 
    169   // If this token's spelling is a pp-identifier, check to see if it is
    170   // 'defined' or if it is a macro.  Note that we check here because many
    171   // keywords are pp-identifiers, so we can't check the kind.
    172   if (IdentifierInfo *II = PeekTok.getIdentifierInfo()) {
    173     // Handle "defined X" and "defined(X)".
    174     if (II->isStr("defined"))
    175       return(EvaluateDefined(Result, PeekTok, DT, ValueLive, PP));
    176 
    177     // If this identifier isn't 'defined' or one of the special
    178     // preprocessor keywords and it wasn't macro expanded, it turns
    179     // into a simple 0, unless it is the C++ keyword "true", in which case it
    180     // turns into "1".
    181     if (ValueLive)
    182       PP.Diag(PeekTok, diag::warn_pp_undef_identifier) << II;
    183     Result.Val = II->getTokenID() == tok::kw_true;
    184     Result.Val.setIsUnsigned(false);  // "0" is signed intmax_t 0.
    185     Result.setRange(PeekTok.getLocation());
    186     PP.LexNonComment(PeekTok);
    187     return false;
    188   }
    189 
    190   switch (PeekTok.getKind()) {
    191   default:  // Non-value token.
    192     PP.Diag(PeekTok, diag::err_pp_expr_bad_token_start_expr);
    193     return true;
    194   case tok::eod:
    195   case tok::r_paren:
    196     // If there is no expression, report and exit.
    197     PP.Diag(PeekTok, diag::err_pp_expected_value_in_expr);
    198     return true;
    199   case tok::numeric_constant: {
    200     llvm::SmallString<64> IntegerBuffer;
    201     bool NumberInvalid = false;
    202     StringRef Spelling = PP.getSpelling(PeekTok, IntegerBuffer,
    203                                               &NumberInvalid);
    204     if (NumberInvalid)
    205       return true; // a diagnostic was already reported
    206 
    207     NumericLiteralParser Literal(Spelling.begin(), Spelling.end(),
    208                                  PeekTok.getLocation(), PP);
    209     if (Literal.hadError)
    210       return true; // a diagnostic was already reported.
    211 
    212     if (Literal.isFloatingLiteral() || Literal.isImaginary) {
    213       PP.Diag(PeekTok, diag::err_pp_illegal_floating_literal);
    214       return true;
    215     }
    216     assert(Literal.isIntegerLiteral() && "Unknown ppnumber");
    217 
    218     // long long is a C99 feature.
    219     if (!PP.getLangOptions().C99 && Literal.isLongLong)
    220       PP.Diag(PeekTok, PP.getLangOptions().CPlusPlus0x ?
    221               diag::warn_cxx98_compat_longlong : diag::ext_longlong);
    222 
    223     // Parse the integer literal into Result.
    224     if (Literal.GetIntegerValue(Result.Val)) {
    225       // Overflow parsing integer literal.
    226       if (ValueLive) PP.Diag(PeekTok, diag::warn_integer_too_large);
    227       Result.Val.setIsUnsigned(true);
    228     } else {
    229       // Set the signedness of the result to match whether there was a U suffix
    230       // or not.
    231       Result.Val.setIsUnsigned(Literal.isUnsigned);
    232 
    233       // Detect overflow based on whether the value is signed.  If signed
    234       // and if the value is too large, emit a warning "integer constant is so
    235       // large that it is unsigned" e.g. on 12345678901234567890 where intmax_t
    236       // is 64-bits.
    237       if (!Literal.isUnsigned && Result.Val.isNegative()) {
    238         // Don't warn for a hex literal: 0x8000..0 shouldn't warn.
    239         if (ValueLive && Literal.getRadix() != 16)
    240           PP.Diag(PeekTok, diag::warn_integer_too_large_for_signed);
    241         Result.Val.setIsUnsigned(true);
    242       }
    243     }
    244 
    245     // Consume the token.
    246     Result.setRange(PeekTok.getLocation());
    247     PP.LexNonComment(PeekTok);
    248     return false;
    249   }
    250   case tok::char_constant:          // 'x'
    251   case tok::wide_char_constant: {   // L'x'
    252   case tok::utf16_char_constant:    // u'x'
    253   case tok::utf32_char_constant:    // U'x'
    254     llvm::SmallString<32> CharBuffer;
    255     bool CharInvalid = false;
    256     StringRef ThisTok = PP.getSpelling(PeekTok, CharBuffer, &CharInvalid);
    257     if (CharInvalid)
    258       return true;
    259 
    260     CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(),
    261                               PeekTok.getLocation(), PP, PeekTok.getKind());
    262     if (Literal.hadError())
    263       return true;  // A diagnostic was already emitted.
    264 
    265     // Character literals are always int or wchar_t, expand to intmax_t.
    266     const TargetInfo &TI = PP.getTargetInfo();
    267     unsigned NumBits;
    268     if (Literal.isMultiChar())
    269       NumBits = TI.getIntWidth();
    270     else if (Literal.isWide())
    271       NumBits = TI.getWCharWidth();
    272     else if (Literal.isUTF16())
    273       NumBits = TI.getChar16Width();
    274     else if (Literal.isUTF32())
    275       NumBits = TI.getChar32Width();
    276     else
    277       NumBits = TI.getCharWidth();
    278 
    279     // Set the width.
    280     llvm::APSInt Val(NumBits);
    281     // Set the value.
    282     Val = Literal.getValue();
    283     // Set the signedness. UTF-16 and UTF-32 are always unsigned
    284     if (!Literal.isUTF16() && !Literal.isUTF32())
    285       Val.setIsUnsigned(!PP.getLangOptions().CharIsSigned);
    286 
    287     if (Result.Val.getBitWidth() > Val.getBitWidth()) {
    288       Result.Val = Val.extend(Result.Val.getBitWidth());
    289     } else {
    290       assert(Result.Val.getBitWidth() == Val.getBitWidth() &&
    291              "intmax_t smaller than char/wchar_t?");
    292       Result.Val = Val;
    293     }
    294 
    295     // Consume the token.
    296     Result.setRange(PeekTok.getLocation());
    297     PP.LexNonComment(PeekTok);
    298     return false;
    299   }
    300   case tok::l_paren: {
    301     SourceLocation Start = PeekTok.getLocation();
    302     PP.LexNonComment(PeekTok);  // Eat the (.
    303     // Parse the value and if there are any binary operators involved, parse
    304     // them.
    305     if (EvaluateValue(Result, PeekTok, DT, ValueLive, PP)) return true;
    306 
    307     // If this is a silly value like (X), which doesn't need parens, check for
    308     // !(defined X).
    309     if (PeekTok.is(tok::r_paren)) {
    310       // Just use DT unmodified as our result.
    311     } else {
    312       // Otherwise, we have something like (x+y), and we consumed '(x'.
    313       if (EvaluateDirectiveSubExpr(Result, 1, PeekTok, ValueLive, PP))
    314         return true;
    315 
    316       if (PeekTok.isNot(tok::r_paren)) {
    317         PP.Diag(PeekTok.getLocation(), diag::err_pp_expected_rparen)
    318           << Result.getRange();
    319         PP.Diag(Start, diag::note_matching) << "(";
    320         return true;
    321       }
    322       DT.State = DefinedTracker::Unknown;
    323     }
    324     Result.setRange(Start, PeekTok.getLocation());
    325     PP.LexNonComment(PeekTok);  // Eat the ).
    326     return false;
    327   }
    328   case tok::plus: {
    329     SourceLocation Start = PeekTok.getLocation();
    330     // Unary plus doesn't modify the value.
    331     PP.LexNonComment(PeekTok);
    332     if (EvaluateValue(Result, PeekTok, DT, ValueLive, PP)) return true;
    333     Result.setBegin(Start);
    334     return false;
    335   }
    336   case tok::minus: {
    337     SourceLocation Loc = PeekTok.getLocation();
    338     PP.LexNonComment(PeekTok);
    339     if (EvaluateValue(Result, PeekTok, DT, ValueLive, PP)) return true;
    340     Result.setBegin(Loc);
    341 
    342     // C99 6.5.3.3p3: The sign of the result matches the sign of the operand.
    343     Result.Val = -Result.Val;
    344 
    345     // -MININT is the only thing that overflows.  Unsigned never overflows.
    346     bool Overflow = !Result.isUnsigned() && Result.Val.isMinSignedValue();
    347 
    348     // If this operator is live and overflowed, report the issue.
    349     if (Overflow && ValueLive)
    350       PP.Diag(Loc, diag::warn_pp_expr_overflow) << Result.getRange();
    351 
    352     DT.State = DefinedTracker::Unknown;
    353     return false;
    354   }
    355 
    356   case tok::tilde: {
    357     SourceLocation Start = PeekTok.getLocation();
    358     PP.LexNonComment(PeekTok);
    359     if (EvaluateValue(Result, PeekTok, DT, ValueLive, PP)) return true;
    360     Result.setBegin(Start);
    361 
    362     // C99 6.5.3.3p4: The sign of the result matches the sign of the operand.
    363     Result.Val = ~Result.Val;
    364     DT.State = DefinedTracker::Unknown;
    365     return false;
    366   }
    367 
    368   case tok::exclaim: {
    369     SourceLocation Start = PeekTok.getLocation();
    370     PP.LexNonComment(PeekTok);
    371     if (EvaluateValue(Result, PeekTok, DT, ValueLive, PP)) return true;
    372     Result.setBegin(Start);
    373     Result.Val = !Result.Val;
    374     // C99 6.5.3.3p5: The sign of the result is 'int', aka it is signed.
    375     Result.Val.setIsUnsigned(false);
    376 
    377     if (DT.State == DefinedTracker::DefinedMacro)
    378       DT.State = DefinedTracker::NotDefinedMacro;
    379     else if (DT.State == DefinedTracker::NotDefinedMacro)
    380       DT.State = DefinedTracker::DefinedMacro;
    381     return false;
    382   }
    383 
    384   // FIXME: Handle #assert
    385   }
    386 }
    387 
    388 
    389 
    390 /// getPrecedence - Return the precedence of the specified binary operator
    391 /// token.  This returns:
    392 ///   ~0 - Invalid token.
    393 ///   14 -> 3 - various operators.
    394 ///    0 - 'eod' or ')'
    395 static unsigned getPrecedence(tok::TokenKind Kind) {
    396   switch (Kind) {
    397   default: return ~0U;
    398   case tok::percent:
    399   case tok::slash:
    400   case tok::star:                 return 14;
    401   case tok::plus:
    402   case tok::minus:                return 13;
    403   case tok::lessless:
    404   case tok::greatergreater:       return 12;
    405   case tok::lessequal:
    406   case tok::less:
    407   case tok::greaterequal:
    408   case tok::greater:              return 11;
    409   case tok::exclaimequal:
    410   case tok::equalequal:           return 10;
    411   case tok::amp:                  return 9;
    412   case tok::caret:                return 8;
    413   case tok::pipe:                 return 7;
    414   case tok::ampamp:               return 6;
    415   case tok::pipepipe:             return 5;
    416   case tok::question:             return 4;
    417   case tok::comma:                return 3;
    418   case tok::colon:                return 2;
    419   case tok::r_paren:              return 0;// Lowest priority, end of expr.
    420   case tok::eod:                  return 0;// Lowest priority, end of directive.
    421   }
    422 }
    423 
    424 
    425 /// EvaluateDirectiveSubExpr - Evaluate the subexpression whose first token is
    426 /// PeekTok, and whose precedence is PeekPrec.  This returns the result in LHS.
    427 ///
    428 /// If ValueLive is false, then this value is being evaluated in a context where
    429 /// the result is not used.  As such, avoid diagnostics that relate to
    430 /// evaluation, such as division by zero warnings.
    431 static bool EvaluateDirectiveSubExpr(PPValue &LHS, unsigned MinPrec,
    432                                      Token &PeekTok, bool ValueLive,
    433                                      Preprocessor &PP) {
    434   unsigned PeekPrec = getPrecedence(PeekTok.getKind());
    435   // If this token isn't valid, report the error.
    436   if (PeekPrec == ~0U) {
    437     PP.Diag(PeekTok.getLocation(), diag::err_pp_expr_bad_token_binop)
    438       << LHS.getRange();
    439     return true;
    440   }
    441 
    442   while (1) {
    443     // If this token has a lower precedence than we are allowed to parse, return
    444     // it so that higher levels of the recursion can parse it.
    445     if (PeekPrec < MinPrec)
    446       return false;
    447 
    448     tok::TokenKind Operator = PeekTok.getKind();
    449 
    450     // If this is a short-circuiting operator, see if the RHS of the operator is
    451     // dead.  Note that this cannot just clobber ValueLive.  Consider
    452     // "0 && 1 ? 4 : 1 / 0", which is parsed as "(0 && 1) ? 4 : (1 / 0)".  In
    453     // this example, the RHS of the && being dead does not make the rest of the
    454     // expr dead.
    455     bool RHSIsLive;
    456     if (Operator == tok::ampamp && LHS.Val == 0)
    457       RHSIsLive = false;   // RHS of "0 && x" is dead.
    458     else if (Operator == tok::pipepipe && LHS.Val != 0)
    459       RHSIsLive = false;   // RHS of "1 || x" is dead.
    460     else if (Operator == tok::question && LHS.Val == 0)
    461       RHSIsLive = false;   // RHS (x) of "0 ? x : y" is dead.
    462     else
    463       RHSIsLive = ValueLive;
    464 
    465     // Consume the operator, remembering the operator's location for reporting.
    466     SourceLocation OpLoc = PeekTok.getLocation();
    467     PP.LexNonComment(PeekTok);
    468 
    469     PPValue RHS(LHS.getBitWidth());
    470     // Parse the RHS of the operator.
    471     DefinedTracker DT;
    472     if (EvaluateValue(RHS, PeekTok, DT, RHSIsLive, PP)) return true;
    473 
    474     // Remember the precedence of this operator and get the precedence of the
    475     // operator immediately to the right of the RHS.
    476     unsigned ThisPrec = PeekPrec;
    477     PeekPrec = getPrecedence(PeekTok.getKind());
    478 
    479     // If this token isn't valid, report the error.
    480     if (PeekPrec == ~0U) {
    481       PP.Diag(PeekTok.getLocation(), diag::err_pp_expr_bad_token_binop)
    482         << RHS.getRange();
    483       return true;
    484     }
    485 
    486     // Decide whether to include the next binop in this subexpression.  For
    487     // example, when parsing x+y*z and looking at '*', we want to recursively
    488     // handle y*z as a single subexpression.  We do this because the precedence
    489     // of * is higher than that of +.  The only strange case we have to handle
    490     // here is for the ?: operator, where the precedence is actually lower than
    491     // the LHS of the '?'.  The grammar rule is:
    492     //
    493     // conditional-expression ::=
    494     //    logical-OR-expression ? expression : conditional-expression
    495     // where 'expression' is actually comma-expression.
    496     unsigned RHSPrec;
    497     if (Operator == tok::question)
    498       // The RHS of "?" should be maximally consumed as an expression.
    499       RHSPrec = getPrecedence(tok::comma);
    500     else  // All others should munch while higher precedence.
    501       RHSPrec = ThisPrec+1;
    502 
    503     if (PeekPrec >= RHSPrec) {
    504       if (EvaluateDirectiveSubExpr(RHS, RHSPrec, PeekTok, RHSIsLive, PP))
    505         return true;
    506       PeekPrec = getPrecedence(PeekTok.getKind());
    507     }
    508     assert(PeekPrec <= ThisPrec && "Recursion didn't work!");
    509 
    510     // Usual arithmetic conversions (C99 6.3.1.8p1): result is unsigned if
    511     // either operand is unsigned.
    512     llvm::APSInt Res(LHS.getBitWidth());
    513     switch (Operator) {
    514     case tok::question:       // No UAC for x and y in "x ? y : z".
    515     case tok::lessless:       // Shift amount doesn't UAC with shift value.
    516     case tok::greatergreater: // Shift amount doesn't UAC with shift value.
    517     case tok::comma:          // Comma operands are not subject to UACs.
    518     case tok::pipepipe:       // Logical || does not do UACs.
    519     case tok::ampamp:         // Logical && does not do UACs.
    520       break;                  // No UAC
    521     default:
    522       Res.setIsUnsigned(LHS.isUnsigned()|RHS.isUnsigned());
    523       // If this just promoted something from signed to unsigned, and if the
    524       // value was negative, warn about it.
    525       if (ValueLive && Res.isUnsigned()) {
    526         if (!LHS.isUnsigned() && LHS.Val.isNegative())
    527           PP.Diag(OpLoc, diag::warn_pp_convert_lhs_to_positive)
    528             << LHS.Val.toString(10, true) + " to " +
    529                LHS.Val.toString(10, false)
    530             << LHS.getRange() << RHS.getRange();
    531         if (!RHS.isUnsigned() && RHS.Val.isNegative())
    532           PP.Diag(OpLoc, diag::warn_pp_convert_rhs_to_positive)
    533             << RHS.Val.toString(10, true) + " to " +
    534                RHS.Val.toString(10, false)
    535             << LHS.getRange() << RHS.getRange();
    536       }
    537       LHS.Val.setIsUnsigned(Res.isUnsigned());
    538       RHS.Val.setIsUnsigned(Res.isUnsigned());
    539     }
    540 
    541     bool Overflow = false;
    542     switch (Operator) {
    543     default: llvm_unreachable("Unknown operator token!");
    544     case tok::percent:
    545       if (RHS.Val != 0)
    546         Res = LHS.Val % RHS.Val;
    547       else if (ValueLive) {
    548         PP.Diag(OpLoc, diag::err_pp_remainder_by_zero)
    549           << LHS.getRange() << RHS.getRange();
    550         return true;
    551       }
    552       break;
    553     case tok::slash:
    554       if (RHS.Val != 0) {
    555         if (LHS.Val.isSigned())
    556           Res = llvm::APSInt(LHS.Val.sdiv_ov(RHS.Val, Overflow), false);
    557         else
    558           Res = LHS.Val / RHS.Val;
    559       } else if (ValueLive) {
    560         PP.Diag(OpLoc, diag::err_pp_division_by_zero)
    561           << LHS.getRange() << RHS.getRange();
    562         return true;
    563       }
    564       break;
    565 
    566     case tok::star:
    567       if (Res.isSigned())
    568         Res = llvm::APSInt(LHS.Val.smul_ov(RHS.Val, Overflow), false);
    569       else
    570         Res = LHS.Val * RHS.Val;
    571       break;
    572     case tok::lessless: {
    573       // Determine whether overflow is about to happen.
    574       unsigned ShAmt = static_cast<unsigned>(RHS.Val.getLimitedValue());
    575       if (LHS.isUnsigned()) {
    576         Overflow = ShAmt >= LHS.Val.getBitWidth();
    577         if (Overflow)
    578           ShAmt = LHS.Val.getBitWidth()-1;
    579         Res = LHS.Val << ShAmt;
    580       } else {
    581         Res = llvm::APSInt(LHS.Val.sshl_ov(ShAmt, Overflow), false);
    582       }
    583       break;
    584     }
    585     case tok::greatergreater: {
    586       // Determine whether overflow is about to happen.
    587       unsigned ShAmt = static_cast<unsigned>(RHS.Val.getLimitedValue());
    588       if (ShAmt >= LHS.getBitWidth())
    589         Overflow = true, ShAmt = LHS.getBitWidth()-1;
    590       Res = LHS.Val >> ShAmt;
    591       break;
    592     }
    593     case tok::plus:
    594       if (LHS.isUnsigned())
    595         Res = LHS.Val + RHS.Val;
    596       else
    597         Res = llvm::APSInt(LHS.Val.sadd_ov(RHS.Val, Overflow), false);
    598       break;
    599     case tok::minus:
    600       if (LHS.isUnsigned())
    601         Res = LHS.Val - RHS.Val;
    602       else
    603         Res = llvm::APSInt(LHS.Val.ssub_ov(RHS.Val, Overflow), false);
    604       break;
    605     case tok::lessequal:
    606       Res = LHS.Val <= RHS.Val;
    607       Res.setIsUnsigned(false);  // C99 6.5.8p6, result is always int (signed)
    608       break;
    609     case tok::less:
    610       Res = LHS.Val < RHS.Val;
    611       Res.setIsUnsigned(false);  // C99 6.5.8p6, result is always int (signed)
    612       break;
    613     case tok::greaterequal:
    614       Res = LHS.Val >= RHS.Val;
    615       Res.setIsUnsigned(false);  // C99 6.5.8p6, result is always int (signed)
    616       break;
    617     case tok::greater:
    618       Res = LHS.Val > RHS.Val;
    619       Res.setIsUnsigned(false);  // C99 6.5.8p6, result is always int (signed)
    620       break;
    621     case tok::exclaimequal:
    622       Res = LHS.Val != RHS.Val;
    623       Res.setIsUnsigned(false);  // C99 6.5.9p3, result is always int (signed)
    624       break;
    625     case tok::equalequal:
    626       Res = LHS.Val == RHS.Val;
    627       Res.setIsUnsigned(false);  // C99 6.5.9p3, result is always int (signed)
    628       break;
    629     case tok::amp:
    630       Res = LHS.Val & RHS.Val;
    631       break;
    632     case tok::caret:
    633       Res = LHS.Val ^ RHS.Val;
    634       break;
    635     case tok::pipe:
    636       Res = LHS.Val | RHS.Val;
    637       break;
    638     case tok::ampamp:
    639       Res = (LHS.Val != 0 && RHS.Val != 0);
    640       Res.setIsUnsigned(false);  // C99 6.5.13p3, result is always int (signed)
    641       break;
    642     case tok::pipepipe:
    643       Res = (LHS.Val != 0 || RHS.Val != 0);
    644       Res.setIsUnsigned(false);  // C99 6.5.14p3, result is always int (signed)
    645       break;
    646     case tok::comma:
    647       // Comma is invalid in pp expressions in c89/c++ mode, but is valid in C99
    648       // if not being evaluated.
    649       if (!PP.getLangOptions().C99 || ValueLive)
    650         PP.Diag(OpLoc, diag::ext_pp_comma_expr)
    651           << LHS.getRange() << RHS.getRange();
    652       Res = RHS.Val; // LHS = LHS,RHS -> RHS.
    653       break;
    654     case tok::question: {
    655       // Parse the : part of the expression.
    656       if (PeekTok.isNot(tok::colon)) {
    657         PP.Diag(PeekTok.getLocation(), diag::err_expected_colon)
    658           << LHS.getRange(), RHS.getRange();
    659         PP.Diag(OpLoc, diag::note_matching) << "?";
    660         return true;
    661       }
    662       // Consume the :.
    663       PP.LexNonComment(PeekTok);
    664 
    665       // Evaluate the value after the :.
    666       bool AfterColonLive = ValueLive && LHS.Val == 0;
    667       PPValue AfterColonVal(LHS.getBitWidth());
    668       DefinedTracker DT;
    669       if (EvaluateValue(AfterColonVal, PeekTok, DT, AfterColonLive, PP))
    670         return true;
    671 
    672       // Parse anything after the : with the same precedence as ?.  We allow
    673       // things of equal precedence because ?: is right associative.
    674       if (EvaluateDirectiveSubExpr(AfterColonVal, ThisPrec,
    675                                    PeekTok, AfterColonLive, PP))
    676         return true;
    677 
    678       // Now that we have the condition, the LHS and the RHS of the :, evaluate.
    679       Res = LHS.Val != 0 ? RHS.Val : AfterColonVal.Val;
    680       RHS.setEnd(AfterColonVal.getRange().getEnd());
    681 
    682       // Usual arithmetic conversions (C99 6.3.1.8p1): result is unsigned if
    683       // either operand is unsigned.
    684       Res.setIsUnsigned(RHS.isUnsigned() | AfterColonVal.isUnsigned());
    685 
    686       // Figure out the precedence of the token after the : part.
    687       PeekPrec = getPrecedence(PeekTok.getKind());
    688       break;
    689     }
    690     case tok::colon:
    691       // Don't allow :'s to float around without being part of ?: exprs.
    692       PP.Diag(OpLoc, diag::err_pp_colon_without_question)
    693         << LHS.getRange() << RHS.getRange();
    694       return true;
    695     }
    696 
    697     // If this operator is live and overflowed, report the issue.
    698     if (Overflow && ValueLive)
    699       PP.Diag(OpLoc, diag::warn_pp_expr_overflow)
    700         << LHS.getRange() << RHS.getRange();
    701 
    702     // Put the result back into 'LHS' for our next iteration.
    703     LHS.Val = Res;
    704     LHS.setEnd(RHS.getRange().getEnd());
    705   }
    706 
    707   return false;
    708 }
    709 
    710 /// EvaluateDirectiveExpression - Evaluate an integer constant expression that
    711 /// may occur after a #if or #elif directive.  If the expression is equivalent
    712 /// to "!defined(X)" return X in IfNDefMacro.
    713 bool Preprocessor::
    714 EvaluateDirectiveExpression(IdentifierInfo *&IfNDefMacro) {
    715   // Save the current state of 'DisableMacroExpansion' and reset it to false. If
    716   // 'DisableMacroExpansion' is true, then we must be in a macro argument list
    717   // in which case a directive is undefined behavior.  We want macros to be able
    718   // to recursively expand in order to get more gcc-list behavior, so we force
    719   // DisableMacroExpansion to false and restore it when we're done parsing the
    720   // expression.
    721   bool DisableMacroExpansionAtStartOfDirective = DisableMacroExpansion;
    722   DisableMacroExpansion = false;
    723 
    724   // Peek ahead one token.
    725   Token Tok;
    726   LexNonComment(Tok);
    727 
    728   // C99 6.10.1p3 - All expressions are evaluated as intmax_t or uintmax_t.
    729   unsigned BitWidth = getTargetInfo().getIntMaxTWidth();
    730 
    731   PPValue ResVal(BitWidth);
    732   DefinedTracker DT;
    733   if (EvaluateValue(ResVal, Tok, DT, true, *this)) {
    734     // Parse error, skip the rest of the macro line.
    735     if (Tok.isNot(tok::eod))
    736       DiscardUntilEndOfDirective();
    737 
    738     // Restore 'DisableMacroExpansion'.
    739     DisableMacroExpansion = DisableMacroExpansionAtStartOfDirective;
    740     return false;
    741   }
    742 
    743   // If we are at the end of the expression after just parsing a value, there
    744   // must be no (unparenthesized) binary operators involved, so we can exit
    745   // directly.
    746   if (Tok.is(tok::eod)) {
    747     // If the expression we parsed was of the form !defined(macro), return the
    748     // macro in IfNDefMacro.
    749     if (DT.State == DefinedTracker::NotDefinedMacro)
    750       IfNDefMacro = DT.TheMacro;
    751 
    752     // Restore 'DisableMacroExpansion'.
    753     DisableMacroExpansion = DisableMacroExpansionAtStartOfDirective;
    754     return ResVal.Val != 0;
    755   }
    756 
    757   // Otherwise, we must have a binary operator (e.g. "#if 1 < 2"), so parse the
    758   // operator and the stuff after it.
    759   if (EvaluateDirectiveSubExpr(ResVal, getPrecedence(tok::question),
    760                                Tok, true, *this)) {
    761     // Parse error, skip the rest of the macro line.
    762     if (Tok.isNot(tok::eod))
    763       DiscardUntilEndOfDirective();
    764 
    765     // Restore 'DisableMacroExpansion'.
    766     DisableMacroExpansion = DisableMacroExpansionAtStartOfDirective;
    767     return false;
    768   }
    769 
    770   // If we aren't at the tok::eod token, something bad happened, like an extra
    771   // ')' token.
    772   if (Tok.isNot(tok::eod)) {
    773     Diag(Tok, diag::err_pp_expected_eol);
    774     DiscardUntilEndOfDirective();
    775   }
    776 
    777   // Restore 'DisableMacroExpansion'.
    778   DisableMacroExpansion = DisableMacroExpansionAtStartOfDirective;
    779   return ResVal.Val != 0;
    780 }
    781