1 //===--- PPExpressions.cpp - Preprocessor Expression Evaluation -----------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the Preprocessor::EvaluateDirectiveExpression method,
11 // which parses and evaluates integer constant expressions for #if directives.
13 //===----------------------------------------------------------------------===//
15 // FIXME: implement testing for #assert's.
17 //===----------------------------------------------------------------------===//
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"
38 using namespace clang;
42 /// PPValue - Represents the value of a subexpression of a preprocessor
43 /// conditional and the source range covered by it.
51 // Default ctor - Construct an 'invalid' PPValue.
52 PPValue(unsigned BitWidth) : Val(BitWidth) {}
54 // If this value was produced by directly evaluating an identifier, produce
56 IdentifierInfo *getIdentifier() const { return II; }
57 void setIdentifier(IdentifierInfo *II) { this->II = II; }
59 unsigned getBitWidth() const { return Val.getBitWidth(); }
60 bool isUnsigned() const { return Val.isUnsigned(); }
62 SourceRange getRange() const { return Range; }
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);
68 void setBegin(SourceLocation L) { Range.setBegin(L); }
69 void setEnd(SourceLocation L) { Range.setEnd(L); }
72 } // end anonymous namespace
74 static bool EvaluateDirectiveSubExpr(PPValue &LHS, unsigned MinPrec,
75 Token &PeekTok, bool ValueLive,
76 bool &IncludedUndefinedIds,
79 /// DefinedTracker - This struct is used while parsing expressions to keep track
80 /// of whether !defined(X) has been seen.
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.
90 DefinedMacro, // defined(X)
91 NotDefinedMacro, // !defined(X)
92 Unknown // Something else.
94 /// TheMacro - When the state is DefinedMacro or NotDefinedMacro, this
95 /// indicates the macro that was checked.
96 IdentifierInfo *TheMacro;
97 bool IncludedUndefinedIds = false;
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);
106 // Get the next token, don't expand it.
107 PP.LexUnexpandedNonComment(PeekTok);
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);
117 if (PeekTok.is(tok::code_completion)) {
118 if (PP.getCodeCompletionHandler())
119 PP.getCodeCompletionHandler()->CodeCompleteMacroName(false);
120 PP.setCodeCompletionReached();
121 PP.LexUnexpandedNonComment(PeekTok);
124 // If we don't have a pp-identifier now, this is an error.
125 if (PP.CheckMacroName(PeekTok, MU_Other))
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;
135 // If there is a macro, mark it used.
136 if (Result.Val != 0 && ValueLive)
137 PP.markMacroAsUsed(Macro.getMacroInfo());
139 // Save macro token for callback.
140 Token macroToken(PeekTok);
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);
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;
155 Result.setEnd(PeekTok.getLocation());
156 PP.LexNonComment(PeekTok);
158 // Consume identifier.
159 Result.setEnd(PeekTok.getLocation());
160 PP.LexNonComment(PeekTok);
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:
173 // #define BAR defined(FOO)
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))
186 .isFunctionMacroExpansion();
187 // For object-type macros, it's easy to replace
188 // #define FOO defined(BAR)
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);
205 PP.Diag(beginLoc, diag::warn_defined_in_object_type_macro);
208 // Invoke the 'defined' callback.
209 if (PPCallbacks *Callbacks = PP.getPPCallbacks()) {
210 Callbacks->Defined(macroToken, Macro,
211 SourceRange(beginLoc, PeekTok.getLocation()));
214 // Success, remember that we saw defined(X).
215 DT.State = DefinedTracker::DefinedMacro;
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.
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
228 static bool EvaluateValue(PPValue &Result, Token &PeekTok, DefinedTracker &DT,
229 bool ValueLive, Preprocessor &PP) {
230 DT.State = DefinedTracker::Unknown;
232 Result.setIdentifier(nullptr);
234 if (PeekTok.is(tok::code_completion)) {
235 if (PP.getCodeCompletionHandler())
236 PP.getCodeCompletionHandler()->CodeCompletePreprocessorExpression();
237 PP.setCodeCompletionReached();
238 PP.LexNonComment(PeekTok);
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);
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
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);
267 switch (PeekTok.getKind()) {
268 default: // Non-value token.
269 PP.Diag(PeekTok, diag::err_pp_expr_bad_token_start_expr);
273 // If there is no expression, report and exit.
274 PP.Diag(PeekTok, diag::err_pp_expected_value_in_expr);
276 case tok::numeric_constant: {
277 SmallString<64> IntegerBuffer;
278 bool NumberInvalid = false;
279 StringRef Spelling = PP.getSpelling(PeekTok, IntegerBuffer,
282 return true; // a diagnostic was already reported
284 NumericLiteralParser Literal(Spelling, PeekTok.getLocation(), PP);
285 if (Literal.hadError)
286 return true; // a diagnostic was already reported.
288 if (Literal.isFloatingLiteral() || Literal.isImaginary) {
289 PP.Diag(PeekTok, diag::err_pp_illegal_floating_literal);
292 assert(Literal.isIntegerLiteral() && "Unknown ppnumber");
294 // Complain about, and drop, any ud-suffix.
295 if (Literal.hasUDSuffix())
296 PP.Diag(PeekTok, diag::err_pp_invalid_udl) << /*integer*/1;
298 // 'long long' is a C99 or C++11 feature.
299 if (!PP.getLangOpts().C99 && Literal.isLongLong) {
300 if (PP.getLangOpts().CPlusPlus)
302 PP.getLangOpts().CPlusPlus11 ?
303 diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong);
305 PP.Diag(PeekTok, diag::ext_c99_longlong);
308 // Parse the integer literal into Result.
309 if (Literal.GetIntegerValue(Result.Val)) {
310 // Overflow parsing integer literal.
312 PP.Diag(PeekTok, diag::err_integer_literal_too_large)
314 Result.Val.setIsUnsigned(true);
316 // Set the signedness of the result to match whether there was a U suffix
318 Result.Val.setIsUnsigned(Literal.isUnsigned);
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
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);
333 // Consume the token.
334 Result.setRange(PeekTok.getLocation());
335 PP.LexNonComment(PeekTok);
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;
347 SmallString<32> CharBuffer;
348 bool CharInvalid = false;
349 StringRef ThisTok = PP.getSpelling(PeekTok, CharBuffer, &CharInvalid);
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.
358 // Character literals are always int or wchar_t, expand to intmax_t.
359 const TargetInfo &TI = PP.getTargetInfo();
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();
370 NumBits = TI.getCharWidth();
373 llvm::APSInt Val(NumBits);
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);
382 if (Result.Val.getBitWidth() > Val.getBitWidth()) {
383 Result.Val = Val.extend(Result.Val.getBitWidth());
385 assert(Result.Val.getBitWidth() == Val.getBitWidth() &&
386 "intmax_t smaller than char/wchar_t?");
390 // Consume the token.
391 Result.setRange(PeekTok.getLocation());
392 PP.LexNonComment(PeekTok);
396 SourceLocation Start = PeekTok.getLocation();
397 PP.LexNonComment(PeekTok); // Eat the (.
398 // Parse the value and if there are any binary operators involved, parse
400 if (EvaluateValue(Result, PeekTok, DT, ValueLive, PP)) return true;
402 // If this is a silly value like (X), which doesn't need parens, check for
404 if (PeekTok.is(tok::r_paren)) {
405 // Just use DT unmodified as our result.
407 // Otherwise, we have something like (x+y), and we consumed '(x'.
408 if (EvaluateDirectiveSubExpr(Result, 1, PeekTok, ValueLive,
409 DT.IncludedUndefinedIds, PP))
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;
418 DT.State = DefinedTracker::Unknown;
420 Result.setRange(Start, PeekTok.getLocation());
421 Result.setIdentifier(nullptr);
422 PP.LexNonComment(PeekTok); // Eat the ).
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);
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);
441 // C99 6.5.3.3p3: The sign of the result matches the sign of the operand.
442 Result.Val = -Result.Val;
444 // -MININT is the only thing that overflows. Unsigned never overflows.
445 bool Overflow = !Result.isUnsigned() && Result.Val.isMinSignedValue();
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();
451 DT.State = DefinedTracker::Unknown;
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);
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;
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);
478 if (DT.State == DefinedTracker::DefinedMacro)
479 DT.State = DefinedTracker::NotDefinedMacro;
480 else if (DT.State == DefinedTracker::NotDefinedMacro)
481 DT.State = DefinedTracker::DefinedMacro;
485 // FIXME: Handle #assert
489 /// getPrecedence - Return the precedence of the specified binary operator
490 /// token. This returns:
491 /// ~0 - Invalid token.
492 /// 14 -> 3 - various operators.
494 static unsigned getPrecedence(tok::TokenKind Kind) {
499 case tok::star: return 14;
501 case tok::minus: return 13;
503 case tok::greatergreater: return 12;
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.
523 static void diagnoseUnexpectedOperator(Preprocessor &PP, PPValue &LHS,
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();
529 PP.Diag(Tok.getLocation(), diag::err_pp_expr_bad_token_binop)
533 /// EvaluateDirectiveSubExpr - Evaluate the subexpression whose first token is
534 /// PeekTok, and whose precedence is PeekPrec. This returns the result in LHS.
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,
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);
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)
556 tok::TokenKind Operator = PeekTok.getKind();
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
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.
571 RHSIsLive = ValueLive;
573 // Consume the operator, remembering the operator's location for reporting.
574 SourceLocation OpLoc = PeekTok.getLocation();
575 PP.LexNonComment(PeekTok);
577 PPValue RHS(LHS.getBitWidth());
578 // Parse the RHS of the operator.
580 if (EvaluateValue(RHS, PeekTok, DT, RHSIsLive, PP)) return true;
581 IncludedUndefinedIds = DT.IncludedUndefinedIds;
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());
588 // If this token isn't valid, report the error.
589 if (PeekPrec == ~0U) {
590 diagnoseUnexpectedOperator(PP, RHS, PeekTok);
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:
601 // conditional-expression ::=
602 // logical-OR-expression ? expression : conditional-expression
603 // where 'expression' is actually comma-expression.
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;
611 if (PeekPrec >= RHSPrec) {
612 if (EvaluateDirectiveSubExpr(RHS, RHSPrec, PeekTok, RHSIsLive,
613 IncludedUndefinedIds, PP))
615 PeekPrec = getPrecedence(PeekTok.getKind());
617 assert(PeekPrec <= ThisPrec && "Recursion didn't work!");
619 // Usual arithmetic conversions (C99 6.3.1.8p1): result is unsigned if
620 // either operand is unsigned.
621 llvm::APSInt Res(LHS.getBitWidth());
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.
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();
646 LHS.Val.setIsUnsigned(Res.isUnsigned());
647 RHS.Val.setIsUnsigned(Res.isUnsigned());
650 bool Overflow = false;
652 default: llvm_unreachable("Unknown operator token!");
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();
664 if (LHS.Val.isSigned())
665 Res = llvm::APSInt(LHS.Val.sdiv_ov(RHS.Val, Overflow), false);
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();
677 Res = llvm::APSInt(LHS.Val.smul_ov(RHS.Val, Overflow), false);
679 Res = LHS.Val * RHS.Val;
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);
686 Res = llvm::APSInt(LHS.Val.sshl_ov(RHS.Val, Overflow), false);
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()) {
694 ShAmt = LHS.getBitWidth()-1;
696 Res = LHS.Val >> ShAmt;
700 if (LHS.isUnsigned())
701 Res = LHS.Val + RHS.Val;
703 Res = llvm::APSInt(LHS.Val.sadd_ov(RHS.Val, Overflow), false);
706 if (LHS.isUnsigned())
707 Res = LHS.Val - RHS.Val;
709 Res = llvm::APSInt(LHS.Val.ssub_ov(RHS.Val, Overflow), false);
712 Res = LHS.Val <= RHS.Val;
713 Res.setIsUnsigned(false); // C99 6.5.8p6, result is always int (signed)
716 Res = LHS.Val < RHS.Val;
717 Res.setIsUnsigned(false); // C99 6.5.8p6, result is always int (signed)
719 case tok::greaterequal:
720 Res = LHS.Val >= RHS.Val;
721 Res.setIsUnsigned(false); // C99 6.5.8p6, result is always int (signed)
724 Res = LHS.Val > RHS.Val;
725 Res.setIsUnsigned(false); // C99 6.5.8p6, result is always int (signed)
727 case tok::exclaimequal:
728 Res = LHS.Val != RHS.Val;
729 Res.setIsUnsigned(false); // C99 6.5.9p3, result is always int (signed)
731 case tok::equalequal:
732 Res = LHS.Val == RHS.Val;
733 Res.setIsUnsigned(false); // C99 6.5.9p3, result is always int (signed)
736 Res = LHS.Val & RHS.Val;
739 Res = LHS.Val ^ RHS.Val;
742 Res = LHS.Val | RHS.Val;
745 Res = (LHS.Val != 0 && RHS.Val != 0);
746 Res.setIsUnsigned(false); // C99 6.5.13p3, result is always int (signed)
749 Res = (LHS.Val != 0 || RHS.Val != 0);
750 Res.setIsUnsigned(false); // C99 6.5.14p3, result is always int (signed)
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.
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;
769 PP.LexNonComment(PeekTok);
771 // Evaluate the value after the :.
772 bool AfterColonLive = ValueLive && LHS.Val == 0;
773 PPValue AfterColonVal(LHS.getBitWidth());
775 if (EvaluateValue(AfterColonVal, PeekTok, DT, AfterColonLive, PP))
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))
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());
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());
793 // Figure out the precedence of the token after the : part.
794 PeekPrec = getPrecedence(PeekTok.getKind());
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();
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();
809 // Put the result back into 'LHS' for our next iteration.
811 LHS.setEnd(RHS.getRange().getEnd());
812 RHS.setIdentifier(nullptr);
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
828 bool DisableMacroExpansionAtStartOfDirective = DisableMacroExpansion;
829 DisableMacroExpansion = false;
831 // Peek ahead one token.
835 // C99 6.10.1p3 - All expressions are evaluated as intmax_t or uintmax_t.
836 unsigned BitWidth = getTargetInfo().getIntMaxTWidth();
838 PPValue ResVal(BitWidth);
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();
845 // Restore 'DisableMacroExpansion'.
846 DisableMacroExpansion = DisableMacroExpansionAtStartOfDirective;
847 return {false, DT.IncludedUndefinedIds};
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
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;
859 // Restore 'DisableMacroExpansion'.
860 DisableMacroExpansion = DisableMacroExpansionAtStartOfDirective;
861 return {ResVal.Val != 0, DT.IncludedUndefinedIds};
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();
872 // Restore 'DisableMacroExpansion'.
873 DisableMacroExpansion = DisableMacroExpansionAtStartOfDirective;
874 return {false, DT.IncludedUndefinedIds};
877 // If we aren't at the tok::eod token, something bad happened, like an extra
879 if (Tok.isNot(tok::eod)) {
880 Diag(Tok, diag::err_pp_expected_eol);
881 DiscardUntilEndOfDirective();
884 // Restore 'DisableMacroExpansion'.
885 DisableMacroExpansion = DisableMacroExpansionAtStartOfDirective;
886 return {ResVal.Val != 0, DT.IncludedUndefinedIds};