]> CyberLeo.Net >> Repos - FreeBSD/stable/9.git/blob - contrib/llvm/tools/clang/lib/Lex/PPExpressions.cpp
MFC r244628:
[FreeBSD/stable/9.git] / contrib / llvm / tools / clang / lib / Lex / PPExpressions.cpp
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         II->getTokenID() != tok::kw_true &&
183         II->getTokenID() != tok::kw_false)
184       PP.Diag(PeekTok, diag::warn_pp_undef_identifier) << II;
185     Result.Val = II->getTokenID() == tok::kw_true;
186     Result.Val.setIsUnsigned(false);  // "0" is signed intmax_t 0.
187     Result.setRange(PeekTok.getLocation());
188     PP.LexNonComment(PeekTok);
189     return false;
190   }
191
192   switch (PeekTok.getKind()) {
193   default:  // Non-value token.
194     PP.Diag(PeekTok, diag::err_pp_expr_bad_token_start_expr);
195     return true;
196   case tok::eod:
197   case tok::r_paren:
198     // If there is no expression, report and exit.
199     PP.Diag(PeekTok, diag::err_pp_expected_value_in_expr);
200     return true;
201   case tok::numeric_constant: {
202     SmallString<64> IntegerBuffer;
203     bool NumberInvalid = false;
204     StringRef Spelling = PP.getSpelling(PeekTok, IntegerBuffer, 
205                                               &NumberInvalid);
206     if (NumberInvalid)
207       return true; // a diagnostic was already reported
208
209     NumericLiteralParser Literal(Spelling, PeekTok.getLocation(), PP);
210     if (Literal.hadError)
211       return true; // a diagnostic was already reported.
212
213     if (Literal.isFloatingLiteral() || Literal.isImaginary) {
214       PP.Diag(PeekTok, diag::err_pp_illegal_floating_literal);
215       return true;
216     }
217     assert(Literal.isIntegerLiteral() && "Unknown ppnumber");
218
219     // Complain about, and drop, any ud-suffix.
220     if (Literal.hasUDSuffix())
221       PP.Diag(PeekTok, diag::err_pp_invalid_udl) << /*integer*/1;
222
223     // 'long long' is a C99 or C++11 feature.
224     if (!PP.getLangOpts().C99 && Literal.isLongLong) {
225       if (PP.getLangOpts().CPlusPlus)
226         PP.Diag(PeekTok,
227              PP.getLangOpts().CPlusPlus0x ?
228              diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong);
229       else
230         PP.Diag(PeekTok, diag::ext_c99_longlong);
231     }
232
233     // Parse the integer literal into Result.
234     if (Literal.GetIntegerValue(Result.Val)) {
235       // Overflow parsing integer literal.
236       if (ValueLive) PP.Diag(PeekTok, diag::warn_integer_too_large);
237       Result.Val.setIsUnsigned(true);
238     } else {
239       // Set the signedness of the result to match whether there was a U suffix
240       // or not.
241       Result.Val.setIsUnsigned(Literal.isUnsigned);
242
243       // Detect overflow based on whether the value is signed.  If signed
244       // and if the value is too large, emit a warning "integer constant is so
245       // large that it is unsigned" e.g. on 12345678901234567890 where intmax_t
246       // is 64-bits.
247       if (!Literal.isUnsigned && Result.Val.isNegative()) {
248         // Don't warn for a hex literal: 0x8000..0 shouldn't warn.
249         if (ValueLive && Literal.getRadix() != 16)
250           PP.Diag(PeekTok, diag::warn_integer_too_large_for_signed);
251         Result.Val.setIsUnsigned(true);
252       }
253     }
254
255     // Consume the token.
256     Result.setRange(PeekTok.getLocation());
257     PP.LexNonComment(PeekTok);
258     return false;
259   }
260   case tok::char_constant:          // 'x'
261   case tok::wide_char_constant: {   // L'x'
262   case tok::utf16_char_constant:    // u'x'
263   case tok::utf32_char_constant:    // U'x'
264     // Complain about, and drop, any ud-suffix.
265     if (PeekTok.hasUDSuffix())
266       PP.Diag(PeekTok, diag::err_pp_invalid_udl) << /*character*/0;
267
268     SmallString<32> CharBuffer;
269     bool CharInvalid = false;
270     StringRef ThisTok = PP.getSpelling(PeekTok, CharBuffer, &CharInvalid);
271     if (CharInvalid)
272       return true;
273
274     CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(),
275                               PeekTok.getLocation(), PP, PeekTok.getKind());
276     if (Literal.hadError())
277       return true;  // A diagnostic was already emitted.
278
279     // Character literals are always int or wchar_t, expand to intmax_t.
280     const TargetInfo &TI = PP.getTargetInfo();
281     unsigned NumBits;
282     if (Literal.isMultiChar())
283       NumBits = TI.getIntWidth();
284     else if (Literal.isWide())
285       NumBits = TI.getWCharWidth();
286     else if (Literal.isUTF16())
287       NumBits = TI.getChar16Width();
288     else if (Literal.isUTF32())
289       NumBits = TI.getChar32Width();
290     else
291       NumBits = TI.getCharWidth();
292
293     // Set the width.
294     llvm::APSInt Val(NumBits);
295     // Set the value.
296     Val = Literal.getValue();
297     // Set the signedness. UTF-16 and UTF-32 are always unsigned
298     if (!Literal.isUTF16() && !Literal.isUTF32())
299       Val.setIsUnsigned(!PP.getLangOpts().CharIsSigned);
300
301     if (Result.Val.getBitWidth() > Val.getBitWidth()) {
302       Result.Val = Val.extend(Result.Val.getBitWidth());
303     } else {
304       assert(Result.Val.getBitWidth() == Val.getBitWidth() &&
305              "intmax_t smaller than char/wchar_t?");
306       Result.Val = Val;
307     }
308
309     // Consume the token.
310     Result.setRange(PeekTok.getLocation());
311     PP.LexNonComment(PeekTok);
312     return false;
313   }
314   case tok::l_paren: {
315     SourceLocation Start = PeekTok.getLocation();
316     PP.LexNonComment(PeekTok);  // Eat the (.
317     // Parse the value and if there are any binary operators involved, parse
318     // them.
319     if (EvaluateValue(Result, PeekTok, DT, ValueLive, PP)) return true;
320
321     // If this is a silly value like (X), which doesn't need parens, check for
322     // !(defined X).
323     if (PeekTok.is(tok::r_paren)) {
324       // Just use DT unmodified as our result.
325     } else {
326       // Otherwise, we have something like (x+y), and we consumed '(x'.
327       if (EvaluateDirectiveSubExpr(Result, 1, PeekTok, ValueLive, PP))
328         return true;
329
330       if (PeekTok.isNot(tok::r_paren)) {
331         PP.Diag(PeekTok.getLocation(), diag::err_pp_expected_rparen)
332           << Result.getRange();
333         PP.Diag(Start, diag::note_matching) << "(";
334         return true;
335       }
336       DT.State = DefinedTracker::Unknown;
337     }
338     Result.setRange(Start, PeekTok.getLocation());
339     PP.LexNonComment(PeekTok);  // Eat the ).
340     return false;
341   }
342   case tok::plus: {
343     SourceLocation Start = PeekTok.getLocation();
344     // Unary plus doesn't modify the value.
345     PP.LexNonComment(PeekTok);
346     if (EvaluateValue(Result, PeekTok, DT, ValueLive, PP)) return true;
347     Result.setBegin(Start);
348     return false;
349   }
350   case tok::minus: {
351     SourceLocation Loc = PeekTok.getLocation();
352     PP.LexNonComment(PeekTok);
353     if (EvaluateValue(Result, PeekTok, DT, ValueLive, PP)) return true;
354     Result.setBegin(Loc);
355
356     // C99 6.5.3.3p3: The sign of the result matches the sign of the operand.
357     Result.Val = -Result.Val;
358
359     // -MININT is the only thing that overflows.  Unsigned never overflows.
360     bool Overflow = !Result.isUnsigned() && Result.Val.isMinSignedValue();
361
362     // If this operator is live and overflowed, report the issue.
363     if (Overflow && ValueLive)
364       PP.Diag(Loc, diag::warn_pp_expr_overflow) << Result.getRange();
365
366     DT.State = DefinedTracker::Unknown;
367     return false;
368   }
369
370   case tok::tilde: {
371     SourceLocation Start = PeekTok.getLocation();
372     PP.LexNonComment(PeekTok);
373     if (EvaluateValue(Result, PeekTok, DT, ValueLive, PP)) return true;
374     Result.setBegin(Start);
375
376     // C99 6.5.3.3p4: The sign of the result matches the sign of the operand.
377     Result.Val = ~Result.Val;
378     DT.State = DefinedTracker::Unknown;
379     return false;
380   }
381
382   case tok::exclaim: {
383     SourceLocation Start = PeekTok.getLocation();
384     PP.LexNonComment(PeekTok);
385     if (EvaluateValue(Result, PeekTok, DT, ValueLive, PP)) return true;
386     Result.setBegin(Start);
387     Result.Val = !Result.Val;
388     // C99 6.5.3.3p5: The sign of the result is 'int', aka it is signed.
389     Result.Val.setIsUnsigned(false);
390
391     if (DT.State == DefinedTracker::DefinedMacro)
392       DT.State = DefinedTracker::NotDefinedMacro;
393     else if (DT.State == DefinedTracker::NotDefinedMacro)
394       DT.State = DefinedTracker::DefinedMacro;
395     return false;
396   }
397
398   // FIXME: Handle #assert
399   }
400 }
401
402
403
404 /// getPrecedence - Return the precedence of the specified binary operator
405 /// token.  This returns:
406 ///   ~0 - Invalid token.
407 ///   14 -> 3 - various operators.
408 ///    0 - 'eod' or ')'
409 static unsigned getPrecedence(tok::TokenKind Kind) {
410   switch (Kind) {
411   default: return ~0U;
412   case tok::percent:
413   case tok::slash:
414   case tok::star:                 return 14;
415   case tok::plus:
416   case tok::minus:                return 13;
417   case tok::lessless:
418   case tok::greatergreater:       return 12;
419   case tok::lessequal:
420   case tok::less:
421   case tok::greaterequal:
422   case tok::greater:              return 11;
423   case tok::exclaimequal:
424   case tok::equalequal:           return 10;
425   case tok::amp:                  return 9;
426   case tok::caret:                return 8;
427   case tok::pipe:                 return 7;
428   case tok::ampamp:               return 6;
429   case tok::pipepipe:             return 5;
430   case tok::question:             return 4;
431   case tok::comma:                return 3;
432   case tok::colon:                return 2;
433   case tok::r_paren:              return 0;// Lowest priority, end of expr.
434   case tok::eod:                  return 0;// Lowest priority, end of directive.
435   }
436 }
437
438
439 /// EvaluateDirectiveSubExpr - Evaluate the subexpression whose first token is
440 /// PeekTok, and whose precedence is PeekPrec.  This returns the result in LHS.
441 ///
442 /// If ValueLive is false, then this value is being evaluated in a context where
443 /// the result is not used.  As such, avoid diagnostics that relate to
444 /// evaluation, such as division by zero warnings.
445 static bool EvaluateDirectiveSubExpr(PPValue &LHS, unsigned MinPrec,
446                                      Token &PeekTok, bool ValueLive,
447                                      Preprocessor &PP) {
448   unsigned PeekPrec = getPrecedence(PeekTok.getKind());
449   // If this token isn't valid, report the error.
450   if (PeekPrec == ~0U) {
451     PP.Diag(PeekTok.getLocation(), diag::err_pp_expr_bad_token_binop)
452       << LHS.getRange();
453     return true;
454   }
455
456   while (1) {
457     // If this token has a lower precedence than we are allowed to parse, return
458     // it so that higher levels of the recursion can parse it.
459     if (PeekPrec < MinPrec)
460       return false;
461
462     tok::TokenKind Operator = PeekTok.getKind();
463
464     // If this is a short-circuiting operator, see if the RHS of the operator is
465     // dead.  Note that this cannot just clobber ValueLive.  Consider
466     // "0 && 1 ? 4 : 1 / 0", which is parsed as "(0 && 1) ? 4 : (1 / 0)".  In
467     // this example, the RHS of the && being dead does not make the rest of the
468     // expr dead.
469     bool RHSIsLive;
470     if (Operator == tok::ampamp && LHS.Val == 0)
471       RHSIsLive = false;   // RHS of "0 && x" is dead.
472     else if (Operator == tok::pipepipe && LHS.Val != 0)
473       RHSIsLive = false;   // RHS of "1 || x" is dead.
474     else if (Operator == tok::question && LHS.Val == 0)
475       RHSIsLive = false;   // RHS (x) of "0 ? x : y" is dead.
476     else
477       RHSIsLive = ValueLive;
478
479     // Consume the operator, remembering the operator's location for reporting.
480     SourceLocation OpLoc = PeekTok.getLocation();
481     PP.LexNonComment(PeekTok);
482
483     PPValue RHS(LHS.getBitWidth());
484     // Parse the RHS of the operator.
485     DefinedTracker DT;
486     if (EvaluateValue(RHS, PeekTok, DT, RHSIsLive, PP)) return true;
487
488     // Remember the precedence of this operator and get the precedence of the
489     // operator immediately to the right of the RHS.
490     unsigned ThisPrec = PeekPrec;
491     PeekPrec = getPrecedence(PeekTok.getKind());
492
493     // If this token isn't valid, report the error.
494     if (PeekPrec == ~0U) {
495       PP.Diag(PeekTok.getLocation(), diag::err_pp_expr_bad_token_binop)
496         << RHS.getRange();
497       return true;
498     }
499
500     // Decide whether to include the next binop in this subexpression.  For
501     // example, when parsing x+y*z and looking at '*', we want to recursively
502     // handle y*z as a single subexpression.  We do this because the precedence
503     // of * is higher than that of +.  The only strange case we have to handle
504     // here is for the ?: operator, where the precedence is actually lower than
505     // the LHS of the '?'.  The grammar rule is:
506     //
507     // conditional-expression ::=
508     //    logical-OR-expression ? expression : conditional-expression
509     // where 'expression' is actually comma-expression.
510     unsigned RHSPrec;
511     if (Operator == tok::question)
512       // The RHS of "?" should be maximally consumed as an expression.
513       RHSPrec = getPrecedence(tok::comma);
514     else  // All others should munch while higher precedence.
515       RHSPrec = ThisPrec+1;
516
517     if (PeekPrec >= RHSPrec) {
518       if (EvaluateDirectiveSubExpr(RHS, RHSPrec, PeekTok, RHSIsLive, PP))
519         return true;
520       PeekPrec = getPrecedence(PeekTok.getKind());
521     }
522     assert(PeekPrec <= ThisPrec && "Recursion didn't work!");
523
524     // Usual arithmetic conversions (C99 6.3.1.8p1): result is unsigned if
525     // either operand is unsigned.
526     llvm::APSInt Res(LHS.getBitWidth());
527     switch (Operator) {
528     case tok::question:       // No UAC for x and y in "x ? y : z".
529     case tok::lessless:       // Shift amount doesn't UAC with shift value.
530     case tok::greatergreater: // Shift amount doesn't UAC with shift value.
531     case tok::comma:          // Comma operands are not subject to UACs.
532     case tok::pipepipe:       // Logical || does not do UACs.
533     case tok::ampamp:         // Logical && does not do UACs.
534       break;                  // No UAC
535     default:
536       Res.setIsUnsigned(LHS.isUnsigned()|RHS.isUnsigned());
537       // If this just promoted something from signed to unsigned, and if the
538       // value was negative, warn about it.
539       if (ValueLive && Res.isUnsigned()) {
540         if (!LHS.isUnsigned() && LHS.Val.isNegative())
541           PP.Diag(OpLoc, diag::warn_pp_convert_lhs_to_positive)
542             << LHS.Val.toString(10, true) + " to " +
543                LHS.Val.toString(10, false)
544             << LHS.getRange() << RHS.getRange();
545         if (!RHS.isUnsigned() && RHS.Val.isNegative())
546           PP.Diag(OpLoc, diag::warn_pp_convert_rhs_to_positive)
547             << RHS.Val.toString(10, true) + " to " +
548                RHS.Val.toString(10, false)
549             << LHS.getRange() << RHS.getRange();
550       }
551       LHS.Val.setIsUnsigned(Res.isUnsigned());
552       RHS.Val.setIsUnsigned(Res.isUnsigned());
553     }
554
555     bool Overflow = false;
556     switch (Operator) {
557     default: llvm_unreachable("Unknown operator token!");
558     case tok::percent:
559       if (RHS.Val != 0)
560         Res = LHS.Val % RHS.Val;
561       else if (ValueLive) {
562         PP.Diag(OpLoc, diag::err_pp_remainder_by_zero)
563           << LHS.getRange() << RHS.getRange();
564         return true;
565       }
566       break;
567     case tok::slash:
568       if (RHS.Val != 0) {
569         if (LHS.Val.isSigned())
570           Res = llvm::APSInt(LHS.Val.sdiv_ov(RHS.Val, Overflow), false);
571         else
572           Res = LHS.Val / RHS.Val;
573       } else if (ValueLive) {
574         PP.Diag(OpLoc, diag::err_pp_division_by_zero)
575           << LHS.getRange() << RHS.getRange();
576         return true;
577       }
578       break;
579
580     case tok::star:
581       if (Res.isSigned())
582         Res = llvm::APSInt(LHS.Val.smul_ov(RHS.Val, Overflow), false);
583       else
584         Res = LHS.Val * RHS.Val;
585       break;
586     case tok::lessless: {
587       // Determine whether overflow is about to happen.
588       unsigned ShAmt = static_cast<unsigned>(RHS.Val.getLimitedValue());
589       if (LHS.isUnsigned()) {
590         Overflow = ShAmt >= LHS.Val.getBitWidth();
591         if (Overflow)
592           ShAmt = LHS.Val.getBitWidth()-1;
593         Res = LHS.Val << ShAmt;
594       } else {
595         Res = llvm::APSInt(LHS.Val.sshl_ov(ShAmt, Overflow), false);
596       }
597       break;
598     }
599     case tok::greatergreater: {
600       // Determine whether overflow is about to happen.
601       unsigned ShAmt = static_cast<unsigned>(RHS.Val.getLimitedValue());
602       if (ShAmt >= LHS.getBitWidth())
603         Overflow = true, ShAmt = LHS.getBitWidth()-1;
604       Res = LHS.Val >> ShAmt;
605       break;
606     }
607     case tok::plus:
608       if (LHS.isUnsigned())
609         Res = LHS.Val + RHS.Val;
610       else
611         Res = llvm::APSInt(LHS.Val.sadd_ov(RHS.Val, Overflow), false);
612       break;
613     case tok::minus:
614       if (LHS.isUnsigned())
615         Res = LHS.Val - RHS.Val;
616       else
617         Res = llvm::APSInt(LHS.Val.ssub_ov(RHS.Val, Overflow), false);
618       break;
619     case tok::lessequal:
620       Res = LHS.Val <= RHS.Val;
621       Res.setIsUnsigned(false);  // C99 6.5.8p6, result is always int (signed)
622       break;
623     case tok::less:
624       Res = LHS.Val < RHS.Val;
625       Res.setIsUnsigned(false);  // C99 6.5.8p6, result is always int (signed)
626       break;
627     case tok::greaterequal:
628       Res = LHS.Val >= RHS.Val;
629       Res.setIsUnsigned(false);  // C99 6.5.8p6, result is always int (signed)
630       break;
631     case tok::greater:
632       Res = LHS.Val > RHS.Val;
633       Res.setIsUnsigned(false);  // C99 6.5.8p6, result is always int (signed)
634       break;
635     case tok::exclaimequal:
636       Res = LHS.Val != RHS.Val;
637       Res.setIsUnsigned(false);  // C99 6.5.9p3, result is always int (signed)
638       break;
639     case tok::equalequal:
640       Res = LHS.Val == RHS.Val;
641       Res.setIsUnsigned(false);  // C99 6.5.9p3, result is always int (signed)
642       break;
643     case tok::amp:
644       Res = LHS.Val & RHS.Val;
645       break;
646     case tok::caret:
647       Res = LHS.Val ^ RHS.Val;
648       break;
649     case tok::pipe:
650       Res = LHS.Val | RHS.Val;
651       break;
652     case tok::ampamp:
653       Res = (LHS.Val != 0 && RHS.Val != 0);
654       Res.setIsUnsigned(false);  // C99 6.5.13p3, result is always int (signed)
655       break;
656     case tok::pipepipe:
657       Res = (LHS.Val != 0 || RHS.Val != 0);
658       Res.setIsUnsigned(false);  // C99 6.5.14p3, result is always int (signed)
659       break;
660     case tok::comma:
661       // Comma is invalid in pp expressions in c89/c++ mode, but is valid in C99
662       // if not being evaluated.
663       if (!PP.getLangOpts().C99 || ValueLive)
664         PP.Diag(OpLoc, diag::ext_pp_comma_expr)
665           << LHS.getRange() << RHS.getRange();
666       Res = RHS.Val; // LHS = LHS,RHS -> RHS.
667       break;
668     case tok::question: {
669       // Parse the : part of the expression.
670       if (PeekTok.isNot(tok::colon)) {
671         PP.Diag(PeekTok.getLocation(), diag::err_expected_colon)
672           << LHS.getRange(), RHS.getRange();
673         PP.Diag(OpLoc, diag::note_matching) << "?";
674         return true;
675       }
676       // Consume the :.
677       PP.LexNonComment(PeekTok);
678
679       // Evaluate the value after the :.
680       bool AfterColonLive = ValueLive && LHS.Val == 0;
681       PPValue AfterColonVal(LHS.getBitWidth());
682       DefinedTracker DT;
683       if (EvaluateValue(AfterColonVal, PeekTok, DT, AfterColonLive, PP))
684         return true;
685
686       // Parse anything after the : with the same precedence as ?.  We allow
687       // things of equal precedence because ?: is right associative.
688       if (EvaluateDirectiveSubExpr(AfterColonVal, ThisPrec,
689                                    PeekTok, AfterColonLive, PP))
690         return true;
691
692       // Now that we have the condition, the LHS and the RHS of the :, evaluate.
693       Res = LHS.Val != 0 ? RHS.Val : AfterColonVal.Val;
694       RHS.setEnd(AfterColonVal.getRange().getEnd());
695
696       // Usual arithmetic conversions (C99 6.3.1.8p1): result is unsigned if
697       // either operand is unsigned.
698       Res.setIsUnsigned(RHS.isUnsigned() | AfterColonVal.isUnsigned());
699
700       // Figure out the precedence of the token after the : part.
701       PeekPrec = getPrecedence(PeekTok.getKind());
702       break;
703     }
704     case tok::colon:
705       // Don't allow :'s to float around without being part of ?: exprs.
706       PP.Diag(OpLoc, diag::err_pp_colon_without_question)
707         << LHS.getRange() << RHS.getRange();
708       return true;
709     }
710
711     // If this operator is live and overflowed, report the issue.
712     if (Overflow && ValueLive)
713       PP.Diag(OpLoc, diag::warn_pp_expr_overflow)
714         << LHS.getRange() << RHS.getRange();
715
716     // Put the result back into 'LHS' for our next iteration.
717     LHS.Val = Res;
718     LHS.setEnd(RHS.getRange().getEnd());
719   }
720 }
721
722 /// EvaluateDirectiveExpression - Evaluate an integer constant expression that
723 /// may occur after a #if or #elif directive.  If the expression is equivalent
724 /// to "!defined(X)" return X in IfNDefMacro.
725 bool Preprocessor::
726 EvaluateDirectiveExpression(IdentifierInfo *&IfNDefMacro) {
727   // Save the current state of 'DisableMacroExpansion' and reset it to false. If
728   // 'DisableMacroExpansion' is true, then we must be in a macro argument list
729   // in which case a directive is undefined behavior.  We want macros to be able
730   // to recursively expand in order to get more gcc-list behavior, so we force
731   // DisableMacroExpansion to false and restore it when we're done parsing the
732   // expression.
733   bool DisableMacroExpansionAtStartOfDirective = DisableMacroExpansion;
734   DisableMacroExpansion = false;
735   
736   // Peek ahead one token.
737   Token Tok;
738   LexNonComment(Tok);
739   
740   // C99 6.10.1p3 - All expressions are evaluated as intmax_t or uintmax_t.
741   unsigned BitWidth = getTargetInfo().getIntMaxTWidth();
742
743   PPValue ResVal(BitWidth);
744   DefinedTracker DT;
745   if (EvaluateValue(ResVal, Tok, DT, true, *this)) {
746     // Parse error, skip the rest of the macro line.
747     if (Tok.isNot(tok::eod))
748       DiscardUntilEndOfDirective();
749     
750     // Restore 'DisableMacroExpansion'.
751     DisableMacroExpansion = DisableMacroExpansionAtStartOfDirective;
752     return false;
753   }
754
755   // If we are at the end of the expression after just parsing a value, there
756   // must be no (unparenthesized) binary operators involved, so we can exit
757   // directly.
758   if (Tok.is(tok::eod)) {
759     // If the expression we parsed was of the form !defined(macro), return the
760     // macro in IfNDefMacro.
761     if (DT.State == DefinedTracker::NotDefinedMacro)
762       IfNDefMacro = DT.TheMacro;
763
764     // Restore 'DisableMacroExpansion'.
765     DisableMacroExpansion = DisableMacroExpansionAtStartOfDirective;
766     return ResVal.Val != 0;
767   }
768
769   // Otherwise, we must have a binary operator (e.g. "#if 1 < 2"), so parse the
770   // operator and the stuff after it.
771   if (EvaluateDirectiveSubExpr(ResVal, getPrecedence(tok::question),
772                                Tok, true, *this)) {
773     // Parse error, skip the rest of the macro line.
774     if (Tok.isNot(tok::eod))
775       DiscardUntilEndOfDirective();
776     
777     // Restore 'DisableMacroExpansion'.
778     DisableMacroExpansion = DisableMacroExpansionAtStartOfDirective;
779     return false;
780   }
781
782   // If we aren't at the tok::eod token, something bad happened, like an extra
783   // ')' token.
784   if (Tok.isNot(tok::eod)) {
785     Diag(Tok, diag::err_pp_expected_eol);
786     DiscardUntilEndOfDirective();
787   }
788
789   // Restore 'DisableMacroExpansion'.
790   DisableMacroExpansion = DisableMacroExpansionAtStartOfDirective;
791   return ResVal.Val != 0;
792 }