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