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