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(), PP); 299 if (Literal.hadError) 300 return true; // a diagnostic was already reported. 301 302 if (Literal.isFloatingLiteral() || Literal.isImaginary) { 303 PP.Diag(PeekTok, diag::err_pp_illegal_floating_literal); 304 return true; 305 } 306 assert(Literal.isIntegerLiteral() && "Unknown ppnumber"); 307 308 // Complain about, and drop, any ud-suffix. 309 if (Literal.hasUDSuffix()) 310 PP.Diag(PeekTok, diag::err_pp_invalid_udl) << /*integer*/1; 311 312 // 'long long' is a C99 or C++11 feature. 313 if (!PP.getLangOpts().C99 && Literal.isLongLong) { 314 if (PP.getLangOpts().CPlusPlus) 315 PP.Diag(PeekTok, 316 PP.getLangOpts().CPlusPlus11 ? 317 diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong); 318 else 319 PP.Diag(PeekTok, diag::ext_c99_longlong); 320 } 321 322 // Parse the integer literal into Result. 323 if (Literal.GetIntegerValue(Result.Val)) { 324 // Overflow parsing integer literal. 325 if (ValueLive) 326 PP.Diag(PeekTok, diag::err_integer_literal_too_large) 327 << /* Unsigned */ 1; 328 Result.Val.setIsUnsigned(true); 329 } else { 330 // Set the signedness of the result to match whether there was a U suffix 331 // or not. 332 Result.Val.setIsUnsigned(Literal.isUnsigned); 333 334 // Detect overflow based on whether the value is signed. If signed 335 // and if the value is too large, emit a warning "integer constant is so 336 // large that it is unsigned" e.g. on 12345678901234567890 where intmax_t 337 // is 64-bits. 338 if (!Literal.isUnsigned && Result.Val.isNegative()) { 339 // Octal, hexadecimal, and binary literals are implicitly unsigned if 340 // the value does not fit into a signed integer type. 341 if (ValueLive && Literal.getRadix() == 10) 342 PP.Diag(PeekTok, diag::ext_integer_literal_too_large_for_signed); 343 Result.Val.setIsUnsigned(true); 344 } 345 } 346 347 // Consume the token. 348 Result.setRange(PeekTok.getLocation()); 349 PP.LexNonComment(PeekTok); 350 return false; 351 } 352 case tok::char_constant: // 'x' 353 case tok::wide_char_constant: // L'x' 354 case tok::utf8_char_constant: // u8'x' 355 case tok::utf16_char_constant: // u'x' 356 case tok::utf32_char_constant: { // U'x' 357 // Complain about, and drop, any ud-suffix. 358 if (PeekTok.hasUDSuffix()) 359 PP.Diag(PeekTok, diag::err_pp_invalid_udl) << /*character*/0; 360 361 SmallString<32> CharBuffer; 362 bool CharInvalid = false; 363 StringRef ThisTok = PP.getSpelling(PeekTok, CharBuffer, &CharInvalid); 364 if (CharInvalid) 365 return true; 366 367 CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), 368 PeekTok.getLocation(), PP, PeekTok.getKind()); 369 if (Literal.hadError()) 370 return true; // A diagnostic was already emitted. 371 372 // Character literals are always int or wchar_t, expand to intmax_t. 373 const TargetInfo &TI = PP.getTargetInfo(); 374 unsigned NumBits; 375 if (Literal.isMultiChar()) 376 NumBits = TI.getIntWidth(); 377 else if (Literal.isWide()) 378 NumBits = TI.getWCharWidth(); 379 else if (Literal.isUTF16()) 380 NumBits = TI.getChar16Width(); 381 else if (Literal.isUTF32()) 382 NumBits = TI.getChar32Width(); 383 else // char or char8_t 384 NumBits = TI.getCharWidth(); 385 386 // Set the width. 387 llvm::APSInt Val(NumBits); 388 // Set the value. 389 Val = Literal.getValue(); 390 // Set the signedness. UTF-16 and UTF-32 are always unsigned 391 if (Literal.isWide()) 392 Val.setIsUnsigned(!TargetInfo::isTypeSigned(TI.getWCharType())); 393 else if (!Literal.isUTF16() && !Literal.isUTF32()) 394 Val.setIsUnsigned(!PP.getLangOpts().CharIsSigned); 395 396 if (Result.Val.getBitWidth() > Val.getBitWidth()) { 397 Result.Val = Val.extend(Result.Val.getBitWidth()); 398 } else { 399 assert(Result.Val.getBitWidth() == Val.getBitWidth() && 400 "intmax_t smaller than char/wchar_t?"); 401 Result.Val = Val; 402 } 403 404 // Consume the token. 405 Result.setRange(PeekTok.getLocation()); 406 PP.LexNonComment(PeekTok); 407 return false; 408 } 409 case tok::l_paren: { 410 SourceLocation Start = PeekTok.getLocation(); 411 PP.LexNonComment(PeekTok); // Eat the (. 412 // Parse the value and if there are any binary operators involved, parse 413 // them. 414 if (EvaluateValue(Result, PeekTok, DT, ValueLive, PP)) return true; 415 416 // If this is a silly value like (X), which doesn't need parens, check for 417 // !(defined X). 418 if (PeekTok.is(tok::r_paren)) { 419 // Just use DT unmodified as our result. 420 } else { 421 // Otherwise, we have something like (x+y), and we consumed '(x'. 422 if (EvaluateDirectiveSubExpr(Result, 1, PeekTok, ValueLive, 423 DT.IncludedUndefinedIds, PP)) 424 return true; 425 426 if (PeekTok.isNot(tok::r_paren)) { 427 PP.Diag(PeekTok.getLocation(), diag::err_pp_expected_rparen) 428 << Result.getRange(); 429 PP.Diag(Start, diag::note_matching) << tok::l_paren; 430 return true; 431 } 432 DT.State = DefinedTracker::Unknown; 433 } 434 Result.setRange(Start, PeekTok.getLocation()); 435 Result.setIdentifier(nullptr); 436 PP.LexNonComment(PeekTok); // Eat the ). 437 return false; 438 } 439 case tok::plus: { 440 SourceLocation Start = PeekTok.getLocation(); 441 // Unary plus doesn't modify the value. 442 PP.LexNonComment(PeekTok); 443 if (EvaluateValue(Result, PeekTok, DT, ValueLive, PP)) return true; 444 Result.setBegin(Start); 445 Result.setIdentifier(nullptr); 446 return false; 447 } 448 case tok::minus: { 449 SourceLocation Loc = PeekTok.getLocation(); 450 PP.LexNonComment(PeekTok); 451 if (EvaluateValue(Result, PeekTok, DT, ValueLive, PP)) return true; 452 Result.setBegin(Loc); 453 Result.setIdentifier(nullptr); 454 455 // C99 6.5.3.3p3: The sign of the result matches the sign of the operand. 456 Result.Val = -Result.Val; 457 458 // -MININT is the only thing that overflows. Unsigned never overflows. 459 bool Overflow = !Result.isUnsigned() && Result.Val.isMinSignedValue(); 460 461 // If this operator is live and overflowed, report the issue. 462 if (Overflow && ValueLive) 463 PP.Diag(Loc, diag::warn_pp_expr_overflow) << Result.getRange(); 464 465 DT.State = DefinedTracker::Unknown; 466 return false; 467 } 468 469 case tok::tilde: { 470 SourceLocation Start = PeekTok.getLocation(); 471 PP.LexNonComment(PeekTok); 472 if (EvaluateValue(Result, PeekTok, DT, ValueLive, PP)) return true; 473 Result.setBegin(Start); 474 Result.setIdentifier(nullptr); 475 476 // C99 6.5.3.3p4: The sign of the result matches the sign of the operand. 477 Result.Val = ~Result.Val; 478 DT.State = DefinedTracker::Unknown; 479 return false; 480 } 481 482 case tok::exclaim: { 483 SourceLocation Start = PeekTok.getLocation(); 484 PP.LexNonComment(PeekTok); 485 if (EvaluateValue(Result, PeekTok, DT, ValueLive, PP)) return true; 486 Result.setBegin(Start); 487 Result.Val = !Result.Val; 488 // C99 6.5.3.3p5: The sign of the result is 'int', aka it is signed. 489 Result.Val.setIsUnsigned(false); 490 Result.setIdentifier(nullptr); 491 492 if (DT.State == DefinedTracker::DefinedMacro) 493 DT.State = DefinedTracker::NotDefinedMacro; 494 else if (DT.State == DefinedTracker::NotDefinedMacro) 495 DT.State = DefinedTracker::DefinedMacro; 496 return false; 497 } 498 case tok::kw_true: 499 case tok::kw_false: 500 Result.Val = PeekTok.getKind() == tok::kw_true; 501 Result.Val.setIsUnsigned(false); // "0" is signed intmax_t 0. 502 Result.setIdentifier(PeekTok.getIdentifierInfo()); 503 Result.setRange(PeekTok.getLocation()); 504 PP.LexNonComment(PeekTok); 505 return false; 506 507 // FIXME: Handle #assert 508 } 509 } 510 511 /// getPrecedence - Return the precedence of the specified binary operator 512 /// token. This returns: 513 /// ~0 - Invalid token. 514 /// 14 -> 3 - various operators. 515 /// 0 - 'eod' or ')' 516 static unsigned getPrecedence(tok::TokenKind Kind) { 517 switch (Kind) { 518 default: return ~0U; 519 case tok::percent: 520 case tok::slash: 521 case tok::star: return 14; 522 case tok::plus: 523 case tok::minus: return 13; 524 case tok::lessless: 525 case tok::greatergreater: return 12; 526 case tok::lessequal: 527 case tok::less: 528 case tok::greaterequal: 529 case tok::greater: return 11; 530 case tok::exclaimequal: 531 case tok::equalequal: return 10; 532 case tok::amp: return 9; 533 case tok::caret: return 8; 534 case tok::pipe: return 7; 535 case tok::ampamp: return 6; 536 case tok::pipepipe: return 5; 537 case tok::question: return 4; 538 case tok::comma: return 3; 539 case tok::colon: return 2; 540 case tok::r_paren: return 0;// Lowest priority, end of expr. 541 case tok::eod: return 0;// Lowest priority, end of directive. 542 } 543 } 544 545 static void diagnoseUnexpectedOperator(Preprocessor &PP, PPValue &LHS, 546 Token &Tok) { 547 if (Tok.is(tok::l_paren) && LHS.getIdentifier()) 548 PP.Diag(LHS.getRange().getBegin(), diag::err_pp_expr_bad_token_lparen) 549 << LHS.getIdentifier(); 550 else 551 PP.Diag(Tok.getLocation(), diag::err_pp_expr_bad_token_binop) 552 << LHS.getRange(); 553 } 554 555 /// EvaluateDirectiveSubExpr - Evaluate the subexpression whose first token is 556 /// PeekTok, and whose precedence is PeekPrec. This returns the result in LHS. 557 /// 558 /// If ValueLive is false, then this value is being evaluated in a context where 559 /// the result is not used. As such, avoid diagnostics that relate to 560 /// evaluation, such as division by zero warnings. 561 static bool EvaluateDirectiveSubExpr(PPValue &LHS, unsigned MinPrec, 562 Token &PeekTok, bool ValueLive, 563 bool &IncludedUndefinedIds, 564 Preprocessor &PP) { 565 unsigned PeekPrec = getPrecedence(PeekTok.getKind()); 566 // If this token isn't valid, report the error. 567 if (PeekPrec == ~0U) { 568 diagnoseUnexpectedOperator(PP, LHS, PeekTok); 569 return true; 570 } 571 572 while (true) { 573 // If this token has a lower precedence than we are allowed to parse, return 574 // it so that higher levels of the recursion can parse it. 575 if (PeekPrec < MinPrec) 576 return false; 577 578 tok::TokenKind Operator = PeekTok.getKind(); 579 580 // If this is a short-circuiting operator, see if the RHS of the operator is 581 // dead. Note that this cannot just clobber ValueLive. Consider 582 // "0 && 1 ? 4 : 1 / 0", which is parsed as "(0 && 1) ? 4 : (1 / 0)". In 583 // this example, the RHS of the && being dead does not make the rest of the 584 // expr dead. 585 bool RHSIsLive; 586 if (Operator == tok::ampamp && LHS.Val == 0) 587 RHSIsLive = false; // RHS of "0 && x" is dead. 588 else if (Operator == tok::pipepipe && LHS.Val != 0) 589 RHSIsLive = false; // RHS of "1 || x" is dead. 590 else if (Operator == tok::question && LHS.Val == 0) 591 RHSIsLive = false; // RHS (x) of "0 ? x : y" is dead. 592 else 593 RHSIsLive = ValueLive; 594 595 // Consume the operator, remembering the operator's location for reporting. 596 SourceLocation OpLoc = PeekTok.getLocation(); 597 PP.LexNonComment(PeekTok); 598 599 PPValue RHS(LHS.getBitWidth()); 600 // Parse the RHS of the operator. 601 DefinedTracker DT; 602 if (EvaluateValue(RHS, PeekTok, DT, RHSIsLive, PP)) return true; 603 IncludedUndefinedIds = DT.IncludedUndefinedIds; 604 605 // Remember the precedence of this operator and get the precedence of the 606 // operator immediately to the right of the RHS. 607 unsigned ThisPrec = PeekPrec; 608 PeekPrec = getPrecedence(PeekTok.getKind()); 609 610 // If this token isn't valid, report the error. 611 if (PeekPrec == ~0U) { 612 diagnoseUnexpectedOperator(PP, RHS, PeekTok); 613 return true; 614 } 615 616 // Decide whether to include the next binop in this subexpression. For 617 // example, when parsing x+y*z and looking at '*', we want to recursively 618 // handle y*z as a single subexpression. We do this because the precedence 619 // of * is higher than that of +. The only strange case we have to handle 620 // here is for the ?: operator, where the precedence is actually lower than 621 // the LHS of the '?'. The grammar rule is: 622 // 623 // conditional-expression ::= 624 // logical-OR-expression ? expression : conditional-expression 625 // where 'expression' is actually comma-expression. 626 unsigned RHSPrec; 627 if (Operator == tok::question) 628 // The RHS of "?" should be maximally consumed as an expression. 629 RHSPrec = getPrecedence(tok::comma); 630 else // All others should munch while higher precedence. 631 RHSPrec = ThisPrec+1; 632 633 if (PeekPrec >= RHSPrec) { 634 if (EvaluateDirectiveSubExpr(RHS, RHSPrec, PeekTok, RHSIsLive, 635 IncludedUndefinedIds, PP)) 636 return true; 637 PeekPrec = getPrecedence(PeekTok.getKind()); 638 } 639 assert(PeekPrec <= ThisPrec && "Recursion didn't work!"); 640 641 // Usual arithmetic conversions (C99 6.3.1.8p1): result is unsigned if 642 // either operand is unsigned. 643 llvm::APSInt Res(LHS.getBitWidth()); 644 switch (Operator) { 645 case tok::question: // No UAC for x and y in "x ? y : z". 646 case tok::lessless: // Shift amount doesn't UAC with shift value. 647 case tok::greatergreater: // Shift amount doesn't UAC with shift value. 648 case tok::comma: // Comma operands are not subject to UACs. 649 case tok::pipepipe: // Logical || does not do UACs. 650 case tok::ampamp: // Logical && does not do UACs. 651 break; // No UAC 652 default: 653 Res.setIsUnsigned(LHS.isUnsigned()|RHS.isUnsigned()); 654 // If this just promoted something from signed to unsigned, and if the 655 // value was negative, warn about it. 656 if (ValueLive && Res.isUnsigned()) { 657 if (!LHS.isUnsigned() && LHS.Val.isNegative()) 658 PP.Diag(OpLoc, diag::warn_pp_convert_to_positive) << 0 659 << LHS.Val.toString(10, true) + " to " + 660 LHS.Val.toString(10, false) 661 << LHS.getRange() << RHS.getRange(); 662 if (!RHS.isUnsigned() && RHS.Val.isNegative()) 663 PP.Diag(OpLoc, diag::warn_pp_convert_to_positive) << 1 664 << RHS.Val.toString(10, true) + " to " + 665 RHS.Val.toString(10, false) 666 << LHS.getRange() << RHS.getRange(); 667 } 668 LHS.Val.setIsUnsigned(Res.isUnsigned()); 669 RHS.Val.setIsUnsigned(Res.isUnsigned()); 670 } 671 672 bool Overflow = false; 673 switch (Operator) { 674 default: llvm_unreachable("Unknown operator token!"); 675 case tok::percent: 676 if (RHS.Val != 0) 677 Res = LHS.Val % RHS.Val; 678 else if (ValueLive) { 679 PP.Diag(OpLoc, diag::err_pp_remainder_by_zero) 680 << LHS.getRange() << RHS.getRange(); 681 return true; 682 } 683 break; 684 case tok::slash: 685 if (RHS.Val != 0) { 686 if (LHS.Val.isSigned()) 687 Res = llvm::APSInt(LHS.Val.sdiv_ov(RHS.Val, Overflow), false); 688 else 689 Res = LHS.Val / RHS.Val; 690 } else if (ValueLive) { 691 PP.Diag(OpLoc, diag::err_pp_division_by_zero) 692 << LHS.getRange() << RHS.getRange(); 693 return true; 694 } 695 break; 696 697 case tok::star: 698 if (Res.isSigned()) 699 Res = llvm::APSInt(LHS.Val.smul_ov(RHS.Val, Overflow), false); 700 else 701 Res = LHS.Val * RHS.Val; 702 break; 703 case tok::lessless: { 704 // Determine whether overflow is about to happen. 705 if (LHS.isUnsigned()) 706 Res = LHS.Val.ushl_ov(RHS.Val, Overflow); 707 else 708 Res = llvm::APSInt(LHS.Val.sshl_ov(RHS.Val, Overflow), false); 709 break; 710 } 711 case tok::greatergreater: { 712 // Determine whether overflow is about to happen. 713 unsigned ShAmt = static_cast<unsigned>(RHS.Val.getLimitedValue()); 714 if (ShAmt >= LHS.getBitWidth()) { 715 Overflow = true; 716 ShAmt = LHS.getBitWidth()-1; 717 } 718 Res = LHS.Val >> ShAmt; 719 break; 720 } 721 case tok::plus: 722 if (LHS.isUnsigned()) 723 Res = LHS.Val + RHS.Val; 724 else 725 Res = llvm::APSInt(LHS.Val.sadd_ov(RHS.Val, Overflow), false); 726 break; 727 case tok::minus: 728 if (LHS.isUnsigned()) 729 Res = LHS.Val - RHS.Val; 730 else 731 Res = llvm::APSInt(LHS.Val.ssub_ov(RHS.Val, Overflow), false); 732 break; 733 case tok::lessequal: 734 Res = LHS.Val <= RHS.Val; 735 Res.setIsUnsigned(false); // C99 6.5.8p6, result is always int (signed) 736 break; 737 case tok::less: 738 Res = LHS.Val < RHS.Val; 739 Res.setIsUnsigned(false); // C99 6.5.8p6, result is always int (signed) 740 break; 741 case tok::greaterequal: 742 Res = LHS.Val >= RHS.Val; 743 Res.setIsUnsigned(false); // C99 6.5.8p6, result is always int (signed) 744 break; 745 case tok::greater: 746 Res = LHS.Val > RHS.Val; 747 Res.setIsUnsigned(false); // C99 6.5.8p6, result is always int (signed) 748 break; 749 case tok::exclaimequal: 750 Res = LHS.Val != RHS.Val; 751 Res.setIsUnsigned(false); // C99 6.5.9p3, result is always int (signed) 752 break; 753 case tok::equalequal: 754 Res = LHS.Val == RHS.Val; 755 Res.setIsUnsigned(false); // C99 6.5.9p3, result is always int (signed) 756 break; 757 case tok::amp: 758 Res = LHS.Val & RHS.Val; 759 break; 760 case tok::caret: 761 Res = LHS.Val ^ RHS.Val; 762 break; 763 case tok::pipe: 764 Res = LHS.Val | RHS.Val; 765 break; 766 case tok::ampamp: 767 Res = (LHS.Val != 0 && RHS.Val != 0); 768 Res.setIsUnsigned(false); // C99 6.5.13p3, result is always int (signed) 769 break; 770 case tok::pipepipe: 771 Res = (LHS.Val != 0 || RHS.Val != 0); 772 Res.setIsUnsigned(false); // C99 6.5.14p3, result is always int (signed) 773 break; 774 case tok::comma: 775 // Comma is invalid in pp expressions in c89/c++ mode, but is valid in C99 776 // if not being evaluated. 777 if (!PP.getLangOpts().C99 || ValueLive) 778 PP.Diag(OpLoc, diag::ext_pp_comma_expr) 779 << LHS.getRange() << RHS.getRange(); 780 Res = RHS.Val; // LHS = LHS,RHS -> RHS. 781 break; 782 case tok::question: { 783 // Parse the : part of the expression. 784 if (PeekTok.isNot(tok::colon)) { 785 PP.Diag(PeekTok.getLocation(), diag::err_expected) 786 << tok::colon << LHS.getRange() << RHS.getRange(); 787 PP.Diag(OpLoc, diag::note_matching) << tok::question; 788 return true; 789 } 790 // Consume the :. 791 PP.LexNonComment(PeekTok); 792 793 // Evaluate the value after the :. 794 bool AfterColonLive = ValueLive && LHS.Val == 0; 795 PPValue AfterColonVal(LHS.getBitWidth()); 796 DefinedTracker DT; 797 if (EvaluateValue(AfterColonVal, PeekTok, DT, AfterColonLive, PP)) 798 return true; 799 800 // Parse anything after the : with the same precedence as ?. We allow 801 // things of equal precedence because ?: is right associative. 802 if (EvaluateDirectiveSubExpr(AfterColonVal, ThisPrec, 803 PeekTok, AfterColonLive, 804 IncludedUndefinedIds, PP)) 805 return true; 806 807 // Now that we have the condition, the LHS and the RHS of the :, evaluate. 808 Res = LHS.Val != 0 ? RHS.Val : AfterColonVal.Val; 809 RHS.setEnd(AfterColonVal.getRange().getEnd()); 810 811 // Usual arithmetic conversions (C99 6.3.1.8p1): result is unsigned if 812 // either operand is unsigned. 813 Res.setIsUnsigned(RHS.isUnsigned() | AfterColonVal.isUnsigned()); 814 815 // Figure out the precedence of the token after the : part. 816 PeekPrec = getPrecedence(PeekTok.getKind()); 817 break; 818 } 819 case tok::colon: 820 // Don't allow :'s to float around without being part of ?: exprs. 821 PP.Diag(OpLoc, diag::err_pp_colon_without_question) 822 << LHS.getRange() << RHS.getRange(); 823 return true; 824 } 825 826 // If this operator is live and overflowed, report the issue. 827 if (Overflow && ValueLive) 828 PP.Diag(OpLoc, diag::warn_pp_expr_overflow) 829 << LHS.getRange() << RHS.getRange(); 830 831 // Put the result back into 'LHS' for our next iteration. 832 LHS.Val = Res; 833 LHS.setEnd(RHS.getRange().getEnd()); 834 RHS.setIdentifier(nullptr); 835 } 836 } 837 838 /// EvaluateDirectiveExpression - Evaluate an integer constant expression that 839 /// may occur after a #if or #elif directive. If the expression is equivalent 840 /// to "!defined(X)" return X in IfNDefMacro. 841 Preprocessor::DirectiveEvalResult 842 Preprocessor::EvaluateDirectiveExpression(IdentifierInfo *&IfNDefMacro) { 843 SaveAndRestore<bool> PPDir(ParsingIfOrElifDirective, true); 844 // Save the current state of 'DisableMacroExpansion' and reset it to false. If 845 // 'DisableMacroExpansion' is true, then we must be in a macro argument list 846 // in which case a directive is undefined behavior. We want macros to be able 847 // to recursively expand in order to get more gcc-list behavior, so we force 848 // DisableMacroExpansion to false and restore it when we're done parsing the 849 // expression. 850 bool DisableMacroExpansionAtStartOfDirective = DisableMacroExpansion; 851 DisableMacroExpansion = false; 852 853 // Peek ahead one token. 854 Token Tok; 855 LexNonComment(Tok); 856 857 // C99 6.10.1p3 - All expressions are evaluated as intmax_t or uintmax_t. 858 unsigned BitWidth = getTargetInfo().getIntMaxTWidth(); 859 860 PPValue ResVal(BitWidth); 861 DefinedTracker DT; 862 SourceLocation ExprStartLoc = SourceMgr.getExpansionLoc(Tok.getLocation()); 863 if (EvaluateValue(ResVal, Tok, DT, true, *this)) { 864 // Parse error, skip the rest of the macro line. 865 SourceRange ConditionRange = ExprStartLoc; 866 if (Tok.isNot(tok::eod)) 867 ConditionRange = DiscardUntilEndOfDirective(); 868 869 // Restore 'DisableMacroExpansion'. 870 DisableMacroExpansion = DisableMacroExpansionAtStartOfDirective; 871 872 // We cannot trust the source range from the value because there was a 873 // parse error. Track the range manually -- the end of the directive is the 874 // end of the condition range. 875 return {false, 876 DT.IncludedUndefinedIds, 877 {ExprStartLoc, ConditionRange.getEnd()}}; 878 } 879 880 // If we are at the end of the expression after just parsing a value, there 881 // must be no (unparenthesized) binary operators involved, so we can exit 882 // directly. 883 if (Tok.is(tok::eod)) { 884 // If the expression we parsed was of the form !defined(macro), return the 885 // macro in IfNDefMacro. 886 if (DT.State == DefinedTracker::NotDefinedMacro) 887 IfNDefMacro = DT.TheMacro; 888 889 // Restore 'DisableMacroExpansion'. 890 DisableMacroExpansion = DisableMacroExpansionAtStartOfDirective; 891 return {ResVal.Val != 0, DT.IncludedUndefinedIds, ResVal.getRange()}; 892 } 893 894 // Otherwise, we must have a binary operator (e.g. "#if 1 < 2"), so parse the 895 // operator and the stuff after it. 896 if (EvaluateDirectiveSubExpr(ResVal, getPrecedence(tok::question), 897 Tok, true, DT.IncludedUndefinedIds, *this)) { 898 // Parse error, skip the rest of the macro line. 899 if (Tok.isNot(tok::eod)) 900 DiscardUntilEndOfDirective(); 901 902 // Restore 'DisableMacroExpansion'. 903 DisableMacroExpansion = DisableMacroExpansionAtStartOfDirective; 904 return {false, DT.IncludedUndefinedIds, ResVal.getRange()}; 905 } 906 907 // If we aren't at the tok::eod token, something bad happened, like an extra 908 // ')' token. 909 if (Tok.isNot(tok::eod)) { 910 Diag(Tok, diag::err_pp_expected_eol); 911 DiscardUntilEndOfDirective(); 912 } 913 914 // Restore 'DisableMacroExpansion'. 915 DisableMacroExpansion = DisableMacroExpansionAtStartOfDirective; 916 return {ResVal.Val != 0, DT.IncludedUndefinedIds, ResVal.getRange()}; 917 } 918