blob: cca76289176d73f0d4e0d4a04c352f5e73f2d62c [file] [log] [blame]
Reid Spencer5f016e22007-07-11 17:01:13 +00001//===--- PPExpressions.cpp - Preprocessor Expression Evaluation -----------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Reid Spencer5f016e22007-07-11 17:01:13 +00007//
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/Lex/MacroInfo.h"
21#include "clang/Lex/LiteralSupport.h"
22#include "clang/Basic/TargetInfo.h"
23#include "clang/Basic/TokenKinds.h"
24#include "clang/Basic/Diagnostic.h"
25#include "llvm/ADT/APSInt.h"
26#include "llvm/ADT/SmallString.h"
27using namespace clang;
28
29static bool EvaluateDirectiveSubExpr(llvm::APSInt &LHS, unsigned MinPrec,
Chris Lattnerd2177732007-07-20 16:59:19 +000030 Token &PeekTok, bool ValueLive,
Reid Spencer5f016e22007-07-11 17:01:13 +000031 Preprocessor &PP);
32
33/// DefinedTracker - This struct is used while parsing expressions to keep track
34/// of whether !defined(X) has been seen.
35///
36/// With this simple scheme, we handle the basic forms:
37/// !defined(X) and !defined X
38/// but we also trivially handle (silly) stuff like:
39/// !!!defined(X) and +!defined(X) and !+!+!defined(X) and !(defined(X)).
40struct DefinedTracker {
41 /// Each time a Value is evaluated, it returns information about whether the
42 /// parsed value is of the form defined(X), !defined(X) or is something else.
43 enum TrackerState {
44 DefinedMacro, // defined(X)
45 NotDefinedMacro, // !defined(X)
46 Unknown // Something else.
47 } State;
48 /// TheMacro - When the state is DefinedMacro or NotDefinedMacro, this
49 /// indicates the macro that was checked.
50 IdentifierInfo *TheMacro;
51};
52
53
54
55/// EvaluateValue - Evaluate the token PeekTok (and any others needed) and
56/// return the computed value in Result. Return true if there was an error
57/// parsing. This function also returns information about the form of the
58/// expression in DT. See above for information on what DT means.
59///
60/// If ValueLive is false, then this value is being evaluated in a context where
61/// the result is not used. As such, avoid diagnostics that relate to
62/// evaluation.
Chris Lattnerd2177732007-07-20 16:59:19 +000063static bool EvaluateValue(llvm::APSInt &Result, Token &PeekTok,
Reid Spencer5f016e22007-07-11 17:01:13 +000064 DefinedTracker &DT, bool ValueLive,
65 Preprocessor &PP) {
66 Result = 0;
67 DT.State = DefinedTracker::Unknown;
68
69 // If this token's spelling is a pp-identifier, check to see if it is
70 // 'defined' or if it is a macro. Note that we check here because many
71 // keywords are pp-identifiers, so we can't check the kind.
72 if (IdentifierInfo *II = PeekTok.getIdentifierInfo()) {
73 // If this identifier isn't 'defined' and it wasn't macro expanded, it turns
74 // into a simple 0, unless it is the C++ keyword "true", in which case it
75 // turns into "1".
76 if (II->getPPKeywordID() != tok::pp_defined) {
Chris Lattner116a4b12008-01-23 17:19:46 +000077 PP.Diag(PeekTok, diag::warn_pp_undef_identifier, II->getName());
Reid Spencer5f016e22007-07-11 17:01:13 +000078 Result = II->getTokenID() == tok::kw_true;
79 Result.setIsUnsigned(false); // "0" is signed intmax_t 0.
80 PP.LexNonComment(PeekTok);
81 return false;
82 }
83
84 // Handle "defined X" and "defined(X)".
85
86 // Get the next token, don't expand it.
87 PP.LexUnexpandedToken(PeekTok);
88
89 // Two options, it can either be a pp-identifier or a (.
90 bool InParens = false;
Chris Lattner22f6bbc2007-10-09 18:02:16 +000091 if (PeekTok.is(tok::l_paren)) {
Reid Spencer5f016e22007-07-11 17:01:13 +000092 // Found a paren, remember we saw it and skip it.
93 InParens = true;
94 PP.LexUnexpandedToken(PeekTok);
95 }
96
97 // If we don't have a pp-identifier now, this is an error.
98 if ((II = PeekTok.getIdentifierInfo()) == 0) {
99 PP.Diag(PeekTok, diag::err_pp_defined_requires_identifier);
100 return true;
101 }
102
103 // Otherwise, we got an identifier, is it defined to something?
Chris Lattner0edde552007-10-07 08:04:56 +0000104 Result = II->hasMacroDefinition();
Reid Spencer5f016e22007-07-11 17:01:13 +0000105 Result.setIsUnsigned(false); // Result is signed intmax_t.
106
107 // If there is a macro, mark it used.
108 if (Result != 0 && ValueLive) {
Chris Lattnercc1a8752007-10-07 08:44:20 +0000109 MacroInfo *Macro = PP.getMacroInfo(II);
Chris Lattner0edde552007-10-07 08:04:56 +0000110 Macro->setIsUsed(true);
Reid Spencer5f016e22007-07-11 17:01:13 +0000111 }
112
113 // Consume identifier.
114 PP.LexNonComment(PeekTok);
115
116 // If we are in parens, ensure we have a trailing ).
117 if (InParens) {
Chris Lattner22f6bbc2007-10-09 18:02:16 +0000118 if (PeekTok.isNot(tok::r_paren)) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000119 PP.Diag(PeekTok, diag::err_pp_missing_rparen);
120 return true;
121 }
122 // Consume the ).
123 PP.LexNonComment(PeekTok);
124 }
125
126 // Success, remember that we saw defined(X).
127 DT.State = DefinedTracker::DefinedMacro;
128 DT.TheMacro = II;
129 return false;
130 }
131
132 switch (PeekTok.getKind()) {
133 default: // Non-value token.
134 PP.Diag(PeekTok, diag::err_pp_expr_bad_token);
135 return true;
136 case tok::eom:
137 case tok::r_paren:
138 // If there is no expression, report and exit.
139 PP.Diag(PeekTok, diag::err_pp_expected_value_in_expr);
140 return true;
141 case tok::numeric_constant: {
142 llvm::SmallString<64> IntegerBuffer;
143 IntegerBuffer.resize(PeekTok.getLength());
144 const char *ThisTokBegin = &IntegerBuffer[0];
145 unsigned ActualLength = PP.getSpelling(PeekTok, ThisTokBegin);
146 NumericLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
147 PeekTok.getLocation(), PP);
148 if (Literal.hadError)
149 return true; // a diagnostic was already reported.
150
Chris Lattner6e400c22007-08-26 03:29:23 +0000151 if (Literal.isFloatingLiteral() || Literal.isImaginary) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000152 PP.Diag(PeekTok, diag::err_pp_illegal_floating_literal);
153 return true;
154 }
155 assert(Literal.isIntegerLiteral() && "Unknown ppnumber");
156
Neil Boothb9449512007-08-29 22:00:19 +0000157 // long long is a C99 feature.
158 if (!PP.getLangOptions().C99 && !PP.getLangOptions().CPlusPlus0x
Neil Booth79859c32007-08-29 22:13:52 +0000159 && Literal.isLongLong)
Neil Boothb9449512007-08-29 22:00:19 +0000160 PP.Diag(PeekTok, diag::ext_longlong);
161
Reid Spencer5f016e22007-07-11 17:01:13 +0000162 // Parse the integer literal into Result.
163 if (Literal.GetIntegerValue(Result)) {
164 // Overflow parsing integer literal.
165 if (ValueLive) PP.Diag(PeekTok, diag::warn_integer_too_large);
166 Result.setIsUnsigned(true);
167 } else {
168 // Set the signedness of the result to match whether there was a U suffix
169 // or not.
170 Result.setIsUnsigned(Literal.isUnsigned);
171
172 // Detect overflow based on whether the value is signed. If signed
173 // and if the value is too large, emit a warning "integer constant is so
174 // large that it is unsigned" e.g. on 12345678901234567890 where intmax_t
175 // is 64-bits.
176 if (!Literal.isUnsigned && Result.isNegative()) {
177 if (ValueLive)PP.Diag(PeekTok, diag::warn_integer_too_large_for_signed);
178 Result.setIsUnsigned(true);
179 }
180 }
181
182 // Consume the token.
183 PP.LexNonComment(PeekTok);
184 return false;
185 }
186 case tok::char_constant: { // 'x'
187 llvm::SmallString<32> CharBuffer;
188 CharBuffer.resize(PeekTok.getLength());
189 const char *ThisTokBegin = &CharBuffer[0];
190 unsigned ActualLength = PP.getSpelling(PeekTok, ThisTokBegin);
191 CharLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
192 PeekTok.getLocation(), PP);
193 if (Literal.hadError())
194 return true; // A diagnostic was already emitted.
195
196 // Character literals are always int or wchar_t, expand to intmax_t.
197 TargetInfo &TI = PP.getTargetInfo();
Chris Lattner98be4942008-03-05 18:54:05 +0000198 unsigned NumBits = TI.getCharWidth(Literal.isWide());
Reid Spencer5f016e22007-07-11 17:01:13 +0000199
200 // Set the width.
201 llvm::APSInt Val(NumBits);
202 // Set the value.
203 Val = Literal.getValue();
204 // Set the signedness.
Chris Lattner98be4942008-03-05 18:54:05 +0000205 Val.setIsUnsigned(!TI.isCharSigned());
Reid Spencer5f016e22007-07-11 17:01:13 +0000206
207 if (Result.getBitWidth() > Val.getBitWidth()) {
Chris Lattner98be4942008-03-05 18:54:05 +0000208 Result = Val.extend(Result.getBitWidth());
Reid Spencer5f016e22007-07-11 17:01:13 +0000209 } else {
210 assert(Result.getBitWidth() == Val.getBitWidth() &&
211 "intmax_t smaller than char/wchar_t?");
212 Result = Val;
213 }
214
215 // Consume the token.
216 PP.LexNonComment(PeekTok);
217 return false;
218 }
219 case tok::l_paren:
220 PP.LexNonComment(PeekTok); // Eat the (.
221 // Parse the value and if there are any binary operators involved, parse
222 // them.
223 if (EvaluateValue(Result, PeekTok, DT, ValueLive, PP)) return true;
224
225 // If this is a silly value like (X), which doesn't need parens, check for
226 // !(defined X).
Chris Lattner22f6bbc2007-10-09 18:02:16 +0000227 if (PeekTok.is(tok::r_paren)) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000228 // Just use DT unmodified as our result.
229 } else {
230 if (EvaluateDirectiveSubExpr(Result, 1, PeekTok, ValueLive, PP))
231 return true;
232
Chris Lattner22f6bbc2007-10-09 18:02:16 +0000233 if (PeekTok.isNot(tok::r_paren)) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000234 PP.Diag(PeekTok, diag::err_pp_expected_rparen);
235 return true;
236 }
237 DT.State = DefinedTracker::Unknown;
238 }
239 PP.LexNonComment(PeekTok); // Eat the ).
240 return false;
241
242 case tok::plus:
243 // Unary plus doesn't modify the value.
244 PP.LexNonComment(PeekTok);
245 return EvaluateValue(Result, PeekTok, DT, ValueLive, PP);
246 case tok::minus: {
247 SourceLocation Loc = PeekTok.getLocation();
248 PP.LexNonComment(PeekTok);
249 if (EvaluateValue(Result, PeekTok, DT, ValueLive, PP)) return true;
250 // C99 6.5.3.3p3: The sign of the result matches the sign of the operand.
251 Result = -Result;
252
253 bool Overflow = false;
254 if (Result.isUnsigned())
Dan Gohman376605b2008-02-13 22:09:49 +0000255 Overflow = Result.isNegative();
Reid Spencer5f016e22007-07-11 17:01:13 +0000256 else if (Result.isMinSignedValue())
257 Overflow = true; // -MININT is the only thing that overflows.
258
259 // If this operator is live and overflowed, report the issue.
260 if (Overflow && ValueLive)
261 PP.Diag(Loc, diag::warn_pp_expr_overflow);
262
263 DT.State = DefinedTracker::Unknown;
264 return false;
265 }
266
267 case tok::tilde:
268 PP.LexNonComment(PeekTok);
269 if (EvaluateValue(Result, PeekTok, DT, ValueLive, PP)) return true;
270 // C99 6.5.3.3p4: The sign of the result matches the sign of the operand.
271 Result = ~Result;
272 DT.State = DefinedTracker::Unknown;
273 return false;
274
275 case tok::exclaim:
276 PP.LexNonComment(PeekTok);
277 if (EvaluateValue(Result, PeekTok, DT, ValueLive, PP)) return true;
278 Result = !Result;
279 // C99 6.5.3.3p5: The sign of the result is 'int', aka it is signed.
280 Result.setIsUnsigned(false);
281
282 if (DT.State == DefinedTracker::DefinedMacro)
283 DT.State = DefinedTracker::NotDefinedMacro;
284 else if (DT.State == DefinedTracker::NotDefinedMacro)
285 DT.State = DefinedTracker::DefinedMacro;
286 return false;
287
288 // FIXME: Handle #assert
289 }
290}
291
292
293
294/// getPrecedence - Return the precedence of the specified binary operator
295/// token. This returns:
296/// ~0 - Invalid token.
297/// 14 - *,/,%
298/// 13 - -,+
299/// 12 - <<,>>
300/// 11 - >=, <=, >, <
301/// 10 - ==, !=
302/// 9 - &
303/// 8 - ^
304/// 7 - |
305/// 6 - &&
306/// 5 - ||
307/// 4 - ?
308/// 3 - :
309/// 0 - eom, )
310static unsigned getPrecedence(tok::TokenKind Kind) {
311 switch (Kind) {
312 default: return ~0U;
313 case tok::percent:
314 case tok::slash:
315 case tok::star: return 14;
316 case tok::plus:
317 case tok::minus: return 13;
318 case tok::lessless:
319 case tok::greatergreater: return 12;
320 case tok::lessequal:
321 case tok::less:
322 case tok::greaterequal:
323 case tok::greater: return 11;
324 case tok::exclaimequal:
325 case tok::equalequal: return 10;
326 case tok::amp: return 9;
327 case tok::caret: return 8;
328 case tok::pipe: return 7;
329 case tok::ampamp: return 6;
330 case tok::pipepipe: return 5;
331 case tok::question: return 4;
332 case tok::colon: return 3;
333 case tok::comma: return 2;
334 case tok::r_paren: return 0; // Lowest priority, end of expr.
335 case tok::eom: return 0; // Lowest priority, end of macro.
336 }
337}
338
339
340/// EvaluateDirectiveSubExpr - Evaluate the subexpression whose first token is
341/// PeekTok, and whose precedence is PeekPrec.
342///
343/// If ValueLive is false, then this value is being evaluated in a context where
344/// the result is not used. As such, avoid diagnostics that relate to
345/// evaluation.
346static bool EvaluateDirectiveSubExpr(llvm::APSInt &LHS, unsigned MinPrec,
Chris Lattnerd2177732007-07-20 16:59:19 +0000347 Token &PeekTok, bool ValueLive,
Reid Spencer5f016e22007-07-11 17:01:13 +0000348 Preprocessor &PP) {
349 unsigned PeekPrec = getPrecedence(PeekTok.getKind());
350 // If this token isn't valid, report the error.
351 if (PeekPrec == ~0U) {
352 PP.Diag(PeekTok, diag::err_pp_expr_bad_token);
353 return true;
354 }
355
356 while (1) {
357 // If this token has a lower precedence than we are allowed to parse, return
358 // it so that higher levels of the recursion can parse it.
359 if (PeekPrec < MinPrec)
360 return false;
361
362 tok::TokenKind Operator = PeekTok.getKind();
363
364 // If this is a short-circuiting operator, see if the RHS of the operator is
365 // dead. Note that this cannot just clobber ValueLive. Consider
366 // "0 && 1 ? 4 : 1 / 0", which is parsed as "(0 && 1) ? 4 : (1 / 0)". In
367 // this example, the RHS of the && being dead does not make the rest of the
368 // expr dead.
369 bool RHSIsLive;
370 if (Operator == tok::ampamp && LHS == 0)
371 RHSIsLive = false; // RHS of "0 && x" is dead.
372 else if (Operator == tok::pipepipe && LHS != 0)
373 RHSIsLive = false; // RHS of "1 || x" is dead.
374 else if (Operator == tok::question && LHS == 0)
375 RHSIsLive = false; // RHS (x) of "0 ? x : y" is dead.
376 else
377 RHSIsLive = ValueLive;
378
379 // Consume the operator, saving the operator token for error reporting.
Chris Lattnerd2177732007-07-20 16:59:19 +0000380 Token OpToken = PeekTok;
Reid Spencer5f016e22007-07-11 17:01:13 +0000381 PP.LexNonComment(PeekTok);
382
383 llvm::APSInt RHS(LHS.getBitWidth());
384 // Parse the RHS of the operator.
385 DefinedTracker DT;
386 if (EvaluateValue(RHS, PeekTok, DT, RHSIsLive, PP)) return true;
387
388 // Remember the precedence of this operator and get the precedence of the
389 // operator immediately to the right of the RHS.
390 unsigned ThisPrec = PeekPrec;
391 PeekPrec = getPrecedence(PeekTok.getKind());
392
393 // If this token isn't valid, report the error.
394 if (PeekPrec == ~0U) {
395 PP.Diag(PeekTok, diag::err_pp_expr_bad_token);
396 return true;
397 }
398
399 bool isRightAssoc = Operator == tok::question;
400
401 // Get the precedence of the operator to the right of the RHS. If it binds
402 // more tightly with RHS than we do, evaluate it completely first.
403 if (ThisPrec < PeekPrec ||
404 (ThisPrec == PeekPrec && isRightAssoc)) {
405 if (EvaluateDirectiveSubExpr(RHS, ThisPrec+1, PeekTok, RHSIsLive, PP))
406 return true;
407 PeekPrec = getPrecedence(PeekTok.getKind());
408 }
409 assert(PeekPrec <= ThisPrec && "Recursion didn't work!");
410
411 // Usual arithmetic conversions (C99 6.3.1.8p1): result is unsigned if
412 // either operand is unsigned. Don't do this for x and y in "x ? y : z".
413 llvm::APSInt Res(LHS.getBitWidth());
414 if (Operator != tok::question) {
415 Res.setIsUnsigned(LHS.isUnsigned()|RHS.isUnsigned());
416 // If this just promoted something from signed to unsigned, and if the
417 // value was negative, warn about it.
418 if (ValueLive && Res.isUnsigned()) {
419 if (!LHS.isUnsigned() && LHS.isNegative())
420 PP.Diag(OpToken, diag::warn_pp_convert_lhs_to_positive,
Chris Lattnerb2024b22007-08-23 05:22:10 +0000421 LHS.toStringSigned() + " to " + LHS.toStringUnsigned());
Reid Spencer5f016e22007-07-11 17:01:13 +0000422 if (!RHS.isUnsigned() && RHS.isNegative())
423 PP.Diag(OpToken, diag::warn_pp_convert_rhs_to_positive,
Chris Lattnerb2024b22007-08-23 05:22:10 +0000424 RHS.toStringSigned() + " to " + RHS.toStringUnsigned());
Reid Spencer5f016e22007-07-11 17:01:13 +0000425 }
426 LHS.setIsUnsigned(Res.isUnsigned());
427 RHS.setIsUnsigned(Res.isUnsigned());
428 }
429
430 // FIXME: All of these should detect and report overflow??
431 bool Overflow = false;
432 switch (Operator) {
433 default: assert(0 && "Unknown operator token!");
434 case tok::percent:
435 if (RHS == 0) {
436 if (ValueLive) PP.Diag(OpToken, diag::err_pp_remainder_by_zero);
437 return true;
438 }
439 Res = LHS % RHS;
440 break;
441 case tok::slash:
442 if (RHS == 0) {
443 if (ValueLive) PP.Diag(OpToken, diag::err_pp_division_by_zero);
444 return true;
445 }
446 Res = LHS / RHS;
447 if (LHS.isSigned())
448 Overflow = LHS.isMinSignedValue() && RHS.isAllOnesValue(); // MININT/-1
449 break;
450 case tok::star:
451 Res = LHS * RHS;
452 if (LHS != 0 && RHS != 0)
453 Overflow = Res/RHS != LHS || Res/LHS != RHS;
454 break;
455 case tok::lessless: {
456 // Determine whether overflow is about to happen.
Chris Lattner701e5eb2007-09-04 02:45:27 +0000457 unsigned ShAmt = static_cast<unsigned>(RHS.getLimitedValue());
Reid Spencer5f016e22007-07-11 17:01:13 +0000458 if (ShAmt >= LHS.getBitWidth())
459 Overflow = true, ShAmt = LHS.getBitWidth()-1;
460 else if (LHS.isUnsigned())
461 Overflow = ShAmt > LHS.countLeadingZeros();
Dan Gohman376605b2008-02-13 22:09:49 +0000462 else if (LHS.isNonNegative())
Reid Spencer5f016e22007-07-11 17:01:13 +0000463 Overflow = ShAmt >= LHS.countLeadingZeros(); // Don't allow sign change.
464 else
465 Overflow = ShAmt >= LHS.countLeadingOnes();
466
467 Res = LHS << ShAmt;
468 break;
469 }
470 case tok::greatergreater: {
471 // Determine whether overflow is about to happen.
Chris Lattner701e5eb2007-09-04 02:45:27 +0000472 unsigned ShAmt = static_cast<unsigned>(RHS.getLimitedValue());
Reid Spencer5f016e22007-07-11 17:01:13 +0000473 if (ShAmt >= LHS.getBitWidth())
474 Overflow = true, ShAmt = LHS.getBitWidth()-1;
475 Res = LHS >> ShAmt;
476 break;
477 }
478 case tok::plus:
479 Res = LHS + RHS;
480 if (LHS.isUnsigned())
481 Overflow = Res.ult(LHS);
Dan Gohman376605b2008-02-13 22:09:49 +0000482 else if (LHS.isNonNegative() == RHS.isNonNegative() &&
483 Res.isNonNegative() != LHS.isNonNegative())
Reid Spencer5f016e22007-07-11 17:01:13 +0000484 Overflow = true; // Overflow for signed addition.
485 break;
486 case tok::minus:
487 Res = LHS - RHS;
488 if (LHS.isUnsigned())
489 Overflow = Res.ugt(LHS);
Dan Gohman376605b2008-02-13 22:09:49 +0000490 else if (LHS.isNonNegative() != RHS.isNonNegative() &&
491 Res.isNonNegative() != LHS.isNonNegative())
Reid Spencer5f016e22007-07-11 17:01:13 +0000492 Overflow = true; // Overflow for signed subtraction.
493 break;
494 case tok::lessequal:
495 Res = LHS <= RHS;
496 Res.setIsUnsigned(false); // C99 6.5.8p6, result is always int (signed)
497 break;
498 case tok::less:
499 Res = LHS < RHS;
500 Res.setIsUnsigned(false); // C99 6.5.8p6, result is always int (signed)
501 break;
502 case tok::greaterequal:
503 Res = LHS >= RHS;
504 Res.setIsUnsigned(false); // C99 6.5.8p6, result is always int (signed)
505 break;
506 case tok::greater:
507 Res = LHS > RHS;
508 Res.setIsUnsigned(false); // C99 6.5.8p6, result is always int (signed)
509 break;
510 case tok::exclaimequal:
511 Res = LHS != RHS;
512 Res.setIsUnsigned(false); // C99 6.5.9p3, result is always int (signed)
513 break;
514 case tok::equalequal:
515 Res = LHS == RHS;
516 Res.setIsUnsigned(false); // C99 6.5.9p3, result is always int (signed)
517 break;
518 case tok::amp:
519 Res = LHS & RHS;
520 break;
521 case tok::caret:
522 Res = LHS ^ RHS;
523 break;
524 case tok::pipe:
525 Res = LHS | RHS;
526 break;
527 case tok::ampamp:
528 Res = (LHS != 0 && RHS != 0);
529 Res.setIsUnsigned(false); // C99 6.5.13p3, result is always int (signed)
530 break;
531 case tok::pipepipe:
532 Res = (LHS != 0 || RHS != 0);
533 Res.setIsUnsigned(false); // C99 6.5.14p3, result is always int (signed)
534 break;
535 case tok::comma:
536 PP.Diag(OpToken, diag::ext_pp_comma_expr);
537 Res = RHS; // LHS = LHS,RHS -> RHS.
538 break;
539 case tok::question: {
540 // Parse the : part of the expression.
Chris Lattner22f6bbc2007-10-09 18:02:16 +0000541 if (PeekTok.isNot(tok::colon)) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000542 PP.Diag(OpToken, diag::err_pp_question_without_colon);
543 return true;
544 }
545 // Consume the :.
546 PP.LexNonComment(PeekTok);
547
548 // Evaluate the value after the :.
549 bool AfterColonLive = ValueLive && LHS == 0;
550 llvm::APSInt AfterColonVal(LHS.getBitWidth());
551 DefinedTracker DT;
552 if (EvaluateValue(AfterColonVal, PeekTok, DT, AfterColonLive, PP))
553 return true;
554
555 // Parse anything after the : RHS that has a higher precedence than ?.
556 if (EvaluateDirectiveSubExpr(AfterColonVal, ThisPrec+1,
557 PeekTok, AfterColonLive, PP))
558 return true;
559
560 // Now that we have the condition, the LHS and the RHS of the :, evaluate.
561 Res = LHS != 0 ? RHS : AfterColonVal;
562
563 // Usual arithmetic conversions (C99 6.3.1.8p1): result is unsigned if
564 // either operand is unsigned.
565 Res.setIsUnsigned(RHS.isUnsigned() | AfterColonVal.isUnsigned());
566
567 // Figure out the precedence of the token after the : part.
568 PeekPrec = getPrecedence(PeekTok.getKind());
569 break;
570 }
571 case tok::colon:
572 // Don't allow :'s to float around without being part of ?: exprs.
573 PP.Diag(OpToken, diag::err_pp_colon_without_question);
574 return true;
575 }
576
577 // If this operator is live and overflowed, report the issue.
578 if (Overflow && ValueLive)
579 PP.Diag(OpToken, diag::warn_pp_expr_overflow);
580
581 // Put the result back into 'LHS' for our next iteration.
582 LHS = Res;
583 }
584
585 return false;
586}
587
588/// EvaluateDirectiveExpression - Evaluate an integer constant expression that
589/// may occur after a #if or #elif directive. If the expression is equivalent
590/// to "!defined(X)" return X in IfNDefMacro.
591bool Preprocessor::
592EvaluateDirectiveExpression(IdentifierInfo *&IfNDefMacro) {
593 // Peek ahead one token.
Chris Lattnerd2177732007-07-20 16:59:19 +0000594 Token Tok;
Reid Spencer5f016e22007-07-11 17:01:13 +0000595 Lex(Tok);
596
597 // C99 6.10.1p3 - All expressions are evaluated as intmax_t or uintmax_t.
Chris Lattner98be4942008-03-05 18:54:05 +0000598 unsigned BitWidth = getTargetInfo().getIntMaxTWidth();
Ted Kremenek9c728dc2007-12-12 22:39:36 +0000599
Reid Spencer5f016e22007-07-11 17:01:13 +0000600 llvm::APSInt ResVal(BitWidth);
601 DefinedTracker DT;
602 if (EvaluateValue(ResVal, Tok, DT, true, *this)) {
603 // Parse error, skip the rest of the macro line.
Chris Lattner22f6bbc2007-10-09 18:02:16 +0000604 if (Tok.isNot(tok::eom))
Reid Spencer5f016e22007-07-11 17:01:13 +0000605 DiscardUntilEndOfDirective();
606 return false;
607 }
608
609 // If we are at the end of the expression after just parsing a value, there
610 // must be no (unparenthesized) binary operators involved, so we can exit
611 // directly.
Chris Lattner22f6bbc2007-10-09 18:02:16 +0000612 if (Tok.is(tok::eom)) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000613 // If the expression we parsed was of the form !defined(macro), return the
614 // macro in IfNDefMacro.
615 if (DT.State == DefinedTracker::NotDefinedMacro)
616 IfNDefMacro = DT.TheMacro;
617
618 return ResVal != 0;
619 }
620
621 // Otherwise, we must have a binary operator (e.g. "#if 1 < 2"), so parse the
622 // operator and the stuff after it.
623 if (EvaluateDirectiveSubExpr(ResVal, 1, Tok, true, *this)) {
624 // Parse error, skip the rest of the macro line.
Chris Lattner22f6bbc2007-10-09 18:02:16 +0000625 if (Tok.isNot(tok::eom))
Reid Spencer5f016e22007-07-11 17:01:13 +0000626 DiscardUntilEndOfDirective();
627 return false;
628 }
629
630 // If we aren't at the tok::eom token, something bad happened, like an extra
631 // ')' token.
Chris Lattner22f6bbc2007-10-09 18:02:16 +0000632 if (Tok.isNot(tok::eom)) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000633 Diag(Tok, diag::err_pp_expected_eol);
634 DiscardUntilEndOfDirective();
635 }
636
637 return ResVal != 0;
638}
639