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,
78 /// DefinedTracker - This struct is used while parsing expressions to keep track
79 /// of whether !defined(X) has been seen.
81 /// With this simple scheme, we handle the basic forms:
82 /// !defined(X) and !defined X
83 /// but we also trivially handle (silly) stuff like:
84 /// !!!defined(X) and +!defined(X) and !+!+!defined(X) and !(defined(X)).
85 struct DefinedTracker {
86 /// Each time a Value is evaluated, it returns information about whether the
87 /// parsed value is of the form defined(X), !defined(X) or is something else.
89 DefinedMacro, // defined(X)
90 NotDefinedMacro, // !defined(X)
91 Unknown // Something else.
93 /// TheMacro - When the state is DefinedMacro or NotDefinedMacro, this
94 /// indicates the macro that was checked.
95 IdentifierInfo *TheMacro;
98 /// EvaluateDefined - Process a 'defined(sym)' expression.
99 static bool EvaluateDefined(PPValue &Result, Token &PeekTok, DefinedTracker &DT,
100 bool ValueLive, Preprocessor &PP) {
101 SourceLocation beginLoc(PeekTok.getLocation());
102 Result.setBegin(beginLoc);
104 // Get the next token, don't expand it.
105 PP.LexUnexpandedNonComment(PeekTok);
107 // Two options, it can either be a pp-identifier or a (.
108 SourceLocation LParenLoc;
109 if (PeekTok.is(tok::l_paren)) {
110 // Found a paren, remember we saw it and skip it.
111 LParenLoc = PeekTok.getLocation();
112 PP.LexUnexpandedNonComment(PeekTok);
115 if (PeekTok.is(tok::code_completion)) {
116 if (PP.getCodeCompletionHandler())
117 PP.getCodeCompletionHandler()->CodeCompleteMacroName(false);
118 PP.setCodeCompletionReached();
119 PP.LexUnexpandedNonComment(PeekTok);
122 // If we don't have a pp-identifier now, this is an error.
123 if (PP.CheckMacroName(PeekTok, MU_Other))
126 // Otherwise, we got an identifier, is it defined to something?
127 IdentifierInfo *II = PeekTok.getIdentifierInfo();
128 MacroDefinition Macro = PP.getMacroDefinition(II);
129 Result.Val = !!Macro;
130 Result.Val.setIsUnsigned(false); // Result is signed intmax_t.
132 // If there is a macro, mark it used.
133 if (Result.Val != 0 && ValueLive)
134 PP.markMacroAsUsed(Macro.getMacroInfo());
136 // Save macro token for callback.
137 Token macroToken(PeekTok);
139 // If we are in parens, ensure we have a trailing ).
140 if (LParenLoc.isValid()) {
141 // Consume identifier.
142 Result.setEnd(PeekTok.getLocation());
143 PP.LexUnexpandedNonComment(PeekTok);
145 if (PeekTok.isNot(tok::r_paren)) {
146 PP.Diag(PeekTok.getLocation(), diag::err_pp_expected_after)
147 << "'defined'" << tok::r_paren;
148 PP.Diag(LParenLoc, diag::note_matching) << tok::l_paren;
152 Result.setEnd(PeekTok.getLocation());
153 PP.LexNonComment(PeekTok);
155 // Consume identifier.
156 Result.setEnd(PeekTok.getLocation());
157 PP.LexNonComment(PeekTok);
161 // Prior to evaluation, macro invocations in the list of preprocessing
162 // tokens that will become the controlling constant expression are replaced
163 // (except for those macro names modified by the 'defined' unary operator),
164 // just as in normal text. If the token 'defined' is generated as a result
165 // of this replacement process or use of the 'defined' unary operator does
166 // not match one of the two specified forms prior to macro replacement, the
167 // behavior is undefined.
168 // This isn't an idle threat, consider this program:
170 // #define BAR defined(FOO)
176 // clang and gcc will pick the #if branch while Visual Studio will take the
177 // #else branch. Emit a warning about this undefined behavior.
178 if (beginLoc.isMacroID()) {
179 bool IsFunctionTypeMacro =
180 PP.getSourceManager()
181 .getSLocEntry(PP.getSourceManager().getFileID(beginLoc))
183 .isFunctionMacroExpansion();
184 // For object-type macros, it's easy to replace
185 // #define FOO defined(BAR)
192 // and doing so makes sense since compilers handle this differently in
193 // practice (see example further up). But for function-type macros,
194 // there is no good way to write
195 // # define FOO(x) (defined(M_ ## x) && M_ ## x)
196 // in a different way, and compilers seem to agree on how to behave here.
197 // So warn by default on object-type macros, but only warn in -pedantic
198 // mode on function-type macros.
199 if (IsFunctionTypeMacro)
200 PP.Diag(beginLoc, diag::warn_defined_in_function_type_macro);
202 PP.Diag(beginLoc, diag::warn_defined_in_object_type_macro);
205 // Invoke the 'defined' callback.
206 if (PPCallbacks *Callbacks = PP.getPPCallbacks()) {
207 Callbacks->Defined(macroToken, Macro,
208 SourceRange(beginLoc, PeekTok.getLocation()));
211 // Success, remember that we saw defined(X).
212 DT.State = DefinedTracker::DefinedMacro;
217 /// EvaluateValue - Evaluate the token PeekTok (and any others needed) and
218 /// return the computed value in Result. Return true if there was an error
219 /// parsing. This function also returns information about the form of the
220 /// expression in DT. See above for information on what DT means.
222 /// If ValueLive is false, then this value is being evaluated in a context where
223 /// the result is not used. As such, avoid diagnostics that relate to
225 static bool EvaluateValue(PPValue &Result, Token &PeekTok, DefinedTracker &DT,
226 bool ValueLive, Preprocessor &PP) {
227 DT.State = DefinedTracker::Unknown;
229 Result.setIdentifier(nullptr);
231 if (PeekTok.is(tok::code_completion)) {
232 if (PP.getCodeCompletionHandler())
233 PP.getCodeCompletionHandler()->CodeCompletePreprocessorExpression();
234 PP.setCodeCompletionReached();
235 PP.LexNonComment(PeekTok);
238 // If this token's spelling is a pp-identifier, check to see if it is
239 // 'defined' or if it is a macro. Note that we check here because many
240 // keywords are pp-identifiers, so we can't check the kind.
241 if (IdentifierInfo *II = PeekTok.getIdentifierInfo()) {
242 // Handle "defined X" and "defined(X)".
243 if (II->isStr("defined"))
244 return EvaluateDefined(Result, PeekTok, DT, ValueLive, PP);
246 // If this identifier isn't 'defined' or one of the special
247 // preprocessor keywords and it wasn't macro expanded, it turns
248 // into a simple 0, unless it is the C++ keyword "true", in which case it
251 II->getTokenID() != tok::kw_true &&
252 II->getTokenID() != tok::kw_false)
253 PP.Diag(PeekTok, diag::warn_pp_undef_identifier) << II;
254 Result.Val = II->getTokenID() == tok::kw_true;
255 Result.Val.setIsUnsigned(false); // "0" is signed intmax_t 0.
256 Result.setIdentifier(II);
257 Result.setRange(PeekTok.getLocation());
258 PP.LexNonComment(PeekTok);
262 switch (PeekTok.getKind()) {
263 default: // Non-value token.
264 PP.Diag(PeekTok, diag::err_pp_expr_bad_token_start_expr);
268 // If there is no expression, report and exit.
269 PP.Diag(PeekTok, diag::err_pp_expected_value_in_expr);
271 case tok::numeric_constant: {
272 SmallString<64> IntegerBuffer;
273 bool NumberInvalid = false;
274 StringRef Spelling = PP.getSpelling(PeekTok, IntegerBuffer,
277 return true; // a diagnostic was already reported
279 NumericLiteralParser Literal(Spelling, PeekTok.getLocation(), PP);
280 if (Literal.hadError)
281 return true; // a diagnostic was already reported.
283 if (Literal.isFloatingLiteral() || Literal.isImaginary) {
284 PP.Diag(PeekTok, diag::err_pp_illegal_floating_literal);
287 assert(Literal.isIntegerLiteral() && "Unknown ppnumber");
289 // Complain about, and drop, any ud-suffix.
290 if (Literal.hasUDSuffix())
291 PP.Diag(PeekTok, diag::err_pp_invalid_udl) << /*integer*/1;
293 // 'long long' is a C99 or C++11 feature.
294 if (!PP.getLangOpts().C99 && Literal.isLongLong) {
295 if (PP.getLangOpts().CPlusPlus)
297 PP.getLangOpts().CPlusPlus11 ?
298 diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong);
300 PP.Diag(PeekTok, diag::ext_c99_longlong);
303 // Parse the integer literal into Result.
304 if (Literal.GetIntegerValue(Result.Val)) {
305 // Overflow parsing integer literal.
307 PP.Diag(PeekTok, diag::err_integer_literal_too_large)
309 Result.Val.setIsUnsigned(true);
311 // Set the signedness of the result to match whether there was a U suffix
313 Result.Val.setIsUnsigned(Literal.isUnsigned);
315 // Detect overflow based on whether the value is signed. If signed
316 // and if the value is too large, emit a warning "integer constant is so
317 // large that it is unsigned" e.g. on 12345678901234567890 where intmax_t
319 if (!Literal.isUnsigned && Result.Val.isNegative()) {
320 // Octal, hexadecimal, and binary literals are implicitly unsigned if
321 // the value does not fit into a signed integer type.
322 if (ValueLive && Literal.getRadix() == 10)
323 PP.Diag(PeekTok, diag::ext_integer_literal_too_large_for_signed);
324 Result.Val.setIsUnsigned(true);
328 // Consume the token.
329 Result.setRange(PeekTok.getLocation());
330 PP.LexNonComment(PeekTok);
333 case tok::char_constant: // 'x'
334 case tok::wide_char_constant: // L'x'
335 case tok::utf8_char_constant: // u8'x'
336 case tok::utf16_char_constant: // u'x'
337 case tok::utf32_char_constant: { // U'x'
338 // Complain about, and drop, any ud-suffix.
339 if (PeekTok.hasUDSuffix())
340 PP.Diag(PeekTok, diag::err_pp_invalid_udl) << /*character*/0;
342 SmallString<32> CharBuffer;
343 bool CharInvalid = false;
344 StringRef ThisTok = PP.getSpelling(PeekTok, CharBuffer, &CharInvalid);
348 CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(),
349 PeekTok.getLocation(), PP, PeekTok.getKind());
350 if (Literal.hadError())
351 return true; // A diagnostic was already emitted.
353 // Character literals are always int or wchar_t, expand to intmax_t.
354 const TargetInfo &TI = PP.getTargetInfo();
356 if (Literal.isMultiChar())
357 NumBits = TI.getIntWidth();
358 else if (Literal.isWide())
359 NumBits = TI.getWCharWidth();
360 else if (Literal.isUTF16())
361 NumBits = TI.getChar16Width();
362 else if (Literal.isUTF32())
363 NumBits = TI.getChar32Width();
365 NumBits = TI.getCharWidth();
368 llvm::APSInt Val(NumBits);
370 Val = Literal.getValue();
371 // Set the signedness. UTF-16 and UTF-32 are always unsigned
372 if (Literal.isWide())
373 Val.setIsUnsigned(!TargetInfo::isTypeSigned(TI.getWCharType()));
374 else if (!Literal.isUTF16() && !Literal.isUTF32())
375 Val.setIsUnsigned(!PP.getLangOpts().CharIsSigned);
377 if (Result.Val.getBitWidth() > Val.getBitWidth()) {
378 Result.Val = Val.extend(Result.Val.getBitWidth());
380 assert(Result.Val.getBitWidth() == Val.getBitWidth() &&
381 "intmax_t smaller than char/wchar_t?");
385 // Consume the token.
386 Result.setRange(PeekTok.getLocation());
387 PP.LexNonComment(PeekTok);
391 SourceLocation Start = PeekTok.getLocation();
392 PP.LexNonComment(PeekTok); // Eat the (.
393 // Parse the value and if there are any binary operators involved, parse
395 if (EvaluateValue(Result, PeekTok, DT, ValueLive, PP)) return true;
397 // If this is a silly value like (X), which doesn't need parens, check for
399 if (PeekTok.is(tok::r_paren)) {
400 // Just use DT unmodified as our result.
402 // Otherwise, we have something like (x+y), and we consumed '(x'.
403 if (EvaluateDirectiveSubExpr(Result, 1, PeekTok, ValueLive, PP))
406 if (PeekTok.isNot(tok::r_paren)) {
407 PP.Diag(PeekTok.getLocation(), diag::err_pp_expected_rparen)
408 << Result.getRange();
409 PP.Diag(Start, diag::note_matching) << tok::l_paren;
412 DT.State = DefinedTracker::Unknown;
414 Result.setRange(Start, PeekTok.getLocation());
415 Result.setIdentifier(nullptr);
416 PP.LexNonComment(PeekTok); // Eat the ).
420 SourceLocation Start = PeekTok.getLocation();
421 // Unary plus doesn't modify the value.
422 PP.LexNonComment(PeekTok);
423 if (EvaluateValue(Result, PeekTok, DT, ValueLive, PP)) return true;
424 Result.setBegin(Start);
425 Result.setIdentifier(nullptr);
429 SourceLocation Loc = PeekTok.getLocation();
430 PP.LexNonComment(PeekTok);
431 if (EvaluateValue(Result, PeekTok, DT, ValueLive, PP)) return true;
432 Result.setBegin(Loc);
433 Result.setIdentifier(nullptr);
435 // C99 6.5.3.3p3: The sign of the result matches the sign of the operand.
436 Result.Val = -Result.Val;
438 // -MININT is the only thing that overflows. Unsigned never overflows.
439 bool Overflow = !Result.isUnsigned() && Result.Val.isMinSignedValue();
441 // If this operator is live and overflowed, report the issue.
442 if (Overflow && ValueLive)
443 PP.Diag(Loc, diag::warn_pp_expr_overflow) << Result.getRange();
445 DT.State = DefinedTracker::Unknown;
450 SourceLocation Start = PeekTok.getLocation();
451 PP.LexNonComment(PeekTok);
452 if (EvaluateValue(Result, PeekTok, DT, ValueLive, PP)) return true;
453 Result.setBegin(Start);
454 Result.setIdentifier(nullptr);
456 // C99 6.5.3.3p4: The sign of the result matches the sign of the operand.
457 Result.Val = ~Result.Val;
458 DT.State = DefinedTracker::Unknown;
463 SourceLocation Start = PeekTok.getLocation();
464 PP.LexNonComment(PeekTok);
465 if (EvaluateValue(Result, PeekTok, DT, ValueLive, PP)) return true;
466 Result.setBegin(Start);
467 Result.Val = !Result.Val;
468 // C99 6.5.3.3p5: The sign of the result is 'int', aka it is signed.
469 Result.Val.setIsUnsigned(false);
470 Result.setIdentifier(nullptr);
472 if (DT.State == DefinedTracker::DefinedMacro)
473 DT.State = DefinedTracker::NotDefinedMacro;
474 else if (DT.State == DefinedTracker::NotDefinedMacro)
475 DT.State = DefinedTracker::DefinedMacro;
479 // FIXME: Handle #assert
483 /// getPrecedence - Return the precedence of the specified binary operator
484 /// token. This returns:
485 /// ~0 - Invalid token.
486 /// 14 -> 3 - various operators.
488 static unsigned getPrecedence(tok::TokenKind Kind) {
493 case tok::star: return 14;
495 case tok::minus: return 13;
497 case tok::greatergreater: return 12;
500 case tok::greaterequal:
501 case tok::greater: return 11;
502 case tok::exclaimequal:
503 case tok::equalequal: return 10;
504 case tok::amp: return 9;
505 case tok::caret: return 8;
506 case tok::pipe: return 7;
507 case tok::ampamp: return 6;
508 case tok::pipepipe: return 5;
509 case tok::question: return 4;
510 case tok::comma: return 3;
511 case tok::colon: return 2;
512 case tok::r_paren: return 0;// Lowest priority, end of expr.
513 case tok::eod: return 0;// Lowest priority, end of directive.
517 static void diagnoseUnexpectedOperator(Preprocessor &PP, PPValue &LHS,
519 if (Tok.is(tok::l_paren) && LHS.getIdentifier())
520 PP.Diag(LHS.getRange().getBegin(), diag::err_pp_expr_bad_token_lparen)
521 << LHS.getIdentifier();
523 PP.Diag(Tok.getLocation(), diag::err_pp_expr_bad_token_binop)
527 /// EvaluateDirectiveSubExpr - Evaluate the subexpression whose first token is
528 /// PeekTok, and whose precedence is PeekPrec. This returns the result in LHS.
530 /// If ValueLive is false, then this value is being evaluated in a context where
531 /// the result is not used. As such, avoid diagnostics that relate to
532 /// evaluation, such as division by zero warnings.
533 static bool EvaluateDirectiveSubExpr(PPValue &LHS, unsigned MinPrec,
534 Token &PeekTok, bool ValueLive,
536 unsigned PeekPrec = getPrecedence(PeekTok.getKind());
537 // If this token isn't valid, report the error.
538 if (PeekPrec == ~0U) {
539 diagnoseUnexpectedOperator(PP, LHS, PeekTok);
544 // If this token has a lower precedence than we are allowed to parse, return
545 // it so that higher levels of the recursion can parse it.
546 if (PeekPrec < MinPrec)
549 tok::TokenKind Operator = PeekTok.getKind();
551 // If this is a short-circuiting operator, see if the RHS of the operator is
552 // dead. Note that this cannot just clobber ValueLive. Consider
553 // "0 && 1 ? 4 : 1 / 0", which is parsed as "(0 && 1) ? 4 : (1 / 0)". In
554 // this example, the RHS of the && being dead does not make the rest of the
557 if (Operator == tok::ampamp && LHS.Val == 0)
558 RHSIsLive = false; // RHS of "0 && x" is dead.
559 else if (Operator == tok::pipepipe && LHS.Val != 0)
560 RHSIsLive = false; // RHS of "1 || x" is dead.
561 else if (Operator == tok::question && LHS.Val == 0)
562 RHSIsLive = false; // RHS (x) of "0 ? x : y" is dead.
564 RHSIsLive = ValueLive;
566 // Consume the operator, remembering the operator's location for reporting.
567 SourceLocation OpLoc = PeekTok.getLocation();
568 PP.LexNonComment(PeekTok);
570 PPValue RHS(LHS.getBitWidth());
571 // Parse the RHS of the operator.
573 if (EvaluateValue(RHS, PeekTok, DT, RHSIsLive, PP)) return true;
575 // Remember the precedence of this operator and get the precedence of the
576 // operator immediately to the right of the RHS.
577 unsigned ThisPrec = PeekPrec;
578 PeekPrec = getPrecedence(PeekTok.getKind());
580 // If this token isn't valid, report the error.
581 if (PeekPrec == ~0U) {
582 diagnoseUnexpectedOperator(PP, RHS, PeekTok);
586 // Decide whether to include the next binop in this subexpression. For
587 // example, when parsing x+y*z and looking at '*', we want to recursively
588 // handle y*z as a single subexpression. We do this because the precedence
589 // of * is higher than that of +. The only strange case we have to handle
590 // here is for the ?: operator, where the precedence is actually lower than
591 // the LHS of the '?'. The grammar rule is:
593 // conditional-expression ::=
594 // logical-OR-expression ? expression : conditional-expression
595 // where 'expression' is actually comma-expression.
597 if (Operator == tok::question)
598 // The RHS of "?" should be maximally consumed as an expression.
599 RHSPrec = getPrecedence(tok::comma);
600 else // All others should munch while higher precedence.
601 RHSPrec = ThisPrec+1;
603 if (PeekPrec >= RHSPrec) {
604 if (EvaluateDirectiveSubExpr(RHS, RHSPrec, PeekTok, RHSIsLive, PP))
606 PeekPrec = getPrecedence(PeekTok.getKind());
608 assert(PeekPrec <= ThisPrec && "Recursion didn't work!");
610 // Usual arithmetic conversions (C99 6.3.1.8p1): result is unsigned if
611 // either operand is unsigned.
612 llvm::APSInt Res(LHS.getBitWidth());
614 case tok::question: // No UAC for x and y in "x ? y : z".
615 case tok::lessless: // Shift amount doesn't UAC with shift value.
616 case tok::greatergreater: // Shift amount doesn't UAC with shift value.
617 case tok::comma: // Comma operands are not subject to UACs.
618 case tok::pipepipe: // Logical || does not do UACs.
619 case tok::ampamp: // Logical && does not do UACs.
622 Res.setIsUnsigned(LHS.isUnsigned()|RHS.isUnsigned());
623 // If this just promoted something from signed to unsigned, and if the
624 // value was negative, warn about it.
625 if (ValueLive && Res.isUnsigned()) {
626 if (!LHS.isUnsigned() && LHS.Val.isNegative())
627 PP.Diag(OpLoc, diag::warn_pp_convert_to_positive) << 0
628 << LHS.Val.toString(10, true) + " to " +
629 LHS.Val.toString(10, false)
630 << LHS.getRange() << RHS.getRange();
631 if (!RHS.isUnsigned() && RHS.Val.isNegative())
632 PP.Diag(OpLoc, diag::warn_pp_convert_to_positive) << 1
633 << RHS.Val.toString(10, true) + " to " +
634 RHS.Val.toString(10, false)
635 << LHS.getRange() << RHS.getRange();
637 LHS.Val.setIsUnsigned(Res.isUnsigned());
638 RHS.Val.setIsUnsigned(Res.isUnsigned());
641 bool Overflow = false;
643 default: llvm_unreachable("Unknown operator token!");
646 Res = LHS.Val % RHS.Val;
647 else if (ValueLive) {
648 PP.Diag(OpLoc, diag::err_pp_remainder_by_zero)
649 << LHS.getRange() << RHS.getRange();
655 if (LHS.Val.isSigned())
656 Res = llvm::APSInt(LHS.Val.sdiv_ov(RHS.Val, Overflow), false);
658 Res = LHS.Val / RHS.Val;
659 } else if (ValueLive) {
660 PP.Diag(OpLoc, diag::err_pp_division_by_zero)
661 << LHS.getRange() << RHS.getRange();
668 Res = llvm::APSInt(LHS.Val.smul_ov(RHS.Val, Overflow), false);
670 Res = LHS.Val * RHS.Val;
672 case tok::lessless: {
673 // Determine whether overflow is about to happen.
674 if (LHS.isUnsigned())
675 Res = LHS.Val.ushl_ov(RHS.Val, Overflow);
677 Res = llvm::APSInt(LHS.Val.sshl_ov(RHS.Val, Overflow), false);
680 case tok::greatergreater: {
681 // Determine whether overflow is about to happen.
682 unsigned ShAmt = static_cast<unsigned>(RHS.Val.getLimitedValue());
683 if (ShAmt >= LHS.getBitWidth()) {
685 ShAmt = LHS.getBitWidth()-1;
687 Res = LHS.Val >> ShAmt;
691 if (LHS.isUnsigned())
692 Res = LHS.Val + RHS.Val;
694 Res = llvm::APSInt(LHS.Val.sadd_ov(RHS.Val, Overflow), false);
697 if (LHS.isUnsigned())
698 Res = LHS.Val - RHS.Val;
700 Res = llvm::APSInt(LHS.Val.ssub_ov(RHS.Val, Overflow), false);
703 Res = LHS.Val <= RHS.Val;
704 Res.setIsUnsigned(false); // C99 6.5.8p6, result is always int (signed)
707 Res = LHS.Val < RHS.Val;
708 Res.setIsUnsigned(false); // C99 6.5.8p6, result is always int (signed)
710 case tok::greaterequal:
711 Res = LHS.Val >= RHS.Val;
712 Res.setIsUnsigned(false); // C99 6.5.8p6, result is always int (signed)
715 Res = LHS.Val > RHS.Val;
716 Res.setIsUnsigned(false); // C99 6.5.8p6, result is always int (signed)
718 case tok::exclaimequal:
719 Res = LHS.Val != RHS.Val;
720 Res.setIsUnsigned(false); // C99 6.5.9p3, result is always int (signed)
722 case tok::equalequal:
723 Res = LHS.Val == RHS.Val;
724 Res.setIsUnsigned(false); // C99 6.5.9p3, result is always int (signed)
727 Res = LHS.Val & RHS.Val;
730 Res = LHS.Val ^ RHS.Val;
733 Res = LHS.Val | RHS.Val;
736 Res = (LHS.Val != 0 && RHS.Val != 0);
737 Res.setIsUnsigned(false); // C99 6.5.13p3, result is always int (signed)
740 Res = (LHS.Val != 0 || RHS.Val != 0);
741 Res.setIsUnsigned(false); // C99 6.5.14p3, result is always int (signed)
744 // Comma is invalid in pp expressions in c89/c++ mode, but is valid in C99
745 // if not being evaluated.
746 if (!PP.getLangOpts().C99 || ValueLive)
747 PP.Diag(OpLoc, diag::ext_pp_comma_expr)
748 << LHS.getRange() << RHS.getRange();
749 Res = RHS.Val; // LHS = LHS,RHS -> RHS.
751 case tok::question: {
752 // Parse the : part of the expression.
753 if (PeekTok.isNot(tok::colon)) {
754 PP.Diag(PeekTok.getLocation(), diag::err_expected)
755 << tok::colon << LHS.getRange() << RHS.getRange();
756 PP.Diag(OpLoc, diag::note_matching) << tok::question;
760 PP.LexNonComment(PeekTok);
762 // Evaluate the value after the :.
763 bool AfterColonLive = ValueLive && LHS.Val == 0;
764 PPValue AfterColonVal(LHS.getBitWidth());
766 if (EvaluateValue(AfterColonVal, PeekTok, DT, AfterColonLive, PP))
769 // Parse anything after the : with the same precedence as ?. We allow
770 // things of equal precedence because ?: is right associative.
771 if (EvaluateDirectiveSubExpr(AfterColonVal, ThisPrec,
772 PeekTok, AfterColonLive, PP))
775 // Now that we have the condition, the LHS and the RHS of the :, evaluate.
776 Res = LHS.Val != 0 ? RHS.Val : AfterColonVal.Val;
777 RHS.setEnd(AfterColonVal.getRange().getEnd());
779 // Usual arithmetic conversions (C99 6.3.1.8p1): result is unsigned if
780 // either operand is unsigned.
781 Res.setIsUnsigned(RHS.isUnsigned() | AfterColonVal.isUnsigned());
783 // Figure out the precedence of the token after the : part.
784 PeekPrec = getPrecedence(PeekTok.getKind());
788 // Don't allow :'s to float around without being part of ?: exprs.
789 PP.Diag(OpLoc, diag::err_pp_colon_without_question)
790 << LHS.getRange() << RHS.getRange();
794 // If this operator is live and overflowed, report the issue.
795 if (Overflow && ValueLive)
796 PP.Diag(OpLoc, diag::warn_pp_expr_overflow)
797 << LHS.getRange() << RHS.getRange();
799 // Put the result back into 'LHS' for our next iteration.
801 LHS.setEnd(RHS.getRange().getEnd());
802 RHS.setIdentifier(nullptr);
806 /// EvaluateDirectiveExpression - Evaluate an integer constant expression that
807 /// may occur after a #if or #elif directive. If the expression is equivalent
808 /// to "!defined(X)" return X in IfNDefMacro.
809 bool Preprocessor::EvaluateDirectiveExpression(IdentifierInfo *&IfNDefMacro) {
810 SaveAndRestore<bool> PPDir(ParsingIfOrElifDirective, true);
811 // Save the current state of 'DisableMacroExpansion' and reset it to false. If
812 // 'DisableMacroExpansion' is true, then we must be in a macro argument list
813 // in which case a directive is undefined behavior. We want macros to be able
814 // to recursively expand in order to get more gcc-list behavior, so we force
815 // DisableMacroExpansion to false and restore it when we're done parsing the
817 bool DisableMacroExpansionAtStartOfDirective = DisableMacroExpansion;
818 DisableMacroExpansion = false;
820 // Peek ahead one token.
824 // C99 6.10.1p3 - All expressions are evaluated as intmax_t or uintmax_t.
825 unsigned BitWidth = getTargetInfo().getIntMaxTWidth();
827 PPValue ResVal(BitWidth);
829 if (EvaluateValue(ResVal, Tok, DT, true, *this)) {
830 // Parse error, skip the rest of the macro line.
831 if (Tok.isNot(tok::eod))
832 DiscardUntilEndOfDirective();
834 // Restore 'DisableMacroExpansion'.
835 DisableMacroExpansion = DisableMacroExpansionAtStartOfDirective;
839 // If we are at the end of the expression after just parsing a value, there
840 // must be no (unparenthesized) binary operators involved, so we can exit
842 if (Tok.is(tok::eod)) {
843 // If the expression we parsed was of the form !defined(macro), return the
844 // macro in IfNDefMacro.
845 if (DT.State == DefinedTracker::NotDefinedMacro)
846 IfNDefMacro = DT.TheMacro;
848 // Restore 'DisableMacroExpansion'.
849 DisableMacroExpansion = DisableMacroExpansionAtStartOfDirective;
850 return ResVal.Val != 0;
853 // Otherwise, we must have a binary operator (e.g. "#if 1 < 2"), so parse the
854 // operator and the stuff after it.
855 if (EvaluateDirectiveSubExpr(ResVal, getPrecedence(tok::question),
857 // Parse error, skip the rest of the macro line.
858 if (Tok.isNot(tok::eod))
859 DiscardUntilEndOfDirective();
861 // Restore 'DisableMacroExpansion'.
862 DisableMacroExpansion = DisableMacroExpansionAtStartOfDirective;
866 // If we aren't at the tok::eod token, something bad happened, like an extra
868 if (Tok.isNot(tok::eod)) {
869 Diag(Tok, diag::err_pp_expected_eol);
870 DiscardUntilEndOfDirective();
873 // Restore 'DisableMacroExpansion'.
874 DisableMacroExpansion = DisableMacroExpansionAtStartOfDirective;
875 return ResVal.Val != 0;