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