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