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