blob: ff0578067cf06fd1582661a8aa23fb26747a8513 [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.
Chris Lattnerd98d9752008-04-13 20:38:43 +0000134 PP.Diag(PeekTok, diag::err_pp_expr_bad_token_start_expr);
Reid Spencer5f016e22007-07-11 17:01:13 +0000135 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.
Chris Lattner9e66ba62008-05-05 04:10:51 +0000297/// 14 -> 3 - various operators.
298/// 0 - 'eom' or ')'
Reid Spencer5f016e22007-07-11 17:01:13 +0000299static unsigned getPrecedence(tok::TokenKind Kind) {
300 switch (Kind) {
301 default: return ~0U;
302 case tok::percent:
303 case tok::slash:
304 case tok::star: return 14;
305 case tok::plus:
306 case tok::minus: return 13;
307 case tok::lessless:
308 case tok::greatergreater: return 12;
309 case tok::lessequal:
310 case tok::less:
311 case tok::greaterequal:
312 case tok::greater: return 11;
313 case tok::exclaimequal:
314 case tok::equalequal: return 10;
315 case tok::amp: return 9;
316 case tok::caret: return 8;
317 case tok::pipe: return 7;
318 case tok::ampamp: return 6;
319 case tok::pipepipe: return 5;
Chris Lattner91891562008-05-04 18:36:18 +0000320 case tok::comma: return 4;
321 case tok::question: return 3;
322 case tok::colon: return 2;
Reid Spencer5f016e22007-07-11 17:01:13 +0000323 case tok::r_paren: return 0; // Lowest priority, end of expr.
324 case tok::eom: return 0; // Lowest priority, end of macro.
325 }
326}
327
328
329/// EvaluateDirectiveSubExpr - Evaluate the subexpression whose first token is
330/// PeekTok, and whose precedence is PeekPrec.
331///
332/// If ValueLive is false, then this value is being evaluated in a context where
333/// the result is not used. As such, avoid diagnostics that relate to
334/// evaluation.
335static bool EvaluateDirectiveSubExpr(llvm::APSInt &LHS, unsigned MinPrec,
Chris Lattnerd2177732007-07-20 16:59:19 +0000336 Token &PeekTok, bool ValueLive,
Reid Spencer5f016e22007-07-11 17:01:13 +0000337 Preprocessor &PP) {
338 unsigned PeekPrec = getPrecedence(PeekTok.getKind());
339 // If this token isn't valid, report the error.
340 if (PeekPrec == ~0U) {
Chris Lattnerd98d9752008-04-13 20:38:43 +0000341 PP.Diag(PeekTok, diag::err_pp_expr_bad_token_binop);
Reid Spencer5f016e22007-07-11 17:01:13 +0000342 return true;
343 }
344
345 while (1) {
346 // If this token has a lower precedence than we are allowed to parse, return
347 // it so that higher levels of the recursion can parse it.
348 if (PeekPrec < MinPrec)
349 return false;
350
351 tok::TokenKind Operator = PeekTok.getKind();
352
353 // If this is a short-circuiting operator, see if the RHS of the operator is
354 // dead. Note that this cannot just clobber ValueLive. Consider
355 // "0 && 1 ? 4 : 1 / 0", which is parsed as "(0 && 1) ? 4 : (1 / 0)". In
356 // this example, the RHS of the && being dead does not make the rest of the
357 // expr dead.
358 bool RHSIsLive;
359 if (Operator == tok::ampamp && LHS == 0)
360 RHSIsLive = false; // RHS of "0 && x" is dead.
361 else if (Operator == tok::pipepipe && LHS != 0)
362 RHSIsLive = false; // RHS of "1 || x" is dead.
363 else if (Operator == tok::question && LHS == 0)
364 RHSIsLive = false; // RHS (x) of "0 ? x : y" is dead.
365 else
366 RHSIsLive = ValueLive;
367
368 // Consume the operator, saving the operator token for error reporting.
Chris Lattnerd2177732007-07-20 16:59:19 +0000369 Token OpToken = PeekTok;
Reid Spencer5f016e22007-07-11 17:01:13 +0000370 PP.LexNonComment(PeekTok);
371
372 llvm::APSInt RHS(LHS.getBitWidth());
373 // Parse the RHS of the operator.
374 DefinedTracker DT;
375 if (EvaluateValue(RHS, PeekTok, DT, RHSIsLive, PP)) return true;
376
377 // Remember the precedence of this operator and get the precedence of the
378 // operator immediately to the right of the RHS.
379 unsigned ThisPrec = PeekPrec;
380 PeekPrec = getPrecedence(PeekTok.getKind());
381
382 // If this token isn't valid, report the error.
383 if (PeekPrec == ~0U) {
Chris Lattnerd98d9752008-04-13 20:38:43 +0000384 PP.Diag(PeekTok, diag::err_pp_expr_bad_token_binop);
Reid Spencer5f016e22007-07-11 17:01:13 +0000385 return true;
386 }
387
388 bool isRightAssoc = Operator == tok::question;
389
390 // Get the precedence of the operator to the right of the RHS. If it binds
391 // more tightly with RHS than we do, evaluate it completely first.
392 if (ThisPrec < PeekPrec ||
393 (ThisPrec == PeekPrec && isRightAssoc)) {
Chris Lattner9e66ba62008-05-05 04:10:51 +0000394 if (EvaluateDirectiveSubExpr(RHS, ThisPrec+!isRightAssoc,
395 PeekTok, RHSIsLive, PP))
Reid Spencer5f016e22007-07-11 17:01:13 +0000396 return true;
397 PeekPrec = getPrecedence(PeekTok.getKind());
398 }
399 assert(PeekPrec <= ThisPrec && "Recursion didn't work!");
400
401 // Usual arithmetic conversions (C99 6.3.1.8p1): result is unsigned if
Chris Lattner019ef7e2008-05-04 23:46:17 +0000402 // either operand is unsigned.
Reid Spencer5f016e22007-07-11 17:01:13 +0000403 llvm::APSInt Res(LHS.getBitWidth());
Chris Lattner019ef7e2008-05-04 23:46:17 +0000404 switch (Operator) {
405 case tok::question: // No UAC for x and y in "x ? y : z".
406 case tok::lessless: // Shift amount doesn't UAC with shift value.
407 case tok::greatergreater: // Shift amount doesn't UAC with shift value.
408 case tok::comma: // Comma operands are not subject to UACs.
409 case tok::pipepipe: // Logical || does not do UACs.
410 case tok::ampamp: // Logical && does not do UACs.
411 break; // No UAC
412 default:
Reid Spencer5f016e22007-07-11 17:01:13 +0000413 Res.setIsUnsigned(LHS.isUnsigned()|RHS.isUnsigned());
414 // If this just promoted something from signed to unsigned, and if the
415 // value was negative, warn about it.
416 if (ValueLive && Res.isUnsigned()) {
417 if (!LHS.isUnsigned() && LHS.isNegative())
418 PP.Diag(OpToken, diag::warn_pp_convert_lhs_to_positive,
Chris Lattnerb2024b22007-08-23 05:22:10 +0000419 LHS.toStringSigned() + " to " + LHS.toStringUnsigned());
Reid Spencer5f016e22007-07-11 17:01:13 +0000420 if (!RHS.isUnsigned() && RHS.isNegative())
421 PP.Diag(OpToken, diag::warn_pp_convert_rhs_to_positive,
Chris Lattnerb2024b22007-08-23 05:22:10 +0000422 RHS.toStringSigned() + " to " + RHS.toStringUnsigned());
Reid Spencer5f016e22007-07-11 17:01:13 +0000423 }
424 LHS.setIsUnsigned(Res.isUnsigned());
425 RHS.setIsUnsigned(Res.isUnsigned());
426 }
427
428 // FIXME: All of these should detect and report overflow??
429 bool Overflow = false;
430 switch (Operator) {
431 default: assert(0 && "Unknown operator token!");
432 case tok::percent:
433 if (RHS == 0) {
Chris Lattner3b691152008-05-04 07:15:21 +0000434 if (ValueLive) {
435 PP.Diag(OpToken, diag::err_pp_remainder_by_zero);
436 return true;
437 }
438 } else {
439 Res = LHS % RHS;
Reid Spencer5f016e22007-07-11 17:01:13 +0000440 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000441 break;
442 case tok::slash:
443 if (RHS == 0) {
Chris Lattner3b691152008-05-04 07:15:21 +0000444 if (ValueLive) {
445 PP.Diag(OpToken, diag::err_pp_division_by_zero);
446 return true;
447 }
448 break;
Reid Spencer5f016e22007-07-11 17:01:13 +0000449 }
Chris Lattner3b691152008-05-04 07:15:21 +0000450
Reid Spencer5f016e22007-07-11 17:01:13 +0000451 Res = LHS / RHS;
452 if (LHS.isSigned())
453 Overflow = LHS.isMinSignedValue() && RHS.isAllOnesValue(); // MININT/-1
454 break;
Chris Lattner3b691152008-05-04 07:15:21 +0000455
Reid Spencer5f016e22007-07-11 17:01:13 +0000456 case tok::star:
457 Res = LHS * RHS;
458 if (LHS != 0 && RHS != 0)
459 Overflow = Res/RHS != LHS || Res/LHS != RHS;
460 break;
461 case tok::lessless: {
462 // Determine whether overflow is about to happen.
Chris Lattner701e5eb2007-09-04 02:45:27 +0000463 unsigned ShAmt = static_cast<unsigned>(RHS.getLimitedValue());
Reid Spencer5f016e22007-07-11 17:01:13 +0000464 if (ShAmt >= LHS.getBitWidth())
465 Overflow = true, ShAmt = LHS.getBitWidth()-1;
466 else if (LHS.isUnsigned())
467 Overflow = ShAmt > LHS.countLeadingZeros();
Dan Gohman376605b2008-02-13 22:09:49 +0000468 else if (LHS.isNonNegative())
Reid Spencer5f016e22007-07-11 17:01:13 +0000469 Overflow = ShAmt >= LHS.countLeadingZeros(); // Don't allow sign change.
470 else
471 Overflow = ShAmt >= LHS.countLeadingOnes();
472
473 Res = LHS << ShAmt;
474 break;
475 }
476 case tok::greatergreater: {
477 // Determine whether overflow is about to happen.
Chris Lattner701e5eb2007-09-04 02:45:27 +0000478 unsigned ShAmt = static_cast<unsigned>(RHS.getLimitedValue());
Reid Spencer5f016e22007-07-11 17:01:13 +0000479 if (ShAmt >= LHS.getBitWidth())
480 Overflow = true, ShAmt = LHS.getBitWidth()-1;
481 Res = LHS >> ShAmt;
482 break;
483 }
484 case tok::plus:
485 Res = LHS + RHS;
486 if (LHS.isUnsigned())
487 Overflow = Res.ult(LHS);
Dan Gohman376605b2008-02-13 22:09:49 +0000488 else if (LHS.isNonNegative() == RHS.isNonNegative() &&
489 Res.isNonNegative() != LHS.isNonNegative())
Reid Spencer5f016e22007-07-11 17:01:13 +0000490 Overflow = true; // Overflow for signed addition.
491 break;
492 case tok::minus:
493 Res = LHS - RHS;
494 if (LHS.isUnsigned())
495 Overflow = Res.ugt(LHS);
Dan Gohman376605b2008-02-13 22:09:49 +0000496 else if (LHS.isNonNegative() != RHS.isNonNegative() &&
497 Res.isNonNegative() != LHS.isNonNegative())
Reid Spencer5f016e22007-07-11 17:01:13 +0000498 Overflow = true; // Overflow for signed subtraction.
499 break;
500 case tok::lessequal:
501 Res = LHS <= RHS;
502 Res.setIsUnsigned(false); // C99 6.5.8p6, result is always int (signed)
503 break;
504 case tok::less:
505 Res = LHS < RHS;
506 Res.setIsUnsigned(false); // C99 6.5.8p6, result is always int (signed)
507 break;
508 case tok::greaterequal:
509 Res = LHS >= RHS;
510 Res.setIsUnsigned(false); // C99 6.5.8p6, result is always int (signed)
511 break;
512 case tok::greater:
513 Res = LHS > RHS;
514 Res.setIsUnsigned(false); // C99 6.5.8p6, result is always int (signed)
515 break;
516 case tok::exclaimequal:
517 Res = LHS != RHS;
518 Res.setIsUnsigned(false); // C99 6.5.9p3, result is always int (signed)
519 break;
520 case tok::equalequal:
521 Res = LHS == RHS;
522 Res.setIsUnsigned(false); // C99 6.5.9p3, result is always int (signed)
523 break;
524 case tok::amp:
525 Res = LHS & RHS;
526 break;
527 case tok::caret:
528 Res = LHS ^ RHS;
529 break;
530 case tok::pipe:
531 Res = LHS | RHS;
532 break;
533 case tok::ampamp:
534 Res = (LHS != 0 && RHS != 0);
535 Res.setIsUnsigned(false); // C99 6.5.13p3, result is always int (signed)
536 break;
537 case tok::pipepipe:
538 Res = (LHS != 0 || RHS != 0);
539 Res.setIsUnsigned(false); // C99 6.5.14p3, result is always int (signed)
540 break;
541 case tok::comma:
Chris Lattner91891562008-05-04 18:36:18 +0000542 // Comma is invalid in pp expressions in c89/c++ mode, but is valid in C99
543 // if not being evaluated.
544 if (!PP.getLangOptions().C99 || ValueLive)
545 PP.Diag(OpToken, diag::ext_pp_comma_expr);
Reid Spencer5f016e22007-07-11 17:01:13 +0000546 Res = RHS; // LHS = LHS,RHS -> RHS.
547 break;
548 case tok::question: {
549 // Parse the : part of the expression.
Chris Lattner22f6bbc2007-10-09 18:02:16 +0000550 if (PeekTok.isNot(tok::colon)) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000551 PP.Diag(OpToken, diag::err_pp_question_without_colon);
552 return true;
553 }
554 // Consume the :.
555 PP.LexNonComment(PeekTok);
556
557 // Evaluate the value after the :.
558 bool AfterColonLive = ValueLive && LHS == 0;
559 llvm::APSInt AfterColonVal(LHS.getBitWidth());
560 DefinedTracker DT;
561 if (EvaluateValue(AfterColonVal, PeekTok, DT, AfterColonLive, PP))
562 return true;
563
564 // Parse anything after the : RHS that has a higher precedence than ?.
565 if (EvaluateDirectiveSubExpr(AfterColonVal, ThisPrec+1,
566 PeekTok, AfterColonLive, PP))
567 return true;
568
569 // Now that we have the condition, the LHS and the RHS of the :, evaluate.
570 Res = LHS != 0 ? RHS : AfterColonVal;
571
572 // Usual arithmetic conversions (C99 6.3.1.8p1): result is unsigned if
573 // either operand is unsigned.
574 Res.setIsUnsigned(RHS.isUnsigned() | AfterColonVal.isUnsigned());
575
576 // Figure out the precedence of the token after the : part.
577 PeekPrec = getPrecedence(PeekTok.getKind());
578 break;
579 }
580 case tok::colon:
581 // Don't allow :'s to float around without being part of ?: exprs.
582 PP.Diag(OpToken, diag::err_pp_colon_without_question);
583 return true;
584 }
585
586 // If this operator is live and overflowed, report the issue.
587 if (Overflow && ValueLive)
588 PP.Diag(OpToken, diag::warn_pp_expr_overflow);
589
590 // Put the result back into 'LHS' for our next iteration.
591 LHS = Res;
592 }
593
594 return false;
595}
596
597/// EvaluateDirectiveExpression - Evaluate an integer constant expression that
598/// may occur after a #if or #elif directive. If the expression is equivalent
599/// to "!defined(X)" return X in IfNDefMacro.
600bool Preprocessor::
601EvaluateDirectiveExpression(IdentifierInfo *&IfNDefMacro) {
602 // Peek ahead one token.
Chris Lattnerd2177732007-07-20 16:59:19 +0000603 Token Tok;
Reid Spencer5f016e22007-07-11 17:01:13 +0000604 Lex(Tok);
605
606 // C99 6.10.1p3 - All expressions are evaluated as intmax_t or uintmax_t.
Chris Lattner98be4942008-03-05 18:54:05 +0000607 unsigned BitWidth = getTargetInfo().getIntMaxTWidth();
Ted Kremenek9c728dc2007-12-12 22:39:36 +0000608
Reid Spencer5f016e22007-07-11 17:01:13 +0000609 llvm::APSInt ResVal(BitWidth);
610 DefinedTracker DT;
611 if (EvaluateValue(ResVal, Tok, DT, true, *this)) {
612 // Parse error, skip the rest of the macro line.
Chris Lattner22f6bbc2007-10-09 18:02:16 +0000613 if (Tok.isNot(tok::eom))
Reid Spencer5f016e22007-07-11 17:01:13 +0000614 DiscardUntilEndOfDirective();
615 return false;
616 }
617
618 // If we are at the end of the expression after just parsing a value, there
619 // must be no (unparenthesized) binary operators involved, so we can exit
620 // directly.
Chris Lattner22f6bbc2007-10-09 18:02:16 +0000621 if (Tok.is(tok::eom)) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000622 // If the expression we parsed was of the form !defined(macro), return the
623 // macro in IfNDefMacro.
624 if (DT.State == DefinedTracker::NotDefinedMacro)
625 IfNDefMacro = DT.TheMacro;
626
627 return ResVal != 0;
628 }
629
630 // Otherwise, we must have a binary operator (e.g. "#if 1 < 2"), so parse the
631 // operator and the stuff after it.
632 if (EvaluateDirectiveSubExpr(ResVal, 1, Tok, true, *this)) {
633 // Parse error, skip the rest of the macro line.
Chris Lattner22f6bbc2007-10-09 18:02:16 +0000634 if (Tok.isNot(tok::eom))
Reid Spencer5f016e22007-07-11 17:01:13 +0000635 DiscardUntilEndOfDirective();
636 return false;
637 }
638
639 // If we aren't at the tok::eom token, something bad happened, like an extra
640 // ')' token.
Chris Lattner22f6bbc2007-10-09 18:02:16 +0000641 if (Tok.isNot(tok::eom)) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000642 Diag(Tok, diag::err_pp_expected_eol);
643 DiscardUntilEndOfDirective();
644 }
645
646 return ResVal != 0;
647}
648