PPExpressions.cpp 29 KB

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