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