blob: 2a4794de8353f14f1c72e5eafcf34fb12a8fde32 [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
Chris Lattner8ed30442008-05-05 06:45:50 +000029/// PPValue - Represents the value of a subexpression of a preprocessor
30/// conditional and the source range covered by it.
31class PPValue {
32 SourceRange Range;
33public:
34 llvm::APSInt Val;
35
36 // Default ctor - Construct an 'invalid' PPValue.
37 PPValue(unsigned BitWidth) : Val(BitWidth) {}
38
39 unsigned getBitWidth() const { return Val.getBitWidth(); }
40 bool isUnsigned() const { return Val.isUnsigned(); }
41
42 const SourceRange &getRange() const { return Range; }
43
44 void setRange(SourceLocation L) { Range.setBegin(L); Range.setEnd(L); }
45 void setRange(SourceLocation B, SourceLocation E) {
46 Range.setBegin(B); Range.setEnd(E);
47 }
48 void setBegin(SourceLocation L) { Range.setBegin(L); }
49 void setEnd(SourceLocation L) { Range.setEnd(L); }
50};
51
52static bool EvaluateDirectiveSubExpr(PPValue &LHS, unsigned MinPrec,
Chris Lattnerd2177732007-07-20 16:59:19 +000053 Token &PeekTok, bool ValueLive,
Reid Spencer5f016e22007-07-11 17:01:13 +000054 Preprocessor &PP);
55
56/// DefinedTracker - This struct is used while parsing expressions to keep track
57/// of whether !defined(X) has been seen.
58///
59/// With this simple scheme, we handle the basic forms:
60/// !defined(X) and !defined X
61/// but we also trivially handle (silly) stuff like:
62/// !!!defined(X) and +!defined(X) and !+!+!defined(X) and !(defined(X)).
63struct DefinedTracker {
64 /// Each time a Value is evaluated, it returns information about whether the
65 /// parsed value is of the form defined(X), !defined(X) or is something else.
66 enum TrackerState {
67 DefinedMacro, // defined(X)
68 NotDefinedMacro, // !defined(X)
69 Unknown // Something else.
70 } State;
71 /// TheMacro - When the state is DefinedMacro or NotDefinedMacro, this
72 /// indicates the macro that was checked.
73 IdentifierInfo *TheMacro;
74};
75
Reid Spencer5f016e22007-07-11 17:01:13 +000076/// EvaluateValue - Evaluate the token PeekTok (and any others needed) and
77/// return the computed value in Result. Return true if there was an error
78/// parsing. This function also returns information about the form of the
79/// expression in DT. See above for information on what DT means.
80///
81/// If ValueLive is false, then this value is being evaluated in a context where
82/// the result is not used. As such, avoid diagnostics that relate to
83/// evaluation.
Chris Lattner8ed30442008-05-05 06:45:50 +000084static bool EvaluateValue(PPValue &Result, Token &PeekTok, DefinedTracker &DT,
85 bool ValueLive, Preprocessor &PP) {
Reid Spencer5f016e22007-07-11 17:01:13 +000086 DT.State = DefinedTracker::Unknown;
87
88 // If this token's spelling is a pp-identifier, check to see if it is
89 // 'defined' or if it is a macro. Note that we check here because many
90 // keywords are pp-identifiers, so we can't check the kind.
91 if (IdentifierInfo *II = PeekTok.getIdentifierInfo()) {
92 // If this identifier isn't 'defined' and it wasn't macro expanded, it turns
93 // into a simple 0, unless it is the C++ keyword "true", in which case it
94 // turns into "1".
95 if (II->getPPKeywordID() != tok::pp_defined) {
Chris Lattner116a4b12008-01-23 17:19:46 +000096 PP.Diag(PeekTok, diag::warn_pp_undef_identifier, II->getName());
Chris Lattner8ed30442008-05-05 06:45:50 +000097 Result.Val = II->getTokenID() == tok::kw_true;
98 Result.Val.setIsUnsigned(false); // "0" is signed intmax_t 0.
99 Result.setRange(PeekTok.getLocation());
Reid Spencer5f016e22007-07-11 17:01:13 +0000100 PP.LexNonComment(PeekTok);
101 return false;
102 }
103
104 // Handle "defined X" and "defined(X)".
Chris Lattner8ed30442008-05-05 06:45:50 +0000105 Result.setBegin(PeekTok.getLocation());
Reid Spencer5f016e22007-07-11 17:01:13 +0000106
107 // Get the next token, don't expand it.
108 PP.LexUnexpandedToken(PeekTok);
109
110 // Two options, it can either be a pp-identifier or a (.
Chris Lattner8ed30442008-05-05 06:45:50 +0000111 SourceLocation LParenLoc;
Chris Lattner22f6bbc2007-10-09 18:02:16 +0000112 if (PeekTok.is(tok::l_paren)) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000113 // Found a paren, remember we saw it and skip it.
Chris Lattner8ed30442008-05-05 06:45:50 +0000114 LParenLoc = PeekTok.getLocation();
Reid Spencer5f016e22007-07-11 17:01:13 +0000115 PP.LexUnexpandedToken(PeekTok);
116 }
117
118 // If we don't have a pp-identifier now, this is an error.
119 if ((II = PeekTok.getIdentifierInfo()) == 0) {
120 PP.Diag(PeekTok, diag::err_pp_defined_requires_identifier);
121 return true;
122 }
123
124 // Otherwise, we got an identifier, is it defined to something?
Chris Lattner8ed30442008-05-05 06:45:50 +0000125 Result.Val = II->hasMacroDefinition();
126 Result.Val.setIsUnsigned(false); // Result is signed intmax_t.
Reid Spencer5f016e22007-07-11 17:01:13 +0000127
128 // If there is a macro, mark it used.
Chris Lattner8ed30442008-05-05 06:45:50 +0000129 if (Result.Val != 0 && ValueLive) {
Chris Lattnercc1a8752007-10-07 08:44:20 +0000130 MacroInfo *Macro = PP.getMacroInfo(II);
Chris Lattner0edde552007-10-07 08:04:56 +0000131 Macro->setIsUsed(true);
Reid Spencer5f016e22007-07-11 17:01:13 +0000132 }
133
134 // Consume identifier.
Chris Lattner8ed30442008-05-05 06:45:50 +0000135 Result.setEnd(PeekTok.getLocation());
Reid Spencer5f016e22007-07-11 17:01:13 +0000136 PP.LexNonComment(PeekTok);
137
138 // If we are in parens, ensure we have a trailing ).
Chris Lattner8ed30442008-05-05 06:45:50 +0000139 if (LParenLoc.isValid()) {
Chris Lattner22f6bbc2007-10-09 18:02:16 +0000140 if (PeekTok.isNot(tok::r_paren)) {
Chris Lattner8ed30442008-05-05 06:45:50 +0000141 PP.Diag(PeekTok.getLocation(), diag::err_pp_missing_rparen);
142 PP.Diag(LParenLoc, diag::err_matching, "(");
Reid Spencer5f016e22007-07-11 17:01:13 +0000143 return true;
144 }
145 // Consume the ).
Chris Lattner8ed30442008-05-05 06:45:50 +0000146 Result.setEnd(PeekTok.getLocation());
Reid Spencer5f016e22007-07-11 17:01:13 +0000147 PP.LexNonComment(PeekTok);
148 }
149
150 // Success, remember that we saw defined(X).
151 DT.State = DefinedTracker::DefinedMacro;
152 DT.TheMacro = II;
153 return false;
154 }
155
156 switch (PeekTok.getKind()) {
157 default: // Non-value token.
Chris Lattnerd98d9752008-04-13 20:38:43 +0000158 PP.Diag(PeekTok, diag::err_pp_expr_bad_token_start_expr);
Reid Spencer5f016e22007-07-11 17:01:13 +0000159 return true;
160 case tok::eom:
161 case tok::r_paren:
162 // If there is no expression, report and exit.
163 PP.Diag(PeekTok, diag::err_pp_expected_value_in_expr);
164 return true;
165 case tok::numeric_constant: {
166 llvm::SmallString<64> IntegerBuffer;
167 IntegerBuffer.resize(PeekTok.getLength());
168 const char *ThisTokBegin = &IntegerBuffer[0];
169 unsigned ActualLength = PP.getSpelling(PeekTok, ThisTokBegin);
170 NumericLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
171 PeekTok.getLocation(), PP);
172 if (Literal.hadError)
173 return true; // a diagnostic was already reported.
174
Chris Lattner6e400c22007-08-26 03:29:23 +0000175 if (Literal.isFloatingLiteral() || Literal.isImaginary) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000176 PP.Diag(PeekTok, diag::err_pp_illegal_floating_literal);
177 return true;
178 }
179 assert(Literal.isIntegerLiteral() && "Unknown ppnumber");
180
Neil Boothb9449512007-08-29 22:00:19 +0000181 // long long is a C99 feature.
182 if (!PP.getLangOptions().C99 && !PP.getLangOptions().CPlusPlus0x
Neil Booth79859c32007-08-29 22:13:52 +0000183 && Literal.isLongLong)
Neil Boothb9449512007-08-29 22:00:19 +0000184 PP.Diag(PeekTok, diag::ext_longlong);
185
Reid Spencer5f016e22007-07-11 17:01:13 +0000186 // Parse the integer literal into Result.
Chris Lattner8ed30442008-05-05 06:45:50 +0000187 if (Literal.GetIntegerValue(Result.Val)) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000188 // Overflow parsing integer literal.
189 if (ValueLive) PP.Diag(PeekTok, diag::warn_integer_too_large);
Chris Lattner8ed30442008-05-05 06:45:50 +0000190 Result.Val.setIsUnsigned(true);
Reid Spencer5f016e22007-07-11 17:01:13 +0000191 } else {
192 // Set the signedness of the result to match whether there was a U suffix
193 // or not.
Chris Lattner8ed30442008-05-05 06:45:50 +0000194 Result.Val.setIsUnsigned(Literal.isUnsigned);
Reid Spencer5f016e22007-07-11 17:01:13 +0000195
196 // Detect overflow based on whether the value is signed. If signed
197 // and if the value is too large, emit a warning "integer constant is so
198 // large that it is unsigned" e.g. on 12345678901234567890 where intmax_t
199 // is 64-bits.
Chris Lattner8ed30442008-05-05 06:45:50 +0000200 if (!Literal.isUnsigned && Result.Val.isNegative()) {
Chris Lattnerb081a352008-07-03 03:47:30 +0000201 // Don't warn for a hex literal: 0x8000..0 shouldn't warn.
202 if (ValueLive && Literal.getRadix() != 16)
Chris Lattner8ed30442008-05-05 06:45:50 +0000203 PP.Diag(PeekTok, diag::warn_integer_too_large_for_signed);
204 Result.Val.setIsUnsigned(true);
Reid Spencer5f016e22007-07-11 17:01:13 +0000205 }
206 }
207
208 // Consume the token.
Chris Lattner8ed30442008-05-05 06:45:50 +0000209 Result.setRange(PeekTok.getLocation());
Reid Spencer5f016e22007-07-11 17:01:13 +0000210 PP.LexNonComment(PeekTok);
211 return false;
212 }
213 case tok::char_constant: { // 'x'
214 llvm::SmallString<32> CharBuffer;
215 CharBuffer.resize(PeekTok.getLength());
216 const char *ThisTokBegin = &CharBuffer[0];
217 unsigned ActualLength = PP.getSpelling(PeekTok, ThisTokBegin);
218 CharLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
219 PeekTok.getLocation(), PP);
220 if (Literal.hadError())
221 return true; // A diagnostic was already emitted.
222
223 // Character literals are always int or wchar_t, expand to intmax_t.
224 TargetInfo &TI = PP.getTargetInfo();
Chris Lattner98be4942008-03-05 18:54:05 +0000225 unsigned NumBits = TI.getCharWidth(Literal.isWide());
Reid Spencer5f016e22007-07-11 17:01:13 +0000226
227 // Set the width.
228 llvm::APSInt Val(NumBits);
229 // Set the value.
230 Val = Literal.getValue();
231 // Set the signedness.
Chris Lattner98be4942008-03-05 18:54:05 +0000232 Val.setIsUnsigned(!TI.isCharSigned());
Reid Spencer5f016e22007-07-11 17:01:13 +0000233
Chris Lattner8ed30442008-05-05 06:45:50 +0000234 if (Result.Val.getBitWidth() > Val.getBitWidth()) {
235 Result.Val = Val.extend(Result.Val.getBitWidth());
Reid Spencer5f016e22007-07-11 17:01:13 +0000236 } else {
Chris Lattner8ed30442008-05-05 06:45:50 +0000237 assert(Result.Val.getBitWidth() == Val.getBitWidth() &&
Reid Spencer5f016e22007-07-11 17:01:13 +0000238 "intmax_t smaller than char/wchar_t?");
Chris Lattner8ed30442008-05-05 06:45:50 +0000239 Result.Val = Val;
Reid Spencer5f016e22007-07-11 17:01:13 +0000240 }
241
242 // Consume the token.
Chris Lattner8ed30442008-05-05 06:45:50 +0000243 Result.setRange(PeekTok.getLocation());
Reid Spencer5f016e22007-07-11 17:01:13 +0000244 PP.LexNonComment(PeekTok);
245 return false;
246 }
Chris Lattner8ed30442008-05-05 06:45:50 +0000247 case tok::l_paren: {
248 SourceLocation Start = PeekTok.getLocation();
Reid Spencer5f016e22007-07-11 17:01:13 +0000249 PP.LexNonComment(PeekTok); // Eat the (.
250 // Parse the value and if there are any binary operators involved, parse
251 // them.
252 if (EvaluateValue(Result, PeekTok, DT, ValueLive, PP)) return true;
253
254 // If this is a silly value like (X), which doesn't need parens, check for
255 // !(defined X).
Chris Lattner22f6bbc2007-10-09 18:02:16 +0000256 if (PeekTok.is(tok::r_paren)) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000257 // Just use DT unmodified as our result.
258 } else {
Chris Lattner8ed30442008-05-05 06:45:50 +0000259 // Otherwise, we have something like (x+y), and we consumed '(x'.
Reid Spencer5f016e22007-07-11 17:01:13 +0000260 if (EvaluateDirectiveSubExpr(Result, 1, PeekTok, ValueLive, PP))
261 return true;
262
Chris Lattner22f6bbc2007-10-09 18:02:16 +0000263 if (PeekTok.isNot(tok::r_paren)) {
Chris Lattner8ed30442008-05-05 06:45:50 +0000264 PP.Diag(PeekTok.getLocation(), diag::err_pp_expected_rparen,
265 Result.getRange());
266 PP.Diag(Start, diag::err_matching, "(");
Reid Spencer5f016e22007-07-11 17:01:13 +0000267 return true;
268 }
269 DT.State = DefinedTracker::Unknown;
270 }
Chris Lattner8ed30442008-05-05 06:45:50 +0000271 Result.setRange(Start, PeekTok.getLocation());
Reid Spencer5f016e22007-07-11 17:01:13 +0000272 PP.LexNonComment(PeekTok); // Eat the ).
273 return false;
Chris Lattner8ed30442008-05-05 06:45:50 +0000274 }
275 case tok::plus: {
276 SourceLocation Start = PeekTok.getLocation();
Reid Spencer5f016e22007-07-11 17:01:13 +0000277 // Unary plus doesn't modify the value.
278 PP.LexNonComment(PeekTok);
Chris Lattner8ed30442008-05-05 06:45:50 +0000279 if (EvaluateValue(Result, PeekTok, DT, ValueLive, PP)) return true;
280 Result.setBegin(Start);
281 return false;
282 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000283 case tok::minus: {
284 SourceLocation Loc = PeekTok.getLocation();
285 PP.LexNonComment(PeekTok);
286 if (EvaluateValue(Result, PeekTok, DT, ValueLive, PP)) return true;
Chris Lattner8ed30442008-05-05 06:45:50 +0000287 Result.setBegin(Loc);
288
Reid Spencer5f016e22007-07-11 17:01:13 +0000289 // C99 6.5.3.3p3: The sign of the result matches the sign of the operand.
Chris Lattner8ed30442008-05-05 06:45:50 +0000290 Result.Val = -Result.Val;
Reid Spencer5f016e22007-07-11 17:01:13 +0000291
Chris Lattnerb081a352008-07-03 03:47:30 +0000292 // -MININT is the only thing that overflows. Unsigned never overflows.
293 bool Overflow = !Result.isUnsigned() && Result.Val.isMinSignedValue();
Reid Spencer5f016e22007-07-11 17:01:13 +0000294
295 // If this operator is live and overflowed, report the issue.
296 if (Overflow && ValueLive)
Chris Lattner8ed30442008-05-05 06:45:50 +0000297 PP.Diag(Loc, diag::warn_pp_expr_overflow, Result.getRange());
Reid Spencer5f016e22007-07-11 17:01:13 +0000298
299 DT.State = DefinedTracker::Unknown;
300 return false;
301 }
302
Chris Lattner8ed30442008-05-05 06:45:50 +0000303 case tok::tilde: {
304 SourceLocation Start = PeekTok.getLocation();
Reid Spencer5f016e22007-07-11 17:01:13 +0000305 PP.LexNonComment(PeekTok);
306 if (EvaluateValue(Result, PeekTok, DT, ValueLive, PP)) return true;
Chris Lattner8ed30442008-05-05 06:45:50 +0000307 Result.setBegin(Start);
308
Reid Spencer5f016e22007-07-11 17:01:13 +0000309 // C99 6.5.3.3p4: The sign of the result matches the sign of the operand.
Chris Lattner8ed30442008-05-05 06:45:50 +0000310 Result.Val = ~Result.Val;
Reid Spencer5f016e22007-07-11 17:01:13 +0000311 DT.State = DefinedTracker::Unknown;
312 return false;
Chris Lattner8ed30442008-05-05 06:45:50 +0000313 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000314
Chris Lattner8ed30442008-05-05 06:45:50 +0000315 case tok::exclaim: {
316 SourceLocation Start = PeekTok.getLocation();
Reid Spencer5f016e22007-07-11 17:01:13 +0000317 PP.LexNonComment(PeekTok);
318 if (EvaluateValue(Result, PeekTok, DT, ValueLive, PP)) return true;
Chris Lattner8ed30442008-05-05 06:45:50 +0000319 Result.setBegin(Start);
320 Result.Val = !Result.Val;
Reid Spencer5f016e22007-07-11 17:01:13 +0000321 // C99 6.5.3.3p5: The sign of the result is 'int', aka it is signed.
Chris Lattner8ed30442008-05-05 06:45:50 +0000322 Result.Val.setIsUnsigned(false);
Reid Spencer5f016e22007-07-11 17:01:13 +0000323
324 if (DT.State == DefinedTracker::DefinedMacro)
325 DT.State = DefinedTracker::NotDefinedMacro;
326 else if (DT.State == DefinedTracker::NotDefinedMacro)
327 DT.State = DefinedTracker::DefinedMacro;
328 return false;
Chris Lattner8ed30442008-05-05 06:45:50 +0000329 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000330
331 // FIXME: Handle #assert
332 }
333}
334
335
336
337/// getPrecedence - Return the precedence of the specified binary operator
338/// token. This returns:
339/// ~0 - Invalid token.
Chris Lattner9e66ba62008-05-05 04:10:51 +0000340/// 14 -> 3 - various operators.
341/// 0 - 'eom' or ')'
Reid Spencer5f016e22007-07-11 17:01:13 +0000342static unsigned getPrecedence(tok::TokenKind Kind) {
343 switch (Kind) {
344 default: return ~0U;
345 case tok::percent:
346 case tok::slash:
347 case tok::star: return 14;
348 case tok::plus:
349 case tok::minus: return 13;
350 case tok::lessless:
351 case tok::greatergreater: return 12;
352 case tok::lessequal:
353 case tok::less:
354 case tok::greaterequal:
355 case tok::greater: return 11;
356 case tok::exclaimequal:
357 case tok::equalequal: return 10;
358 case tok::amp: return 9;
359 case tok::caret: return 8;
360 case tok::pipe: return 7;
361 case tok::ampamp: return 6;
362 case tok::pipepipe: return 5;
Chris Lattner98ed49f2008-05-05 20:07:41 +0000363 case tok::question: return 4;
364 case tok::comma: return 3;
Chris Lattner91891562008-05-04 18:36:18 +0000365 case tok::colon: return 2;
Reid Spencer5f016e22007-07-11 17:01:13 +0000366 case tok::r_paren: return 0; // Lowest priority, end of expr.
367 case tok::eom: return 0; // Lowest priority, end of macro.
368 }
369}
370
371
372/// EvaluateDirectiveSubExpr - Evaluate the subexpression whose first token is
Chris Lattner8ed30442008-05-05 06:45:50 +0000373/// PeekTok, and whose precedence is PeekPrec. This returns the result in LHS.
Reid Spencer5f016e22007-07-11 17:01:13 +0000374///
375/// If ValueLive is false, then this value is being evaluated in a context where
376/// the result is not used. As such, avoid diagnostics that relate to
Chris Lattner8ed30442008-05-05 06:45:50 +0000377/// evaluation, such as division by zero warnings.
378static bool EvaluateDirectiveSubExpr(PPValue &LHS, unsigned MinPrec,
Chris Lattnerd2177732007-07-20 16:59:19 +0000379 Token &PeekTok, bool ValueLive,
Reid Spencer5f016e22007-07-11 17:01:13 +0000380 Preprocessor &PP) {
381 unsigned PeekPrec = getPrecedence(PeekTok.getKind());
382 // If this token isn't valid, report the error.
383 if (PeekPrec == ~0U) {
Chris Lattner8ed30442008-05-05 06:45:50 +0000384 PP.Diag(PeekTok.getLocation(), diag::err_pp_expr_bad_token_binop,
385 LHS.getRange());
Reid Spencer5f016e22007-07-11 17:01:13 +0000386 return true;
387 }
388
389 while (1) {
390 // If this token has a lower precedence than we are allowed to parse, return
391 // it so that higher levels of the recursion can parse it.
392 if (PeekPrec < MinPrec)
393 return false;
394
395 tok::TokenKind Operator = PeekTok.getKind();
396
397 // If this is a short-circuiting operator, see if the RHS of the operator is
398 // dead. Note that this cannot just clobber ValueLive. Consider
399 // "0 && 1 ? 4 : 1 / 0", which is parsed as "(0 && 1) ? 4 : (1 / 0)". In
400 // this example, the RHS of the && being dead does not make the rest of the
401 // expr dead.
402 bool RHSIsLive;
Chris Lattner8ed30442008-05-05 06:45:50 +0000403 if (Operator == tok::ampamp && LHS.Val == 0)
Reid Spencer5f016e22007-07-11 17:01:13 +0000404 RHSIsLive = false; // RHS of "0 && x" is dead.
Chris Lattner8ed30442008-05-05 06:45:50 +0000405 else if (Operator == tok::pipepipe && LHS.Val != 0)
Reid Spencer5f016e22007-07-11 17:01:13 +0000406 RHSIsLive = false; // RHS of "1 || x" is dead.
Chris Lattner8ed30442008-05-05 06:45:50 +0000407 else if (Operator == tok::question && LHS.Val == 0)
Reid Spencer5f016e22007-07-11 17:01:13 +0000408 RHSIsLive = false; // RHS (x) of "0 ? x : y" is dead.
409 else
410 RHSIsLive = ValueLive;
411
Chris Lattner8ed30442008-05-05 06:45:50 +0000412 // Consume the operator, remembering the operator's location for reporting.
413 SourceLocation OpLoc = PeekTok.getLocation();
Reid Spencer5f016e22007-07-11 17:01:13 +0000414 PP.LexNonComment(PeekTok);
415
Chris Lattner8ed30442008-05-05 06:45:50 +0000416 PPValue RHS(LHS.getBitWidth());
Reid Spencer5f016e22007-07-11 17:01:13 +0000417 // Parse the RHS of the operator.
418 DefinedTracker DT;
419 if (EvaluateValue(RHS, PeekTok, DT, RHSIsLive, PP)) return true;
420
421 // Remember the precedence of this operator and get the precedence of the
422 // operator immediately to the right of the RHS.
423 unsigned ThisPrec = PeekPrec;
424 PeekPrec = getPrecedence(PeekTok.getKind());
425
426 // If this token isn't valid, report the error.
427 if (PeekPrec == ~0U) {
Chris Lattner8ed30442008-05-05 06:45:50 +0000428 PP.Diag(PeekTok.getLocation(), diag::err_pp_expr_bad_token_binop,
429 RHS.getRange());
Reid Spencer5f016e22007-07-11 17:01:13 +0000430 return true;
431 }
432
Chris Lattner98ed49f2008-05-05 20:07:41 +0000433 // Decide whether to include the next binop in this subexpression. For
434 // example, when parsing x+y*z and looking at '*', we want to recursively
Chris Lattner44cbbb02008-05-05 20:09:27 +0000435 // handle y*z as a single subexpression. We do this because the precedence
436 // of * is higher than that of +. The only strange case we have to handle
437 // here is for the ?: operator, where the precedence is actually lower than
438 // the LHS of the '?'. The grammar rule is:
Chris Lattner98ed49f2008-05-05 20:07:41 +0000439 //
440 // conditional-expression ::=
441 // logical-OR-expression ? expression : conditional-expression
442 // where 'expression' is actually comma-expression.
443 unsigned RHSPrec;
444 if (Operator == tok::question)
445 // The RHS of "?" should be maximally consumed as an expression.
446 RHSPrec = getPrecedence(tok::comma);
447 else // All others should munch while higher precedence.
448 RHSPrec = ThisPrec+1;
Reid Spencer5f016e22007-07-11 17:01:13 +0000449
Chris Lattner98ed49f2008-05-05 20:07:41 +0000450 if (PeekPrec >= RHSPrec) {
451 if (EvaluateDirectiveSubExpr(RHS, RHSPrec, PeekTok, RHSIsLive, PP))
Reid Spencer5f016e22007-07-11 17:01:13 +0000452 return true;
453 PeekPrec = getPrecedence(PeekTok.getKind());
454 }
455 assert(PeekPrec <= ThisPrec && "Recursion didn't work!");
456
457 // Usual arithmetic conversions (C99 6.3.1.8p1): result is unsigned if
Chris Lattner019ef7e2008-05-04 23:46:17 +0000458 // either operand is unsigned.
Reid Spencer5f016e22007-07-11 17:01:13 +0000459 llvm::APSInt Res(LHS.getBitWidth());
Chris Lattner019ef7e2008-05-04 23:46:17 +0000460 switch (Operator) {
461 case tok::question: // No UAC for x and y in "x ? y : z".
462 case tok::lessless: // Shift amount doesn't UAC with shift value.
463 case tok::greatergreater: // Shift amount doesn't UAC with shift value.
464 case tok::comma: // Comma operands are not subject to UACs.
465 case tok::pipepipe: // Logical || does not do UACs.
466 case tok::ampamp: // Logical && does not do UACs.
467 break; // No UAC
468 default:
Reid Spencer5f016e22007-07-11 17:01:13 +0000469 Res.setIsUnsigned(LHS.isUnsigned()|RHS.isUnsigned());
470 // If this just promoted something from signed to unsigned, and if the
471 // value was negative, warn about it.
472 if (ValueLive && Res.isUnsigned()) {
Chris Lattner8ed30442008-05-05 06:45:50 +0000473 if (!LHS.isUnsigned() && LHS.Val.isNegative())
474 PP.Diag(OpLoc, diag::warn_pp_convert_lhs_to_positive,
475 LHS.Val.toStringSigned() + " to "+LHS.Val.toStringUnsigned(),
476 LHS.getRange(), RHS.getRange());
477 if (!RHS.isUnsigned() && RHS.Val.isNegative())
478 PP.Diag(OpLoc, diag::warn_pp_convert_rhs_to_positive,
479 RHS.Val.toStringSigned() + " to "+RHS.Val.toStringUnsigned(),
480 LHS.getRange(), RHS.getRange());
Reid Spencer5f016e22007-07-11 17:01:13 +0000481 }
Chris Lattner8ed30442008-05-05 06:45:50 +0000482 LHS.Val.setIsUnsigned(Res.isUnsigned());
483 RHS.Val.setIsUnsigned(Res.isUnsigned());
Reid Spencer5f016e22007-07-11 17:01:13 +0000484 }
485
486 // FIXME: All of these should detect and report overflow??
487 bool Overflow = false;
488 switch (Operator) {
489 default: assert(0 && "Unknown operator token!");
490 case tok::percent:
Chris Lattner8ed30442008-05-05 06:45:50 +0000491 if (RHS.Val != 0)
492 Res = LHS.Val % RHS.Val;
493 else if (ValueLive) {
494 PP.Diag(OpLoc, diag::err_pp_remainder_by_zero, LHS.getRange(),
495 RHS.getRange());
496 return true;
Reid Spencer5f016e22007-07-11 17:01:13 +0000497 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000498 break;
499 case tok::slash:
Chris Lattner8ed30442008-05-05 06:45:50 +0000500 if (RHS.Val != 0) {
501 Res = LHS.Val / RHS.Val;
502 if (LHS.Val.isSigned()) // MININT/-1 --> overflow.
503 Overflow = LHS.Val.isMinSignedValue() && RHS.Val.isAllOnesValue();
504 } else if (ValueLive) {
505 PP.Diag(OpLoc, diag::err_pp_division_by_zero, LHS.getRange(),
506 RHS.getRange());
507 return true;
Reid Spencer5f016e22007-07-11 17:01:13 +0000508 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000509 break;
Chris Lattner3b691152008-05-04 07:15:21 +0000510
Reid Spencer5f016e22007-07-11 17:01:13 +0000511 case tok::star:
Chris Lattner8ed30442008-05-05 06:45:50 +0000512 Res = LHS.Val * RHS.Val;
513 if (LHS.Val != 0 && RHS.Val != 0)
514 Overflow = Res/RHS.Val != LHS.Val || Res/LHS.Val != RHS.Val;
Reid Spencer5f016e22007-07-11 17:01:13 +0000515 break;
516 case tok::lessless: {
517 // Determine whether overflow is about to happen.
Chris Lattner8ed30442008-05-05 06:45:50 +0000518 unsigned ShAmt = static_cast<unsigned>(RHS.Val.getLimitedValue());
519 if (ShAmt >= LHS.Val.getBitWidth())
520 Overflow = true, ShAmt = LHS.Val.getBitWidth()-1;
Reid Spencer5f016e22007-07-11 17:01:13 +0000521 else if (LHS.isUnsigned())
Chris Lattner8ed30442008-05-05 06:45:50 +0000522 Overflow = ShAmt > LHS.Val.countLeadingZeros();
523 else if (LHS.Val.isNonNegative()) // Don't allow sign change.
524 Overflow = ShAmt >= LHS.Val.countLeadingZeros();
Reid Spencer5f016e22007-07-11 17:01:13 +0000525 else
Chris Lattner8ed30442008-05-05 06:45:50 +0000526 Overflow = ShAmt >= LHS.Val.countLeadingOnes();
Reid Spencer5f016e22007-07-11 17:01:13 +0000527
Chris Lattner8ed30442008-05-05 06:45:50 +0000528 Res = LHS.Val << ShAmt;
Reid Spencer5f016e22007-07-11 17:01:13 +0000529 break;
530 }
531 case tok::greatergreater: {
532 // Determine whether overflow is about to happen.
Chris Lattner8ed30442008-05-05 06:45:50 +0000533 unsigned ShAmt = static_cast<unsigned>(RHS.Val.getLimitedValue());
Reid Spencer5f016e22007-07-11 17:01:13 +0000534 if (ShAmt >= LHS.getBitWidth())
535 Overflow = true, ShAmt = LHS.getBitWidth()-1;
Chris Lattner8ed30442008-05-05 06:45:50 +0000536 Res = LHS.Val >> ShAmt;
Reid Spencer5f016e22007-07-11 17:01:13 +0000537 break;
538 }
539 case tok::plus:
Chris Lattner8ed30442008-05-05 06:45:50 +0000540 Res = LHS.Val + RHS.Val;
Reid Spencer5f016e22007-07-11 17:01:13 +0000541 if (LHS.isUnsigned())
Chris Lattner8ed30442008-05-05 06:45:50 +0000542 Overflow = Res.ult(LHS.Val);
543 else if (LHS.Val.isNonNegative() == RHS.Val.isNonNegative() &&
544 Res.isNonNegative() != LHS.Val.isNonNegative())
Reid Spencer5f016e22007-07-11 17:01:13 +0000545 Overflow = true; // Overflow for signed addition.
546 break;
547 case tok::minus:
Chris Lattner8ed30442008-05-05 06:45:50 +0000548 Res = LHS.Val - RHS.Val;
Reid Spencer5f016e22007-07-11 17:01:13 +0000549 if (LHS.isUnsigned())
Chris Lattner8ed30442008-05-05 06:45:50 +0000550 Overflow = Res.ugt(LHS.Val);
551 else if (LHS.Val.isNonNegative() != RHS.Val.isNonNegative() &&
552 Res.isNonNegative() != LHS.Val.isNonNegative())
Reid Spencer5f016e22007-07-11 17:01:13 +0000553 Overflow = true; // Overflow for signed subtraction.
554 break;
555 case tok::lessequal:
Chris Lattner8ed30442008-05-05 06:45:50 +0000556 Res = LHS.Val <= RHS.Val;
Reid Spencer5f016e22007-07-11 17:01:13 +0000557 Res.setIsUnsigned(false); // C99 6.5.8p6, result is always int (signed)
558 break;
559 case tok::less:
Chris Lattner8ed30442008-05-05 06:45:50 +0000560 Res = LHS.Val < RHS.Val;
Reid Spencer5f016e22007-07-11 17:01:13 +0000561 Res.setIsUnsigned(false); // C99 6.5.8p6, result is always int (signed)
562 break;
563 case tok::greaterequal:
Chris Lattner8ed30442008-05-05 06:45:50 +0000564 Res = LHS.Val >= RHS.Val;
Reid Spencer5f016e22007-07-11 17:01:13 +0000565 Res.setIsUnsigned(false); // C99 6.5.8p6, result is always int (signed)
566 break;
567 case tok::greater:
Chris Lattner8ed30442008-05-05 06:45:50 +0000568 Res = LHS.Val > RHS.Val;
Reid Spencer5f016e22007-07-11 17:01:13 +0000569 Res.setIsUnsigned(false); // C99 6.5.8p6, result is always int (signed)
570 break;
571 case tok::exclaimequal:
Chris Lattner8ed30442008-05-05 06:45:50 +0000572 Res = LHS.Val != RHS.Val;
Reid Spencer5f016e22007-07-11 17:01:13 +0000573 Res.setIsUnsigned(false); // C99 6.5.9p3, result is always int (signed)
574 break;
575 case tok::equalequal:
Chris Lattner8ed30442008-05-05 06:45:50 +0000576 Res = LHS.Val == RHS.Val;
Reid Spencer5f016e22007-07-11 17:01:13 +0000577 Res.setIsUnsigned(false); // C99 6.5.9p3, result is always int (signed)
578 break;
579 case tok::amp:
Chris Lattner8ed30442008-05-05 06:45:50 +0000580 Res = LHS.Val & RHS.Val;
Reid Spencer5f016e22007-07-11 17:01:13 +0000581 break;
582 case tok::caret:
Chris Lattner8ed30442008-05-05 06:45:50 +0000583 Res = LHS.Val ^ RHS.Val;
Reid Spencer5f016e22007-07-11 17:01:13 +0000584 break;
585 case tok::pipe:
Chris Lattner8ed30442008-05-05 06:45:50 +0000586 Res = LHS.Val | RHS.Val;
Reid Spencer5f016e22007-07-11 17:01:13 +0000587 break;
588 case tok::ampamp:
Chris Lattner8ed30442008-05-05 06:45:50 +0000589 Res = (LHS.Val != 0 && RHS.Val != 0);
Reid Spencer5f016e22007-07-11 17:01:13 +0000590 Res.setIsUnsigned(false); // C99 6.5.13p3, result is always int (signed)
591 break;
592 case tok::pipepipe:
Chris Lattner8ed30442008-05-05 06:45:50 +0000593 Res = (LHS.Val != 0 || RHS.Val != 0);
Reid Spencer5f016e22007-07-11 17:01:13 +0000594 Res.setIsUnsigned(false); // C99 6.5.14p3, result is always int (signed)
595 break;
596 case tok::comma:
Chris Lattner91891562008-05-04 18:36:18 +0000597 // Comma is invalid in pp expressions in c89/c++ mode, but is valid in C99
598 // if not being evaluated.
599 if (!PP.getLangOptions().C99 || ValueLive)
Chris Lattner8ed30442008-05-05 06:45:50 +0000600 PP.Diag(OpLoc, diag::ext_pp_comma_expr, LHS.getRange(), RHS.getRange());
601 Res = RHS.Val; // LHS = LHS,RHS -> RHS.
Reid Spencer5f016e22007-07-11 17:01:13 +0000602 break;
603 case tok::question: {
604 // Parse the : part of the expression.
Chris Lattner22f6bbc2007-10-09 18:02:16 +0000605 if (PeekTok.isNot(tok::colon)) {
Chris Lattner8ed30442008-05-05 06:45:50 +0000606 PP.Diag(PeekTok.getLocation(), diag::err_expected_colon,
607 LHS.getRange(), RHS.getRange());
608 PP.Diag(OpLoc, diag::err_matching, "?");
Reid Spencer5f016e22007-07-11 17:01:13 +0000609 return true;
610 }
611 // Consume the :.
612 PP.LexNonComment(PeekTok);
613
614 // Evaluate the value after the :.
Chris Lattner8ed30442008-05-05 06:45:50 +0000615 bool AfterColonLive = ValueLive && LHS.Val == 0;
616 PPValue AfterColonVal(LHS.getBitWidth());
Reid Spencer5f016e22007-07-11 17:01:13 +0000617 DefinedTracker DT;
618 if (EvaluateValue(AfterColonVal, PeekTok, DT, AfterColonLive, PP))
619 return true;
620
Chris Lattner44cbbb02008-05-05 20:09:27 +0000621 // Parse anything after the : with the same precedence as ?. We allow
622 // things of equal precedence because ?: is right associative.
Chris Lattner98ed49f2008-05-05 20:07:41 +0000623 if (EvaluateDirectiveSubExpr(AfterColonVal, ThisPrec,
Reid Spencer5f016e22007-07-11 17:01:13 +0000624 PeekTok, AfterColonLive, PP))
625 return true;
626
627 // Now that we have the condition, the LHS and the RHS of the :, evaluate.
Chris Lattner8ed30442008-05-05 06:45:50 +0000628 Res = LHS.Val != 0 ? RHS.Val : AfterColonVal.Val;
629 RHS.setEnd(AfterColonVal.getRange().getEnd());
Reid Spencer5f016e22007-07-11 17:01:13 +0000630
631 // Usual arithmetic conversions (C99 6.3.1.8p1): result is unsigned if
632 // either operand is unsigned.
633 Res.setIsUnsigned(RHS.isUnsigned() | AfterColonVal.isUnsigned());
634
635 // Figure out the precedence of the token after the : part.
636 PeekPrec = getPrecedence(PeekTok.getKind());
637 break;
638 }
639 case tok::colon:
640 // Don't allow :'s to float around without being part of ?: exprs.
Chris Lattner8ed30442008-05-05 06:45:50 +0000641 PP.Diag(OpLoc, diag::err_pp_colon_without_question, LHS.getRange(),
642 RHS.getRange());
Reid Spencer5f016e22007-07-11 17:01:13 +0000643 return true;
644 }
645
646 // If this operator is live and overflowed, report the issue.
647 if (Overflow && ValueLive)
Chris Lattner8ed30442008-05-05 06:45:50 +0000648 PP.Diag(OpLoc, diag::warn_pp_expr_overflow,
649 LHS.getRange(), RHS.getRange());
Reid Spencer5f016e22007-07-11 17:01:13 +0000650
651 // Put the result back into 'LHS' for our next iteration.
Chris Lattner8ed30442008-05-05 06:45:50 +0000652 LHS.Val = Res;
653 LHS.setEnd(RHS.getRange().getEnd());
Reid Spencer5f016e22007-07-11 17:01:13 +0000654 }
655
656 return false;
657}
658
659/// EvaluateDirectiveExpression - Evaluate an integer constant expression that
660/// may occur after a #if or #elif directive. If the expression is equivalent
661/// to "!defined(X)" return X in IfNDefMacro.
662bool Preprocessor::
663EvaluateDirectiveExpression(IdentifierInfo *&IfNDefMacro) {
664 // Peek ahead one token.
Chris Lattnerd2177732007-07-20 16:59:19 +0000665 Token Tok;
Reid Spencer5f016e22007-07-11 17:01:13 +0000666 Lex(Tok);
667
668 // C99 6.10.1p3 - All expressions are evaluated as intmax_t or uintmax_t.
Chris Lattner98be4942008-03-05 18:54:05 +0000669 unsigned BitWidth = getTargetInfo().getIntMaxTWidth();
Ted Kremenek9c728dc2007-12-12 22:39:36 +0000670
Chris Lattner8ed30442008-05-05 06:45:50 +0000671 PPValue ResVal(BitWidth);
Reid Spencer5f016e22007-07-11 17:01:13 +0000672 DefinedTracker DT;
673 if (EvaluateValue(ResVal, Tok, DT, true, *this)) {
674 // Parse error, skip the rest of the macro line.
Chris Lattner22f6bbc2007-10-09 18:02:16 +0000675 if (Tok.isNot(tok::eom))
Reid Spencer5f016e22007-07-11 17:01:13 +0000676 DiscardUntilEndOfDirective();
677 return false;
678 }
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.
Chris Lattner22f6bbc2007-10-09 18:02:16 +0000683 if (Tok.is(tok::eom)) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000684 // 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
Chris Lattner8ed30442008-05-05 06:45:50 +0000689 return ResVal.Val != 0;
Reid Spencer5f016e22007-07-11 17:01:13 +0000690 }
691
692 // Otherwise, we must have a binary operator (e.g. "#if 1 < 2"), so parse the
693 // operator and the stuff after it.
Chris Lattner98ed49f2008-05-05 20:07:41 +0000694 if (EvaluateDirectiveSubExpr(ResVal, getPrecedence(tok::question),
695 Tok, true, *this)) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000696 // Parse error, skip the rest of the macro line.
Chris Lattner22f6bbc2007-10-09 18:02:16 +0000697 if (Tok.isNot(tok::eom))
Reid Spencer5f016e22007-07-11 17:01:13 +0000698 DiscardUntilEndOfDirective();
699 return false;
700 }
701
702 // If we aren't at the tok::eom token, something bad happened, like an extra
703 // ')' token.
Chris Lattner22f6bbc2007-10-09 18:02:16 +0000704 if (Tok.isNot(tok::eom)) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000705 Diag(Tok, diag::err_pp_expected_eol);
706 DiscardUntilEndOfDirective();
707 }
708
Chris Lattner8ed30442008-05-05 06:45:50 +0000709 return ResVal.Val != 0;
Reid Spencer5f016e22007-07-11 17:01:13 +0000710}
711