blob: bd7dda4d9a165f63db1c3200e969e80ec6a8c777 [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 // If this is the first use of a target-specific macro, warn about it.
Chris Lattner0edde552007-10-07 08:04:56 +0000113 if (Macro->isTargetSpecific()) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000114 // Don't warn on second use.
Chris Lattner0edde552007-10-07 08:04:56 +0000115 Macro->setIsTargetSpecific(false);
Ted Kremenek9c728dc2007-12-12 22:39:36 +0000116 PP.getTargetInfo().DiagnoseNonPortability(
117 PP.getFullLoc(PeekTok.getLocation()),
118 diag::port_target_macro_use);
Reid Spencer5f016e22007-07-11 17:01:13 +0000119 }
120 } else if (ValueLive) {
121 // Use of a target-specific macro for some other target? If so, warn.
122 if (II->isOtherTargetMacro()) {
123 II->setIsOtherTargetMacro(false); // Don't warn on second use.
Ted Kremenek9c728dc2007-12-12 22:39:36 +0000124 PP.getTargetInfo().DiagnoseNonPortability(
125 PP.getFullLoc(PeekTok.getLocation()),
126 diag::port_target_macro_use);
Reid Spencer5f016e22007-07-11 17:01:13 +0000127 }
128 }
129
130 // Consume identifier.
131 PP.LexNonComment(PeekTok);
132
133 // If we are in parens, ensure we have a trailing ).
134 if (InParens) {
Chris Lattner22f6bbc2007-10-09 18:02:16 +0000135 if (PeekTok.isNot(tok::r_paren)) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000136 PP.Diag(PeekTok, diag::err_pp_missing_rparen);
137 return true;
138 }
139 // Consume the ).
140 PP.LexNonComment(PeekTok);
141 }
142
143 // Success, remember that we saw defined(X).
144 DT.State = DefinedTracker::DefinedMacro;
145 DT.TheMacro = II;
146 return false;
147 }
148
149 switch (PeekTok.getKind()) {
150 default: // Non-value token.
151 PP.Diag(PeekTok, diag::err_pp_expr_bad_token);
152 return true;
153 case tok::eom:
154 case tok::r_paren:
155 // If there is no expression, report and exit.
156 PP.Diag(PeekTok, diag::err_pp_expected_value_in_expr);
157 return true;
158 case tok::numeric_constant: {
159 llvm::SmallString<64> IntegerBuffer;
160 IntegerBuffer.resize(PeekTok.getLength());
161 const char *ThisTokBegin = &IntegerBuffer[0];
162 unsigned ActualLength = PP.getSpelling(PeekTok, ThisTokBegin);
163 NumericLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
164 PeekTok.getLocation(), PP);
165 if (Literal.hadError)
166 return true; // a diagnostic was already reported.
167
Chris Lattner6e400c22007-08-26 03:29:23 +0000168 if (Literal.isFloatingLiteral() || Literal.isImaginary) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000169 PP.Diag(PeekTok, diag::err_pp_illegal_floating_literal);
170 return true;
171 }
172 assert(Literal.isIntegerLiteral() && "Unknown ppnumber");
173
Neil Boothb9449512007-08-29 22:00:19 +0000174 // long long is a C99 feature.
175 if (!PP.getLangOptions().C99 && !PP.getLangOptions().CPlusPlus0x
Neil Booth79859c32007-08-29 22:13:52 +0000176 && Literal.isLongLong)
Neil Boothb9449512007-08-29 22:00:19 +0000177 PP.Diag(PeekTok, diag::ext_longlong);
178
Reid Spencer5f016e22007-07-11 17:01:13 +0000179 // Parse the integer literal into Result.
180 if (Literal.GetIntegerValue(Result)) {
181 // Overflow parsing integer literal.
182 if (ValueLive) PP.Diag(PeekTok, diag::warn_integer_too_large);
183 Result.setIsUnsigned(true);
184 } else {
185 // Set the signedness of the result to match whether there was a U suffix
186 // or not.
187 Result.setIsUnsigned(Literal.isUnsigned);
188
189 // Detect overflow based on whether the value is signed. If signed
190 // and if the value is too large, emit a warning "integer constant is so
191 // large that it is unsigned" e.g. on 12345678901234567890 where intmax_t
192 // is 64-bits.
193 if (!Literal.isUnsigned && Result.isNegative()) {
194 if (ValueLive)PP.Diag(PeekTok, diag::warn_integer_too_large_for_signed);
195 Result.setIsUnsigned(true);
196 }
197 }
198
199 // Consume the token.
200 PP.LexNonComment(PeekTok);
201 return false;
202 }
203 case tok::char_constant: { // 'x'
204 llvm::SmallString<32> CharBuffer;
205 CharBuffer.resize(PeekTok.getLength());
206 const char *ThisTokBegin = &CharBuffer[0];
207 unsigned ActualLength = PP.getSpelling(PeekTok, ThisTokBegin);
208 CharLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
209 PeekTok.getLocation(), PP);
210 if (Literal.hadError())
211 return true; // A diagnostic was already emitted.
212
213 // Character literals are always int or wchar_t, expand to intmax_t.
214 TargetInfo &TI = PP.getTargetInfo();
215 unsigned NumBits;
216 if (Literal.isWide())
Ted Kremenek9c728dc2007-12-12 22:39:36 +0000217 NumBits = TI.getWCharWidth(PP.getFullLoc(PeekTok.getLocation()));
Reid Spencer5f016e22007-07-11 17:01:13 +0000218 else
Ted Kremenek9c728dc2007-12-12 22:39:36 +0000219 NumBits = TI.getCharWidth(PP.getFullLoc(PeekTok.getLocation()));
Reid Spencer5f016e22007-07-11 17:01:13 +0000220
221 // Set the width.
222 llvm::APSInt Val(NumBits);
223 // Set the value.
224 Val = Literal.getValue();
225 // Set the signedness.
Ted Kremenek9c728dc2007-12-12 22:39:36 +0000226 Val.setIsUnsigned(!TI.isCharSigned(PP.getFullLoc(PeekTok.getLocation())));
Reid Spencer5f016e22007-07-11 17:01:13 +0000227
228 if (Result.getBitWidth() > Val.getBitWidth()) {
229 if (Val.isSigned())
230 Result = Val.sext(Result.getBitWidth());
231 else
232 Result = Val.zext(Result.getBitWidth());
233 Result.setIsUnsigned(Val.isUnsigned());
234 } else {
235 assert(Result.getBitWidth() == Val.getBitWidth() &&
236 "intmax_t smaller than char/wchar_t?");
237 Result = Val;
238 }
239
240 // Consume the token.
241 PP.LexNonComment(PeekTok);
242 return false;
243 }
244 case tok::l_paren:
245 PP.LexNonComment(PeekTok); // Eat the (.
246 // Parse the value and if there are any binary operators involved, parse
247 // them.
248 if (EvaluateValue(Result, PeekTok, DT, ValueLive, PP)) return true;
249
250 // If this is a silly value like (X), which doesn't need parens, check for
251 // !(defined X).
Chris Lattner22f6bbc2007-10-09 18:02:16 +0000252 if (PeekTok.is(tok::r_paren)) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000253 // Just use DT unmodified as our result.
254 } else {
255 if (EvaluateDirectiveSubExpr(Result, 1, PeekTok, ValueLive, PP))
256 return true;
257
Chris Lattner22f6bbc2007-10-09 18:02:16 +0000258 if (PeekTok.isNot(tok::r_paren)) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000259 PP.Diag(PeekTok, diag::err_pp_expected_rparen);
260 return true;
261 }
262 DT.State = DefinedTracker::Unknown;
263 }
264 PP.LexNonComment(PeekTok); // Eat the ).
265 return false;
266
267 case tok::plus:
268 // Unary plus doesn't modify the value.
269 PP.LexNonComment(PeekTok);
270 return EvaluateValue(Result, PeekTok, DT, ValueLive, PP);
271 case tok::minus: {
272 SourceLocation Loc = PeekTok.getLocation();
273 PP.LexNonComment(PeekTok);
274 if (EvaluateValue(Result, PeekTok, DT, ValueLive, PP)) return true;
275 // C99 6.5.3.3p3: The sign of the result matches the sign of the operand.
276 Result = -Result;
277
278 bool Overflow = false;
279 if (Result.isUnsigned())
280 Overflow = !Result.isPositive();
281 else if (Result.isMinSignedValue())
282 Overflow = true; // -MININT is the only thing that overflows.
283
284 // If this operator is live and overflowed, report the issue.
285 if (Overflow && ValueLive)
286 PP.Diag(Loc, diag::warn_pp_expr_overflow);
287
288 DT.State = DefinedTracker::Unknown;
289 return false;
290 }
291
292 case tok::tilde:
293 PP.LexNonComment(PeekTok);
294 if (EvaluateValue(Result, PeekTok, DT, ValueLive, PP)) return true;
295 // C99 6.5.3.3p4: The sign of the result matches the sign of the operand.
296 Result = ~Result;
297 DT.State = DefinedTracker::Unknown;
298 return false;
299
300 case tok::exclaim:
301 PP.LexNonComment(PeekTok);
302 if (EvaluateValue(Result, PeekTok, DT, ValueLive, PP)) return true;
303 Result = !Result;
304 // C99 6.5.3.3p5: The sign of the result is 'int', aka it is signed.
305 Result.setIsUnsigned(false);
306
307 if (DT.State == DefinedTracker::DefinedMacro)
308 DT.State = DefinedTracker::NotDefinedMacro;
309 else if (DT.State == DefinedTracker::NotDefinedMacro)
310 DT.State = DefinedTracker::DefinedMacro;
311 return false;
312
313 // FIXME: Handle #assert
314 }
315}
316
317
318
319/// getPrecedence - Return the precedence of the specified binary operator
320/// token. This returns:
321/// ~0 - Invalid token.
322/// 14 - *,/,%
323/// 13 - -,+
324/// 12 - <<,>>
325/// 11 - >=, <=, >, <
326/// 10 - ==, !=
327/// 9 - &
328/// 8 - ^
329/// 7 - |
330/// 6 - &&
331/// 5 - ||
332/// 4 - ?
333/// 3 - :
334/// 0 - eom, )
335static unsigned getPrecedence(tok::TokenKind Kind) {
336 switch (Kind) {
337 default: return ~0U;
338 case tok::percent:
339 case tok::slash:
340 case tok::star: return 14;
341 case tok::plus:
342 case tok::minus: return 13;
343 case tok::lessless:
344 case tok::greatergreater: return 12;
345 case tok::lessequal:
346 case tok::less:
347 case tok::greaterequal:
348 case tok::greater: return 11;
349 case tok::exclaimequal:
350 case tok::equalequal: return 10;
351 case tok::amp: return 9;
352 case tok::caret: return 8;
353 case tok::pipe: return 7;
354 case tok::ampamp: return 6;
355 case tok::pipepipe: return 5;
356 case tok::question: return 4;
357 case tok::colon: return 3;
358 case tok::comma: return 2;
359 case tok::r_paren: return 0; // Lowest priority, end of expr.
360 case tok::eom: return 0; // Lowest priority, end of macro.
361 }
362}
363
364
365/// EvaluateDirectiveSubExpr - Evaluate the subexpression whose first token is
366/// PeekTok, and whose precedence is PeekPrec.
367///
368/// If ValueLive is false, then this value is being evaluated in a context where
369/// the result is not used. As such, avoid diagnostics that relate to
370/// evaluation.
371static bool EvaluateDirectiveSubExpr(llvm::APSInt &LHS, unsigned MinPrec,
Chris Lattnerd2177732007-07-20 16:59:19 +0000372 Token &PeekTok, bool ValueLive,
Reid Spencer5f016e22007-07-11 17:01:13 +0000373 Preprocessor &PP) {
374 unsigned PeekPrec = getPrecedence(PeekTok.getKind());
375 // If this token isn't valid, report the error.
376 if (PeekPrec == ~0U) {
377 PP.Diag(PeekTok, diag::err_pp_expr_bad_token);
378 return true;
379 }
380
381 while (1) {
382 // If this token has a lower precedence than we are allowed to parse, return
383 // it so that higher levels of the recursion can parse it.
384 if (PeekPrec < MinPrec)
385 return false;
386
387 tok::TokenKind Operator = PeekTok.getKind();
388
389 // If this is a short-circuiting operator, see if the RHS of the operator is
390 // dead. Note that this cannot just clobber ValueLive. Consider
391 // "0 && 1 ? 4 : 1 / 0", which is parsed as "(0 && 1) ? 4 : (1 / 0)". In
392 // this example, the RHS of the && being dead does not make the rest of the
393 // expr dead.
394 bool RHSIsLive;
395 if (Operator == tok::ampamp && LHS == 0)
396 RHSIsLive = false; // RHS of "0 && x" is dead.
397 else if (Operator == tok::pipepipe && LHS != 0)
398 RHSIsLive = false; // RHS of "1 || x" is dead.
399 else if (Operator == tok::question && LHS == 0)
400 RHSIsLive = false; // RHS (x) of "0 ? x : y" is dead.
401 else
402 RHSIsLive = ValueLive;
403
404 // Consume the operator, saving the operator token for error reporting.
Chris Lattnerd2177732007-07-20 16:59:19 +0000405 Token OpToken = PeekTok;
Reid Spencer5f016e22007-07-11 17:01:13 +0000406 PP.LexNonComment(PeekTok);
407
408 llvm::APSInt RHS(LHS.getBitWidth());
409 // Parse the RHS of the operator.
410 DefinedTracker DT;
411 if (EvaluateValue(RHS, PeekTok, DT, RHSIsLive, PP)) return true;
412
413 // Remember the precedence of this operator and get the precedence of the
414 // operator immediately to the right of the RHS.
415 unsigned ThisPrec = PeekPrec;
416 PeekPrec = getPrecedence(PeekTok.getKind());
417
418 // If this token isn't valid, report the error.
419 if (PeekPrec == ~0U) {
420 PP.Diag(PeekTok, diag::err_pp_expr_bad_token);
421 return true;
422 }
423
424 bool isRightAssoc = Operator == tok::question;
425
426 // Get the precedence of the operator to the right of the RHS. If it binds
427 // more tightly with RHS than we do, evaluate it completely first.
428 if (ThisPrec < PeekPrec ||
429 (ThisPrec == PeekPrec && isRightAssoc)) {
430 if (EvaluateDirectiveSubExpr(RHS, ThisPrec+1, PeekTok, RHSIsLive, PP))
431 return true;
432 PeekPrec = getPrecedence(PeekTok.getKind());
433 }
434 assert(PeekPrec <= ThisPrec && "Recursion didn't work!");
435
436 // Usual arithmetic conversions (C99 6.3.1.8p1): result is unsigned if
437 // either operand is unsigned. Don't do this for x and y in "x ? y : z".
438 llvm::APSInt Res(LHS.getBitWidth());
439 if (Operator != tok::question) {
440 Res.setIsUnsigned(LHS.isUnsigned()|RHS.isUnsigned());
441 // If this just promoted something from signed to unsigned, and if the
442 // value was negative, warn about it.
443 if (ValueLive && Res.isUnsigned()) {
444 if (!LHS.isUnsigned() && LHS.isNegative())
445 PP.Diag(OpToken, diag::warn_pp_convert_lhs_to_positive,
Chris Lattnerb2024b22007-08-23 05:22:10 +0000446 LHS.toStringSigned() + " to " + LHS.toStringUnsigned());
Reid Spencer5f016e22007-07-11 17:01:13 +0000447 if (!RHS.isUnsigned() && RHS.isNegative())
448 PP.Diag(OpToken, diag::warn_pp_convert_rhs_to_positive,
Chris Lattnerb2024b22007-08-23 05:22:10 +0000449 RHS.toStringSigned() + " to " + RHS.toStringUnsigned());
Reid Spencer5f016e22007-07-11 17:01:13 +0000450 }
451 LHS.setIsUnsigned(Res.isUnsigned());
452 RHS.setIsUnsigned(Res.isUnsigned());
453 }
454
455 // FIXME: All of these should detect and report overflow??
456 bool Overflow = false;
457 switch (Operator) {
458 default: assert(0 && "Unknown operator token!");
459 case tok::percent:
460 if (RHS == 0) {
461 if (ValueLive) PP.Diag(OpToken, diag::err_pp_remainder_by_zero);
462 return true;
463 }
464 Res = LHS % RHS;
465 break;
466 case tok::slash:
467 if (RHS == 0) {
468 if (ValueLive) PP.Diag(OpToken, diag::err_pp_division_by_zero);
469 return true;
470 }
471 Res = LHS / RHS;
472 if (LHS.isSigned())
473 Overflow = LHS.isMinSignedValue() && RHS.isAllOnesValue(); // MININT/-1
474 break;
475 case tok::star:
476 Res = LHS * RHS;
477 if (LHS != 0 && RHS != 0)
478 Overflow = Res/RHS != LHS || Res/LHS != RHS;
479 break;
480 case tok::lessless: {
481 // Determine whether overflow is about to happen.
Chris Lattner701e5eb2007-09-04 02:45:27 +0000482 unsigned ShAmt = static_cast<unsigned>(RHS.getLimitedValue());
Reid Spencer5f016e22007-07-11 17:01:13 +0000483 if (ShAmt >= LHS.getBitWidth())
484 Overflow = true, ShAmt = LHS.getBitWidth()-1;
485 else if (LHS.isUnsigned())
486 Overflow = ShAmt > LHS.countLeadingZeros();
487 else if (LHS.isPositive())
488 Overflow = ShAmt >= LHS.countLeadingZeros(); // Don't allow sign change.
489 else
490 Overflow = ShAmt >= LHS.countLeadingOnes();
491
492 Res = LHS << ShAmt;
493 break;
494 }
495 case tok::greatergreater: {
496 // Determine whether overflow is about to happen.
Chris Lattner701e5eb2007-09-04 02:45:27 +0000497 unsigned ShAmt = static_cast<unsigned>(RHS.getLimitedValue());
Reid Spencer5f016e22007-07-11 17:01:13 +0000498 if (ShAmt >= LHS.getBitWidth())
499 Overflow = true, ShAmt = LHS.getBitWidth()-1;
500 Res = LHS >> ShAmt;
501 break;
502 }
503 case tok::plus:
504 Res = LHS + RHS;
505 if (LHS.isUnsigned())
506 Overflow = Res.ult(LHS);
507 else if (LHS.isPositive() == RHS.isPositive() &&
508 Res.isPositive() != LHS.isPositive())
509 Overflow = true; // Overflow for signed addition.
510 break;
511 case tok::minus:
512 Res = LHS - RHS;
513 if (LHS.isUnsigned())
514 Overflow = Res.ugt(LHS);
515 else if (LHS.isPositive() != RHS.isPositive() &&
516 Res.isPositive() != LHS.isPositive())
517 Overflow = true; // Overflow for signed subtraction.
518 break;
519 case tok::lessequal:
520 Res = LHS <= RHS;
521 Res.setIsUnsigned(false); // C99 6.5.8p6, result is always int (signed)
522 break;
523 case tok::less:
524 Res = LHS < RHS;
525 Res.setIsUnsigned(false); // C99 6.5.8p6, result is always int (signed)
526 break;
527 case tok::greaterequal:
528 Res = LHS >= RHS;
529 Res.setIsUnsigned(false); // C99 6.5.8p6, result is always int (signed)
530 break;
531 case tok::greater:
532 Res = LHS > RHS;
533 Res.setIsUnsigned(false); // C99 6.5.8p6, result is always int (signed)
534 break;
535 case tok::exclaimequal:
536 Res = LHS != RHS;
537 Res.setIsUnsigned(false); // C99 6.5.9p3, result is always int (signed)
538 break;
539 case tok::equalequal:
540 Res = LHS == RHS;
541 Res.setIsUnsigned(false); // C99 6.5.9p3, result is always int (signed)
542 break;
543 case tok::amp:
544 Res = LHS & RHS;
545 break;
546 case tok::caret:
547 Res = LHS ^ RHS;
548 break;
549 case tok::pipe:
550 Res = LHS | RHS;
551 break;
552 case tok::ampamp:
553 Res = (LHS != 0 && RHS != 0);
554 Res.setIsUnsigned(false); // C99 6.5.13p3, result is always int (signed)
555 break;
556 case tok::pipepipe:
557 Res = (LHS != 0 || RHS != 0);
558 Res.setIsUnsigned(false); // C99 6.5.14p3, result is always int (signed)
559 break;
560 case tok::comma:
561 PP.Diag(OpToken, diag::ext_pp_comma_expr);
562 Res = RHS; // LHS = LHS,RHS -> RHS.
563 break;
564 case tok::question: {
565 // Parse the : part of the expression.
Chris Lattner22f6bbc2007-10-09 18:02:16 +0000566 if (PeekTok.isNot(tok::colon)) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000567 PP.Diag(OpToken, diag::err_pp_question_without_colon);
568 return true;
569 }
570 // Consume the :.
571 PP.LexNonComment(PeekTok);
572
573 // Evaluate the value after the :.
574 bool AfterColonLive = ValueLive && LHS == 0;
575 llvm::APSInt AfterColonVal(LHS.getBitWidth());
576 DefinedTracker DT;
577 if (EvaluateValue(AfterColonVal, PeekTok, DT, AfterColonLive, PP))
578 return true;
579
580 // Parse anything after the : RHS that has a higher precedence than ?.
581 if (EvaluateDirectiveSubExpr(AfterColonVal, ThisPrec+1,
582 PeekTok, AfterColonLive, PP))
583 return true;
584
585 // Now that we have the condition, the LHS and the RHS of the :, evaluate.
586 Res = LHS != 0 ? RHS : AfterColonVal;
587
588 // Usual arithmetic conversions (C99 6.3.1.8p1): result is unsigned if
589 // either operand is unsigned.
590 Res.setIsUnsigned(RHS.isUnsigned() | AfterColonVal.isUnsigned());
591
592 // Figure out the precedence of the token after the : part.
593 PeekPrec = getPrecedence(PeekTok.getKind());
594 break;
595 }
596 case tok::colon:
597 // Don't allow :'s to float around without being part of ?: exprs.
598 PP.Diag(OpToken, diag::err_pp_colon_without_question);
599 return true;
600 }
601
602 // If this operator is live and overflowed, report the issue.
603 if (Overflow && ValueLive)
604 PP.Diag(OpToken, diag::warn_pp_expr_overflow);
605
606 // Put the result back into 'LHS' for our next iteration.
607 LHS = Res;
608 }
609
610 return false;
611}
612
613/// EvaluateDirectiveExpression - Evaluate an integer constant expression that
614/// may occur after a #if or #elif directive. If the expression is equivalent
615/// to "!defined(X)" return X in IfNDefMacro.
616bool Preprocessor::
617EvaluateDirectiveExpression(IdentifierInfo *&IfNDefMacro) {
618 // Peek ahead one token.
Chris Lattnerd2177732007-07-20 16:59:19 +0000619 Token Tok;
Reid Spencer5f016e22007-07-11 17:01:13 +0000620 Lex(Tok);
621
622 // C99 6.10.1p3 - All expressions are evaluated as intmax_t or uintmax_t.
Ted Kremenek9c728dc2007-12-12 22:39:36 +0000623 unsigned BitWidth =
624 getTargetInfo().getIntMaxTWidth(getFullLoc(Tok.getLocation()));
625
Reid Spencer5f016e22007-07-11 17:01:13 +0000626 llvm::APSInt ResVal(BitWidth);
627 DefinedTracker DT;
628 if (EvaluateValue(ResVal, Tok, DT, true, *this)) {
629 // Parse error, skip the rest of the macro line.
Chris Lattner22f6bbc2007-10-09 18:02:16 +0000630 if (Tok.isNot(tok::eom))
Reid Spencer5f016e22007-07-11 17:01:13 +0000631 DiscardUntilEndOfDirective();
632 return false;
633 }
634
635 // If we are at the end of the expression after just parsing a value, there
636 // must be no (unparenthesized) binary operators involved, so we can exit
637 // directly.
Chris Lattner22f6bbc2007-10-09 18:02:16 +0000638 if (Tok.is(tok::eom)) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000639 // If the expression we parsed was of the form !defined(macro), return the
640 // macro in IfNDefMacro.
641 if (DT.State == DefinedTracker::NotDefinedMacro)
642 IfNDefMacro = DT.TheMacro;
643
644 return ResVal != 0;
645 }
646
647 // Otherwise, we must have a binary operator (e.g. "#if 1 < 2"), so parse the
648 // operator and the stuff after it.
649 if (EvaluateDirectiveSubExpr(ResVal, 1, Tok, true, *this)) {
650 // Parse error, skip the rest of the macro line.
Chris Lattner22f6bbc2007-10-09 18:02:16 +0000651 if (Tok.isNot(tok::eom))
Reid Spencer5f016e22007-07-11 17:01:13 +0000652 DiscardUntilEndOfDirective();
653 return false;
654 }
655
656 // If we aren't at the tok::eom token, something bad happened, like an extra
657 // ')' token.
Chris Lattner22f6bbc2007-10-09 18:02:16 +0000658 if (Tok.isNot(tok::eom)) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000659 Diag(Tok, diag::err_pp_expected_eol);
660 DiscardUntilEndOfDirective();
661 }
662
663 return ResVal != 0;
664}
665