1 //===--- PPExpressions.cpp - Preprocessor Expression Evaluation -----------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // This file implements the Preprocessor::EvaluateDirectiveExpression method, 11 // which parses and evaluates integer constant expressions for #if directives. 12 // 13 //===----------------------------------------------------------------------===// 14 // 15 // FIXME: implement testing for #assert's. 16 // 17 //===----------------------------------------------------------------------===// 18 19 #include "clang/Lex/Preprocessor.h" 20 #include "clang/Basic/IdentifierTable.h" 21 #include "clang/Basic/SourceLocation.h" 22 #include "clang/Basic/SourceManager.h" 23 #include "clang/Basic/TargetInfo.h" 24 #include "clang/Basic/TokenKinds.h" 25 #include "clang/Lex/CodeCompletionHandler.h" 26 #include "clang/Lex/LexDiagnostic.h" 27 #include "clang/Lex/LiteralSupport.h" 28 #include "clang/Lex/MacroInfo.h" 29 #include "clang/Lex/PPCallbacks.h" 30 #include "clang/Lex/Token.h" 31 #include "llvm/ADT/APSInt.h" 32 #include "llvm/ADT/SmallString.h" 33 #include "llvm/ADT/StringRef.h" 34 #include "llvm/Support/ErrorHandling.h" 35 #include "llvm/Support/SaveAndRestore.h" 36 #include <cassert> 37 38 using namespace clang; 39 40 namespace { 41 42 /// PPValue - Represents the value of a subexpression of a preprocessor 43 /// conditional and the source range covered by it. 44 class PPValue { 45 SourceRange Range; 46 IdentifierInfo *II; 47 48 public: 49 llvm::APSInt Val; 50 51 // Default ctor - Construct an 'invalid' PPValue. 52 PPValue(unsigned BitWidth) : Val(BitWidth) {} 53 54 // If this value was produced by directly evaluating an identifier, produce 55 // that identifier. 56 IdentifierInfo *getIdentifier() const { return II; } 57 void setIdentifier(IdentifierInfo *II) { this->II = II; } 58 59 unsigned getBitWidth() const { return Val.getBitWidth(); } 60 bool isUnsigned() const { return Val.isUnsigned(); } 61 62 SourceRange getRange() const { return Range; } 63 64 void setRange(SourceLocation L) { Range.setBegin(L); Range.setEnd(L); } 65 void setRange(SourceLocation B, SourceLocation E) { 66 Range.setBegin(B); Range.setEnd(E); 67 } 68 void setBegin(SourceLocation L) { Range.setBegin(L); } 69 void setEnd(SourceLocation L) { Range.setEnd(L); } 70 }; 71 72 } // end anonymous namespace 73 74 static bool EvaluateDirectiveSubExpr(PPValue &LHS, unsigned MinPrec, 75 Token &PeekTok, bool ValueLive, 76 Preprocessor &PP); 77 78 /// DefinedTracker - This struct is used while parsing expressions to keep track 79 /// of whether !defined(X) has been seen. 80 /// 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. 88 enum TrackerState { 89 DefinedMacro, // defined(X) 90 NotDefinedMacro, // !defined(X) 91 Unknown // Something else. 92 } State; 93 /// TheMacro - When the state is DefinedMacro or NotDefinedMacro, this 94 /// indicates the macro that was checked. 95 IdentifierInfo *TheMacro; 96 }; 97 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); 103 104 // Get the next token, don't expand it. 105 PP.LexUnexpandedNonComment(PeekTok); 106 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); 113 } 114 115 if (PeekTok.is(tok::code_completion)) { 116 if (PP.getCodeCompletionHandler()) 117 PP.getCodeCompletionHandler()->CodeCompleteMacroName(false); 118 PP.setCodeCompletionReached(); 119 PP.LexUnexpandedNonComment(PeekTok); 120 } 121 122 // If we don't have a pp-identifier now, this is an error. 123 if (PP.CheckMacroName(PeekTok, MU_Other)) 124 return true; 125 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. 131 132 // If there is a macro, mark it used. 133 if (Result.Val != 0 && ValueLive) 134 PP.markMacroAsUsed(Macro.getMacroInfo()); 135 136 // Save macro token for callback. 137 Token macroToken(PeekTok); 138 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); 144 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; 149 return true; 150 } 151 // Consume the ). 152 Result.setEnd(PeekTok.getLocation()); 153 PP.LexNonComment(PeekTok); 154 } else { 155 // Consume identifier. 156 Result.setEnd(PeekTok.getLocation()); 157 PP.LexNonComment(PeekTok); 158 } 159 160 // [cpp.cond]p4: 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: 169 // #define FOO 170 // #define BAR defined(FOO) 171 // #if BAR 172 // ... 173 // #else 174 // ... 175 // #endif 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)) 182 .getExpansion() 183 .isFunctionMacroExpansion(); 184 // For object-type macros, it's easy to replace 185 // #define FOO defined(BAR) 186 // with 187 // #if defined(BAR) 188 // #define FOO 1 189 // #else 190 // #define FOO 0 191 // #endif 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); 201 else 202 PP.Diag(beginLoc, diag::warn_defined_in_object_type_macro); 203 } 204 205 // Invoke the 'defined' callback. 206 if (PPCallbacks *Callbacks = PP.getPPCallbacks()) { 207 Callbacks->Defined(macroToken, Macro, 208 SourceRange(beginLoc, PeekTok.getLocation())); 209 } 210 211 // Success, remember that we saw defined(X). 212 DT.State = DefinedTracker::DefinedMacro; 213 DT.TheMacro = II; 214 return false; 215 } 216 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. 221 /// 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 224 /// evaluation. 225 static bool EvaluateValue(PPValue &Result, Token &PeekTok, DefinedTracker &DT, 226 bool ValueLive, Preprocessor &PP) { 227 DT.State = DefinedTracker::Unknown; 228 229 Result.setIdentifier(nullptr); 230 231 if (PeekTok.is(tok::code_completion)) { 232 if (PP.getCodeCompletionHandler()) 233 PP.getCodeCompletionHandler()->CodeCompletePreprocessorExpression(); 234 PP.setCodeCompletionReached(); 235 PP.LexNonComment(PeekTok); 236 } 237 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); 245 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 249 // turns into "1". 250 if (ValueLive && 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); 259 return false; 260 } 261 262 switch (PeekTok.getKind()) { 263 default: // Non-value token. 264 PP.Diag(PeekTok, diag::err_pp_expr_bad_token_start_expr); 265 return true; 266 case tok::eod: 267 case tok::r_paren: 268 // If there is no expression, report and exit. 269 PP.Diag(PeekTok, diag::err_pp_expected_value_in_expr); 270 return true; 271 case tok::numeric_constant: { 272 SmallString<64> IntegerBuffer; 273 bool NumberInvalid = false; 274 StringRef Spelling = PP.getSpelling(PeekTok, IntegerBuffer, 275 &NumberInvalid); 276 if (NumberInvalid) 277 return true; // a diagnostic was already reported 278 279 NumericLiteralParser Literal(Spelling, PeekTok.getLocation(), PP); 280 if (Literal.hadError) 281 return true; // a diagnostic was already reported. 282 283 if (Literal.isFloatingLiteral() || Literal.isImaginary) { 284 PP.Diag(PeekTok, diag::err_pp_illegal_floating_literal); 285 return true; 286 } 287 assert(Literal.isIntegerLiteral() && "Unknown ppnumber"); 288 289 // Complain about, and drop, any ud-suffix. 290 if (Literal.hasUDSuffix()) 291 PP.Diag(PeekTok, diag::err_pp_invalid_udl) << /*integer*/1; 292 293 // 'long long' is a C99 or C++11 feature. 294 if (!PP.getLangOpts().C99 && Literal.isLongLong) { 295 if (PP.getLangOpts().CPlusPlus) 296 PP.Diag(PeekTok, 297 PP.getLangOpts().CPlusPlus11 ? 298 diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong); 299 else 300 PP.Diag(PeekTok, diag::ext_c99_longlong); 301 } 302 303 // Parse the integer literal into Result. 304 if (Literal.GetIntegerValue(Result.Val)) { 305 // Overflow parsing integer literal. 306 if (ValueLive) 307 PP.Diag(PeekTok, diag::err_integer_literal_too_large) 308 << /* Unsigned */ 1; 309 Result.Val.setIsUnsigned(true); 310 } else { 311 // Set the signedness of the result to match whether there was a U suffix 312 // or not. 313 Result.Val.setIsUnsigned(Literal.isUnsigned); 314 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 318 // is 64-bits. 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); 325 } 326 } 327 328 // Consume the token. 329 Result.setRange(PeekTok.getLocation()); 330 PP.LexNonComment(PeekTok); 331 return false; 332 } 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; 341 342 SmallString<32> CharBuffer; 343 bool CharInvalid = false; 344 StringRef ThisTok = PP.getSpelling(PeekTok, CharBuffer, &CharInvalid); 345 if (CharInvalid) 346 return true; 347 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. 352 353 // Character literals are always int or wchar_t, expand to intmax_t. 354 const TargetInfo &TI = PP.getTargetInfo(); 355 unsigned NumBits; 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(); 364 else 365 NumBits = TI.getCharWidth(); 366 367 // Set the width. 368 llvm::APSInt Val(NumBits); 369 // Set the value. 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); 376 377 if (Result.Val.getBitWidth() > Val.getBitWidth()) { 378 Result.Val = Val.extend(Result.Val.getBitWidth()); 379 } else { 380 assert(Result.Val.getBitWidth() == Val.getBitWidth() && 381 "intmax_t smaller than char/wchar_t?"); 382 Result.Val = Val; 383 } 384 385 // Consume the token. 386 Result.setRange(PeekTok.getLocation()); 387 PP.LexNonComment(PeekTok); 388 return false; 389 } 390 case tok::l_paren: { 391 SourceLocation Start = PeekTok.getLocation(); 392 PP.LexNonComment(PeekTok); // Eat the (. 393 // Parse the value and if there are any binary operators involved, parse 394 // them. 395 if (EvaluateValue(Result, PeekTok, DT, ValueLive, PP)) return true; 396 397 // If this is a silly value like (X), which doesn't need parens, check for 398 // !(defined X). 399 if (PeekTok.is(tok::r_paren)) { 400 // Just use DT unmodified as our result. 401 } else { 402 // Otherwise, we have something like (x+y), and we consumed '(x'. 403 if (EvaluateDirectiveSubExpr(Result, 1, PeekTok, ValueLive, PP)) 404 return true; 405 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; 410 return true; 411 } 412 DT.State = DefinedTracker::Unknown; 413 } 414 Result.setRange(Start, PeekTok.getLocation()); 415 Result.setIdentifier(nullptr); 416 PP.LexNonComment(PeekTok); // Eat the ). 417 return false; 418 } 419 case tok::plus: { 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); 426 return false; 427 } 428 case tok::minus: { 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); 434 435 // C99 6.5.3.3p3: The sign of the result matches the sign of the operand. 436 Result.Val = -Result.Val; 437 438 // -MININT is the only thing that overflows. Unsigned never overflows. 439 bool Overflow = !Result.isUnsigned() && Result.Val.isMinSignedValue(); 440 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(); 444 445 DT.State = DefinedTracker::Unknown; 446 return false; 447 } 448 449 case tok::tilde: { 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); 455 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; 459 return false; 460 } 461 462 case tok::exclaim: { 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); 471 472 if (DT.State == DefinedTracker::DefinedMacro) 473 DT.State = DefinedTracker::NotDefinedMacro; 474 else if (DT.State == DefinedTracker::NotDefinedMacro) 475 DT.State = DefinedTracker::DefinedMacro; 476 return false; 477 } 478 479 // FIXME: Handle #assert 480 } 481 } 482 483 /// getPrecedence - Return the precedence of the specified binary operator 484 /// token. This returns: 485 /// ~0 - Invalid token. 486 /// 14 -> 3 - various operators. 487 /// 0 - 'eod' or ')' 488 static unsigned getPrecedence(tok::TokenKind Kind) { 489 switch (Kind) { 490 default: return ~0U; 491 case tok::percent: 492 case tok::slash: 493 case tok::star: return 14; 494 case tok::plus: 495 case tok::minus: return 13; 496 case tok::lessless: 497 case tok::greatergreater: return 12; 498 case tok::lessequal: 499 case tok::less: 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. 514 } 515 } 516 517 static void diagnoseUnexpectedOperator(Preprocessor &PP, PPValue &LHS, 518 Token &Tok) { 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(); 522 else 523 PP.Diag(Tok.getLocation(), diag::err_pp_expr_bad_token_binop) 524 << LHS.getRange(); 525 } 526 527 /// EvaluateDirectiveSubExpr - Evaluate the subexpression whose first token is 528 /// PeekTok, and whose precedence is PeekPrec. This returns the result in LHS. 529 /// 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, 535 Preprocessor &PP) { 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); 540 return true; 541 } 542 543 while (true) { 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) 547 return false; 548 549 tok::TokenKind Operator = PeekTok.getKind(); 550 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 555 // expr dead. 556 bool RHSIsLive; 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. 563 else 564 RHSIsLive = ValueLive; 565 566 // Consume the operator, remembering the operator's location for reporting. 567 SourceLocation OpLoc = PeekTok.getLocation(); 568 PP.LexNonComment(PeekTok); 569 570 PPValue RHS(LHS.getBitWidth()); 571 // Parse the RHS of the operator. 572 DefinedTracker DT; 573 if (EvaluateValue(RHS, PeekTok, DT, RHSIsLive, PP)) return true; 574 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()); 579 580 // If this token isn't valid, report the error. 581 if (PeekPrec == ~0U) { 582 diagnoseUnexpectedOperator(PP, RHS, PeekTok); 583 return true; 584 } 585 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: 592 // 593 // conditional-expression ::= 594 // logical-OR-expression ? expression : conditional-expression 595 // where 'expression' is actually comma-expression. 596 unsigned RHSPrec; 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; 602 603 if (PeekPrec >= RHSPrec) { 604 if (EvaluateDirectiveSubExpr(RHS, RHSPrec, PeekTok, RHSIsLive, PP)) 605 return true; 606 PeekPrec = getPrecedence(PeekTok.getKind()); 607 } 608 assert(PeekPrec <= ThisPrec && "Recursion didn't work!"); 609 610 // Usual arithmetic conversions (C99 6.3.1.8p1): result is unsigned if 611 // either operand is unsigned. 612 llvm::APSInt Res(LHS.getBitWidth()); 613 switch (Operator) { 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. 620 break; // No UAC 621 default: 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(); 636 } 637 LHS.Val.setIsUnsigned(Res.isUnsigned()); 638 RHS.Val.setIsUnsigned(Res.isUnsigned()); 639 } 640 641 bool Overflow = false; 642 switch (Operator) { 643 default: llvm_unreachable("Unknown operator token!"); 644 case tok::percent: 645 if (RHS.Val != 0) 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(); 650 return true; 651 } 652 break; 653 case tok::slash: 654 if (RHS.Val != 0) { 655 if (LHS.Val.isSigned()) 656 Res = llvm::APSInt(LHS.Val.sdiv_ov(RHS.Val, Overflow), false); 657 else 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(); 662 return true; 663 } 664 break; 665 666 case tok::star: 667 if (Res.isSigned()) 668 Res = llvm::APSInt(LHS.Val.smul_ov(RHS.Val, Overflow), false); 669 else 670 Res = LHS.Val * RHS.Val; 671 break; 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); 676 else 677 Res = llvm::APSInt(LHS.Val.sshl_ov(RHS.Val, Overflow), false); 678 break; 679 } 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()) { 684 Overflow = true; 685 ShAmt = LHS.getBitWidth()-1; 686 } 687 Res = LHS.Val >> ShAmt; 688 break; 689 } 690 case tok::plus: 691 if (LHS.isUnsigned()) 692 Res = LHS.Val + RHS.Val; 693 else 694 Res = llvm::APSInt(LHS.Val.sadd_ov(RHS.Val, Overflow), false); 695 break; 696 case tok::minus: 697 if (LHS.isUnsigned()) 698 Res = LHS.Val - RHS.Val; 699 else 700 Res = llvm::APSInt(LHS.Val.ssub_ov(RHS.Val, Overflow), false); 701 break; 702 case tok::lessequal: 703 Res = LHS.Val <= RHS.Val; 704 Res.setIsUnsigned(false); // C99 6.5.8p6, result is always int (signed) 705 break; 706 case tok::less: 707 Res = LHS.Val < RHS.Val; 708 Res.setIsUnsigned(false); // C99 6.5.8p6, result is always int (signed) 709 break; 710 case tok::greaterequal: 711 Res = LHS.Val >= RHS.Val; 712 Res.setIsUnsigned(false); // C99 6.5.8p6, result is always int (signed) 713 break; 714 case tok::greater: 715 Res = LHS.Val > RHS.Val; 716 Res.setIsUnsigned(false); // C99 6.5.8p6, result is always int (signed) 717 break; 718 case tok::exclaimequal: 719 Res = LHS.Val != RHS.Val; 720 Res.setIsUnsigned(false); // C99 6.5.9p3, result is always int (signed) 721 break; 722 case tok::equalequal: 723 Res = LHS.Val == RHS.Val; 724 Res.setIsUnsigned(false); // C99 6.5.9p3, result is always int (signed) 725 break; 726 case tok::amp: 727 Res = LHS.Val & RHS.Val; 728 break; 729 case tok::caret: 730 Res = LHS.Val ^ RHS.Val; 731 break; 732 case tok::pipe: 733 Res = LHS.Val | RHS.Val; 734 break; 735 case tok::ampamp: 736 Res = (LHS.Val != 0 && RHS.Val != 0); 737 Res.setIsUnsigned(false); // C99 6.5.13p3, result is always int (signed) 738 break; 739 case tok::pipepipe: 740 Res = (LHS.Val != 0 || RHS.Val != 0); 741 Res.setIsUnsigned(false); // C99 6.5.14p3, result is always int (signed) 742 break; 743 case tok::comma: 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. 750 break; 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; 757 return true; 758 } 759 // Consume the :. 760 PP.LexNonComment(PeekTok); 761 762 // Evaluate the value after the :. 763 bool AfterColonLive = ValueLive && LHS.Val == 0; 764 PPValue AfterColonVal(LHS.getBitWidth()); 765 DefinedTracker DT; 766 if (EvaluateValue(AfterColonVal, PeekTok, DT, AfterColonLive, PP)) 767 return true; 768 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)) 773 return true; 774 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()); 778 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()); 782 783 // Figure out the precedence of the token after the : part. 784 PeekPrec = getPrecedence(PeekTok.getKind()); 785 break; 786 } 787 case tok::colon: 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(); 791 return true; 792 } 793 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(); 798 799 // Put the result back into 'LHS' for our next iteration. 800 LHS.Val = Res; 801 LHS.setEnd(RHS.getRange().getEnd()); 802 RHS.setIdentifier(nullptr); 803 } 804 } 805 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 816 // expression. 817 bool DisableMacroExpansionAtStartOfDirective = DisableMacroExpansion; 818 DisableMacroExpansion = false; 819 820 // Peek ahead one token. 821 Token Tok; 822 LexNonComment(Tok); 823 824 // C99 6.10.1p3 - All expressions are evaluated as intmax_t or uintmax_t. 825 unsigned BitWidth = getTargetInfo().getIntMaxTWidth(); 826 827 PPValue ResVal(BitWidth); 828 DefinedTracker DT; 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(); 833 834 // Restore 'DisableMacroExpansion'. 835 DisableMacroExpansion = DisableMacroExpansionAtStartOfDirective; 836 return false; 837 } 838 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 841 // directly. 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; 847 848 // Restore 'DisableMacroExpansion'. 849 DisableMacroExpansion = DisableMacroExpansionAtStartOfDirective; 850 return ResVal.Val != 0; 851 } 852 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), 856 Tok, true, *this)) { 857 // Parse error, skip the rest of the macro line. 858 if (Tok.isNot(tok::eod)) 859 DiscardUntilEndOfDirective(); 860 861 // Restore 'DisableMacroExpansion'. 862 DisableMacroExpansion = DisableMacroExpansionAtStartOfDirective; 863 return false; 864 } 865 866 // If we aren't at the tok::eod token, something bad happened, like an extra 867 // ')' token. 868 if (Tok.isNot(tok::eod)) { 869 Diag(Tok, diag::err_pp_expected_eol); 870 DiscardUntilEndOfDirective(); 871 } 872 873 // Restore 'DisableMacroExpansion'. 874 DisableMacroExpansion = DisableMacroExpansionAtStartOfDirective; 875 return ResVal.Val != 0; 876 } 877