1193326Sed//===--- PPExpressions.cpp - Preprocessor Expression Evaluation -----------===//
2193326Sed//
3193326Sed//                     The LLVM Compiler Infrastructure
4193326Sed//
5193326Sed// This file is distributed under the University of Illinois Open Source
6193326Sed// License. See LICENSE.TXT for details.
7193326Sed//
8193326Sed//===----------------------------------------------------------------------===//
9193326Sed//
10193326Sed// This file implements the Preprocessor::EvaluateDirectiveExpression method,
11193326Sed// which parses and evaluates integer constant expressions for #if directives.
12193326Sed//
13193326Sed//===----------------------------------------------------------------------===//
14193326Sed//
15193326Sed// FIXME: implement testing for #assert's.
16193326Sed//
17193326Sed//===----------------------------------------------------------------------===//
18193326Sed
19193326Sed#include "clang/Lex/Preprocessor.h"
20249423Sdim#include "clang/Basic/TargetInfo.h"
21212904Sdim#include "clang/Lex/CodeCompletionHandler.h"
22193326Sed#include "clang/Lex/LexDiagnostic.h"
23249423Sdim#include "clang/Lex/LiteralSupport.h"
24249423Sdim#include "clang/Lex/MacroInfo.h"
25193326Sed#include "llvm/ADT/APSInt.h"
26226633Sdim#include "llvm/Support/ErrorHandling.h"
27249423Sdim#include "llvm/Support/SaveAndRestore.h"
28193326Sedusing namespace clang;
29193326Sed
30212904Sdimnamespace {
31212904Sdim
32193326Sed/// PPValue - Represents the value of a subexpression of a preprocessor
33193326Sed/// conditional and the source range covered by it.
34193326Sedclass PPValue {
35193326Sed  SourceRange Range;
36193326Sedpublic:
37193326Sed  llvm::APSInt Val;
38198092Srdivacky
39193326Sed  // Default ctor - Construct an 'invalid' PPValue.
40193326Sed  PPValue(unsigned BitWidth) : Val(BitWidth) {}
41198092Srdivacky
42193326Sed  unsigned getBitWidth() const { return Val.getBitWidth(); }
43193326Sed  bool isUnsigned() const { return Val.isUnsigned(); }
44198092Srdivacky
45193326Sed  const SourceRange &getRange() const { return Range; }
46198092Srdivacky
47193326Sed  void setRange(SourceLocation L) { Range.setBegin(L); Range.setEnd(L); }
48193326Sed  void setRange(SourceLocation B, SourceLocation E) {
49198092Srdivacky    Range.setBegin(B); Range.setEnd(E);
50193326Sed  }
51193326Sed  void setBegin(SourceLocation L) { Range.setBegin(L); }
52193326Sed  void setEnd(SourceLocation L) { Range.setEnd(L); }
53193326Sed};
54193326Sed
55212904Sdim}
56212904Sdim
57193326Sedstatic bool EvaluateDirectiveSubExpr(PPValue &LHS, unsigned MinPrec,
58193326Sed                                     Token &PeekTok, bool ValueLive,
59193326Sed                                     Preprocessor &PP);
60193326Sed
61193326Sed/// DefinedTracker - This struct is used while parsing expressions to keep track
62193326Sed/// of whether !defined(X) has been seen.
63193326Sed///
64193326Sed/// With this simple scheme, we handle the basic forms:
65193326Sed///    !defined(X)   and !defined X
66193326Sed/// but we also trivially handle (silly) stuff like:
67193326Sed///    !!!defined(X) and +!defined(X) and !+!+!defined(X) and !(defined(X)).
68193326Sedstruct DefinedTracker {
69193326Sed  /// Each time a Value is evaluated, it returns information about whether the
70193326Sed  /// parsed value is of the form defined(X), !defined(X) or is something else.
71193326Sed  enum TrackerState {
72193326Sed    DefinedMacro,        // defined(X)
73193326Sed    NotDefinedMacro,     // !defined(X)
74193326Sed    Unknown              // Something else.
75193326Sed  } State;
76193326Sed  /// TheMacro - When the state is DefinedMacro or NotDefinedMacro, this
77193326Sed  /// indicates the macro that was checked.
78193326Sed  IdentifierInfo *TheMacro;
79193326Sed};
80193326Sed
81198893Srdivacky/// EvaluateDefined - Process a 'defined(sym)' expression.
82200583Srdivackystatic bool EvaluateDefined(PPValue &Result, Token &PeekTok, DefinedTracker &DT,
83200583Srdivacky                            bool ValueLive, Preprocessor &PP) {
84198893Srdivacky  IdentifierInfo *II;
85263508Sdim  SourceLocation beginLoc(PeekTok.getLocation());
86263508Sdim  Result.setBegin(beginLoc);
87198893Srdivacky
88198893Srdivacky  // Get the next token, don't expand it.
89226633Sdim  PP.LexUnexpandedNonComment(PeekTok);
90198893Srdivacky
91198893Srdivacky  // Two options, it can either be a pp-identifier or a (.
92198893Srdivacky  SourceLocation LParenLoc;
93198893Srdivacky  if (PeekTok.is(tok::l_paren)) {
94198893Srdivacky    // Found a paren, remember we saw it and skip it.
95198893Srdivacky    LParenLoc = PeekTok.getLocation();
96226633Sdim    PP.LexUnexpandedNonComment(PeekTok);
97198893Srdivacky  }
98198893Srdivacky
99212904Sdim  if (PeekTok.is(tok::code_completion)) {
100212904Sdim    if (PP.getCodeCompletionHandler())
101212904Sdim      PP.getCodeCompletionHandler()->CodeCompleteMacroName(false);
102226633Sdim    PP.setCodeCompletionReached();
103226633Sdim    PP.LexUnexpandedNonComment(PeekTok);
104212904Sdim  }
105212904Sdim
106198893Srdivacky  // If we don't have a pp-identifier now, this is an error.
107198893Srdivacky  if ((II = PeekTok.getIdentifierInfo()) == 0) {
108198893Srdivacky    PP.Diag(PeekTok, diag::err_pp_defined_requires_identifier);
109198893Srdivacky    return true;
110198893Srdivacky  }
111198893Srdivacky
112198893Srdivacky  // Otherwise, we got an identifier, is it defined to something?
113198893Srdivacky  Result.Val = II->hasMacroDefinition();
114198893Srdivacky  Result.Val.setIsUnsigned(false);  // Result is signed intmax_t.
115198893Srdivacky
116249423Sdim  MacroDirective *Macro = 0;
117198893Srdivacky  // If there is a macro, mark it used.
118198893Srdivacky  if (Result.Val != 0 && ValueLive) {
119249423Sdim    Macro = PP.getMacroDirective(II);
120249423Sdim    PP.markMacroAsUsed(Macro->getMacroInfo());
121198893Srdivacky  }
122198893Srdivacky
123263508Sdim  // Save macro token for callback.
124263508Sdim  Token macroToken(PeekTok);
125198893Srdivacky
126198893Srdivacky  // If we are in parens, ensure we have a trailing ).
127198893Srdivacky  if (LParenLoc.isValid()) {
128226633Sdim    // Consume identifier.
129226633Sdim    Result.setEnd(PeekTok.getLocation());
130226633Sdim    PP.LexUnexpandedNonComment(PeekTok);
131226633Sdim
132198893Srdivacky    if (PeekTok.isNot(tok::r_paren)) {
133198893Srdivacky      PP.Diag(PeekTok.getLocation(), diag::err_pp_missing_rparen) << "defined";
134198893Srdivacky      PP.Diag(LParenLoc, diag::note_matching) << "(";
135198893Srdivacky      return true;
136198893Srdivacky    }
137198893Srdivacky    // Consume the ).
138198893Srdivacky    Result.setEnd(PeekTok.getLocation());
139198893Srdivacky    PP.LexNonComment(PeekTok);
140226633Sdim  } else {
141226633Sdim    // Consume identifier.
142226633Sdim    Result.setEnd(PeekTok.getLocation());
143226633Sdim    PP.LexNonComment(PeekTok);
144198893Srdivacky  }
145198893Srdivacky
146263508Sdim  // Invoke the 'defined' callback.
147263508Sdim  if (PPCallbacks *Callbacks = PP.getPPCallbacks()) {
148263508Sdim    MacroDirective *MD = Macro;
149263508Sdim    // Pass the MacroInfo for the macro name even if the value is dead.
150263508Sdim    if (!MD && Result.Val != 0)
151263508Sdim      MD = PP.getMacroDirective(II);
152263508Sdim    Callbacks->Defined(macroToken, MD,
153263508Sdim                       SourceRange(beginLoc, PeekTok.getLocation()));
154263508Sdim  }
155263508Sdim
156198893Srdivacky  // Success, remember that we saw defined(X).
157198893Srdivacky  DT.State = DefinedTracker::DefinedMacro;
158198893Srdivacky  DT.TheMacro = II;
159198893Srdivacky  return false;
160198893Srdivacky}
161198893Srdivacky
162193326Sed/// EvaluateValue - Evaluate the token PeekTok (and any others needed) and
163193326Sed/// return the computed value in Result.  Return true if there was an error
164193326Sed/// parsing.  This function also returns information about the form of the
165193326Sed/// expression in DT.  See above for information on what DT means.
166193326Sed///
167193326Sed/// If ValueLive is false, then this value is being evaluated in a context where
168193326Sed/// the result is not used.  As such, avoid diagnostics that relate to
169193326Sed/// evaluation.
170193326Sedstatic bool EvaluateValue(PPValue &Result, Token &PeekTok, DefinedTracker &DT,
171193326Sed                          bool ValueLive, Preprocessor &PP) {
172193326Sed  DT.State = DefinedTracker::Unknown;
173198092Srdivacky
174212904Sdim  if (PeekTok.is(tok::code_completion)) {
175212904Sdim    if (PP.getCodeCompletionHandler())
176212904Sdim      PP.getCodeCompletionHandler()->CodeCompletePreprocessorExpression();
177226633Sdim    PP.setCodeCompletionReached();
178226633Sdim    PP.LexNonComment(PeekTok);
179212904Sdim  }
180212904Sdim
181193326Sed  // If this token's spelling is a pp-identifier, check to see if it is
182193326Sed  // 'defined' or if it is a macro.  Note that we check here because many
183193326Sed  // keywords are pp-identifiers, so we can't check the kind.
184193326Sed  if (IdentifierInfo *II = PeekTok.getIdentifierInfo()) {
185200583Srdivacky    // Handle "defined X" and "defined(X)".
186200583Srdivacky    if (II->isStr("defined"))
187198893Srdivacky      return(EvaluateDefined(Result, PeekTok, DT, ValueLive, PP));
188200583Srdivacky
189200583Srdivacky    // If this identifier isn't 'defined' or one of the special
190200583Srdivacky    // preprocessor keywords and it wasn't macro expanded, it turns
191200583Srdivacky    // into a simple 0, unless it is the C++ keyword "true", in which case it
192200583Srdivacky    // turns into "1".
193243830Sdim    if (ValueLive &&
194243830Sdim        II->getTokenID() != tok::kw_true &&
195243830Sdim        II->getTokenID() != tok::kw_false)
196200583Srdivacky      PP.Diag(PeekTok, diag::warn_pp_undef_identifier) << II;
197200583Srdivacky    Result.Val = II->getTokenID() == tok::kw_true;
198200583Srdivacky    Result.Val.setIsUnsigned(false);  // "0" is signed intmax_t 0.
199200583Srdivacky    Result.setRange(PeekTok.getLocation());
200200583Srdivacky    PP.LexNonComment(PeekTok);
201200583Srdivacky    return false;
202193326Sed  }
203198092Srdivacky
204193326Sed  switch (PeekTok.getKind()) {
205193326Sed  default:  // Non-value token.
206193326Sed    PP.Diag(PeekTok, diag::err_pp_expr_bad_token_start_expr);
207193326Sed    return true;
208221345Sdim  case tok::eod:
209193326Sed  case tok::r_paren:
210193326Sed    // If there is no expression, report and exit.
211193326Sed    PP.Diag(PeekTok, diag::err_pp_expected_value_in_expr);
212193326Sed    return true;
213193326Sed  case tok::numeric_constant: {
214234353Sdim    SmallString<64> IntegerBuffer;
215205219Srdivacky    bool NumberInvalid = false;
216226633Sdim    StringRef Spelling = PP.getSpelling(PeekTok, IntegerBuffer,
217205219Srdivacky                                              &NumberInvalid);
218205219Srdivacky    if (NumberInvalid)
219205219Srdivacky      return true; // a diagnostic was already reported
220205219Srdivacky
221243830Sdim    NumericLiteralParser Literal(Spelling, PeekTok.getLocation(), PP);
222193326Sed    if (Literal.hadError)
223193326Sed      return true; // a diagnostic was already reported.
224198092Srdivacky
225193326Sed    if (Literal.isFloatingLiteral() || Literal.isImaginary) {
226193326Sed      PP.Diag(PeekTok, diag::err_pp_illegal_floating_literal);
227193326Sed      return true;
228193326Sed    }
229193326Sed    assert(Literal.isIntegerLiteral() && "Unknown ppnumber");
230193326Sed
231234353Sdim    // Complain about, and drop, any ud-suffix.
232234353Sdim    if (Literal.hasUDSuffix())
233234353Sdim      PP.Diag(PeekTok, diag::err_pp_invalid_udl) << /*integer*/1;
234234353Sdim
235243830Sdim    // 'long long' is a C99 or C++11 feature.
236243830Sdim    if (!PP.getLangOpts().C99 && Literal.isLongLong) {
237243830Sdim      if (PP.getLangOpts().CPlusPlus)
238243830Sdim        PP.Diag(PeekTok,
239249423Sdim             PP.getLangOpts().CPlusPlus11 ?
240243830Sdim             diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong);
241243830Sdim      else
242243830Sdim        PP.Diag(PeekTok, diag::ext_c99_longlong);
243243830Sdim    }
244193326Sed
245193326Sed    // Parse the integer literal into Result.
246193326Sed    if (Literal.GetIntegerValue(Result.Val)) {
247193326Sed      // Overflow parsing integer literal.
248263508Sdim      if (ValueLive) PP.Diag(PeekTok, diag::err_integer_too_large);
249193326Sed      Result.Val.setIsUnsigned(true);
250193326Sed    } else {
251193326Sed      // Set the signedness of the result to match whether there was a U suffix
252193326Sed      // or not.
253193326Sed      Result.Val.setIsUnsigned(Literal.isUnsigned);
254198092Srdivacky
255193326Sed      // Detect overflow based on whether the value is signed.  If signed
256193326Sed      // and if the value is too large, emit a warning "integer constant is so
257193326Sed      // large that it is unsigned" e.g. on 12345678901234567890 where intmax_t
258193326Sed      // is 64-bits.
259193326Sed      if (!Literal.isUnsigned && Result.Val.isNegative()) {
260263508Sdim        // Don't warn for a hex or octal literal: 0x8000..0 shouldn't warn.
261263508Sdim        if (ValueLive && Literal.getRadix() == 10)
262193326Sed          PP.Diag(PeekTok, diag::warn_integer_too_large_for_signed);
263193326Sed        Result.Val.setIsUnsigned(true);
264193326Sed      }
265193326Sed    }
266198092Srdivacky
267193326Sed    // Consume the token.
268193326Sed    Result.setRange(PeekTok.getLocation());
269193326Sed    PP.LexNonComment(PeekTok);
270193326Sed    return false;
271193326Sed  }
272226633Sdim  case tok::char_constant:          // 'x'
273249423Sdim  case tok::wide_char_constant:     // L'x'
274226633Sdim  case tok::utf16_char_constant:    // u'x'
275249423Sdim  case tok::utf32_char_constant: {  // U'x'
276234353Sdim    // Complain about, and drop, any ud-suffix.
277234353Sdim    if (PeekTok.hasUDSuffix())
278234353Sdim      PP.Diag(PeekTok, diag::err_pp_invalid_udl) << /*character*/0;
279234353Sdim
280234353Sdim    SmallString<32> CharBuffer;
281205219Srdivacky    bool CharInvalid = false;
282226633Sdim    StringRef ThisTok = PP.getSpelling(PeekTok, CharBuffer, &CharInvalid);
283205219Srdivacky    if (CharInvalid)
284205219Srdivacky      return true;
285204643Srdivacky
286204643Srdivacky    CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(),
287226633Sdim                              PeekTok.getLocation(), PP, PeekTok.getKind());
288193326Sed    if (Literal.hadError())
289193326Sed      return true;  // A diagnostic was already emitted.
290193326Sed
291193326Sed    // Character literals are always int or wchar_t, expand to intmax_t.
292199482Srdivacky    const TargetInfo &TI = PP.getTargetInfo();
293193326Sed    unsigned NumBits;
294193326Sed    if (Literal.isMultiChar())
295193326Sed      NumBits = TI.getIntWidth();
296198092Srdivacky    else if (Literal.isWide())
297198092Srdivacky      NumBits = TI.getWCharWidth();
298226633Sdim    else if (Literal.isUTF16())
299226633Sdim      NumBits = TI.getChar16Width();
300226633Sdim    else if (Literal.isUTF32())
301226633Sdim      NumBits = TI.getChar32Width();
302193326Sed    else
303198092Srdivacky      NumBits = TI.getCharWidth();
304193326Sed
305193326Sed    // Set the width.
306193326Sed    llvm::APSInt Val(NumBits);
307193326Sed    // Set the value.
308193326Sed    Val = Literal.getValue();
309226633Sdim    // Set the signedness. UTF-16 and UTF-32 are always unsigned
310226633Sdim    if (!Literal.isUTF16() && !Literal.isUTF32())
311234353Sdim      Val.setIsUnsigned(!PP.getLangOpts().CharIsSigned);
312198092Srdivacky
313193326Sed    if (Result.Val.getBitWidth() > Val.getBitWidth()) {
314193326Sed      Result.Val = Val.extend(Result.Val.getBitWidth());
315193326Sed    } else {
316193326Sed      assert(Result.Val.getBitWidth() == Val.getBitWidth() &&
317193326Sed             "intmax_t smaller than char/wchar_t?");
318193326Sed      Result.Val = Val;
319193326Sed    }
320193326Sed
321193326Sed    // Consume the token.
322193326Sed    Result.setRange(PeekTok.getLocation());
323193326Sed    PP.LexNonComment(PeekTok);
324193326Sed    return false;
325193326Sed  }
326193326Sed  case tok::l_paren: {
327193326Sed    SourceLocation Start = PeekTok.getLocation();
328193326Sed    PP.LexNonComment(PeekTok);  // Eat the (.
329193326Sed    // Parse the value and if there are any binary operators involved, parse
330193326Sed    // them.
331193326Sed    if (EvaluateValue(Result, PeekTok, DT, ValueLive, PP)) return true;
332193326Sed
333193326Sed    // If this is a silly value like (X), which doesn't need parens, check for
334193326Sed    // !(defined X).
335193326Sed    if (PeekTok.is(tok::r_paren)) {
336193326Sed      // Just use DT unmodified as our result.
337193326Sed    } else {
338193326Sed      // Otherwise, we have something like (x+y), and we consumed '(x'.
339193326Sed      if (EvaluateDirectiveSubExpr(Result, 1, PeekTok, ValueLive, PP))
340193326Sed        return true;
341198092Srdivacky
342193326Sed      if (PeekTok.isNot(tok::r_paren)) {
343193326Sed        PP.Diag(PeekTok.getLocation(), diag::err_pp_expected_rparen)
344193326Sed          << Result.getRange();
345193326Sed        PP.Diag(Start, diag::note_matching) << "(";
346193326Sed        return true;
347193326Sed      }
348193326Sed      DT.State = DefinedTracker::Unknown;
349193326Sed    }
350193326Sed    Result.setRange(Start, PeekTok.getLocation());
351193326Sed    PP.LexNonComment(PeekTok);  // Eat the ).
352193326Sed    return false;
353193326Sed  }
354193326Sed  case tok::plus: {
355193326Sed    SourceLocation Start = PeekTok.getLocation();
356193326Sed    // Unary plus doesn't modify the value.
357193326Sed    PP.LexNonComment(PeekTok);
358193326Sed    if (EvaluateValue(Result, PeekTok, DT, ValueLive, PP)) return true;
359193326Sed    Result.setBegin(Start);
360193326Sed    return false;
361193326Sed  }
362193326Sed  case tok::minus: {
363193326Sed    SourceLocation Loc = PeekTok.getLocation();
364193326Sed    PP.LexNonComment(PeekTok);
365193326Sed    if (EvaluateValue(Result, PeekTok, DT, ValueLive, PP)) return true;
366193326Sed    Result.setBegin(Loc);
367198092Srdivacky
368193326Sed    // C99 6.5.3.3p3: The sign of the result matches the sign of the operand.
369193326Sed    Result.Val = -Result.Val;
370198092Srdivacky
371193326Sed    // -MININT is the only thing that overflows.  Unsigned never overflows.
372193326Sed    bool Overflow = !Result.isUnsigned() && Result.Val.isMinSignedValue();
373198092Srdivacky
374193326Sed    // If this operator is live and overflowed, report the issue.
375193326Sed    if (Overflow && ValueLive)
376193326Sed      PP.Diag(Loc, diag::warn_pp_expr_overflow) << Result.getRange();
377198092Srdivacky
378193326Sed    DT.State = DefinedTracker::Unknown;
379193326Sed    return false;
380193326Sed  }
381198092Srdivacky
382193326Sed  case tok::tilde: {
383193326Sed    SourceLocation Start = PeekTok.getLocation();
384193326Sed    PP.LexNonComment(PeekTok);
385193326Sed    if (EvaluateValue(Result, PeekTok, DT, ValueLive, PP)) return true;
386193326Sed    Result.setBegin(Start);
387193326Sed
388193326Sed    // C99 6.5.3.3p4: The sign of the result matches the sign of the operand.
389193326Sed    Result.Val = ~Result.Val;
390193326Sed    DT.State = DefinedTracker::Unknown;
391193326Sed    return false;
392193326Sed  }
393198092Srdivacky
394193326Sed  case tok::exclaim: {
395193326Sed    SourceLocation Start = PeekTok.getLocation();
396193326Sed    PP.LexNonComment(PeekTok);
397193326Sed    if (EvaluateValue(Result, PeekTok, DT, ValueLive, PP)) return true;
398193326Sed    Result.setBegin(Start);
399193326Sed    Result.Val = !Result.Val;
400193326Sed    // C99 6.5.3.3p5: The sign of the result is 'int', aka it is signed.
401193326Sed    Result.Val.setIsUnsigned(false);
402198092Srdivacky
403193326Sed    if (DT.State == DefinedTracker::DefinedMacro)
404193326Sed      DT.State = DefinedTracker::NotDefinedMacro;
405193326Sed    else if (DT.State == DefinedTracker::NotDefinedMacro)
406193326Sed      DT.State = DefinedTracker::DefinedMacro;
407193326Sed    return false;
408193326Sed  }
409198092Srdivacky
410193326Sed  // FIXME: Handle #assert
411193326Sed  }
412193326Sed}
413193326Sed
414193326Sed
415193326Sed
416193326Sed/// getPrecedence - Return the precedence of the specified binary operator
417193326Sed/// token.  This returns:
418193326Sed///   ~0 - Invalid token.
419193326Sed///   14 -> 3 - various operators.
420221345Sdim///    0 - 'eod' or ')'
421193326Sedstatic unsigned getPrecedence(tok::TokenKind Kind) {
422193326Sed  switch (Kind) {
423193326Sed  default: return ~0U;
424193326Sed  case tok::percent:
425193326Sed  case tok::slash:
426193326Sed  case tok::star:                 return 14;
427193326Sed  case tok::plus:
428193326Sed  case tok::minus:                return 13;
429193326Sed  case tok::lessless:
430193326Sed  case tok::greatergreater:       return 12;
431193326Sed  case tok::lessequal:
432193326Sed  case tok::less:
433193326Sed  case tok::greaterequal:
434193326Sed  case tok::greater:              return 11;
435193326Sed  case tok::exclaimequal:
436193326Sed  case tok::equalequal:           return 10;
437193326Sed  case tok::amp:                  return 9;
438193326Sed  case tok::caret:                return 8;
439193326Sed  case tok::pipe:                 return 7;
440193326Sed  case tok::ampamp:               return 6;
441193326Sed  case tok::pipepipe:             return 5;
442193326Sed  case tok::question:             return 4;
443193326Sed  case tok::comma:                return 3;
444193326Sed  case tok::colon:                return 2;
445221345Sdim  case tok::r_paren:              return 0;// Lowest priority, end of expr.
446221345Sdim  case tok::eod:                  return 0;// Lowest priority, end of directive.
447193326Sed  }
448193326Sed}
449193326Sed
450193326Sed
451193326Sed/// EvaluateDirectiveSubExpr - Evaluate the subexpression whose first token is
452193326Sed/// PeekTok, and whose precedence is PeekPrec.  This returns the result in LHS.
453193326Sed///
454193326Sed/// If ValueLive is false, then this value is being evaluated in a context where
455193326Sed/// the result is not used.  As such, avoid diagnostics that relate to
456193326Sed/// evaluation, such as division by zero warnings.
457193326Sedstatic bool EvaluateDirectiveSubExpr(PPValue &LHS, unsigned MinPrec,
458193326Sed                                     Token &PeekTok, bool ValueLive,
459193326Sed                                     Preprocessor &PP) {
460193326Sed  unsigned PeekPrec = getPrecedence(PeekTok.getKind());
461193326Sed  // If this token isn't valid, report the error.
462193326Sed  if (PeekPrec == ~0U) {
463193326Sed    PP.Diag(PeekTok.getLocation(), diag::err_pp_expr_bad_token_binop)
464193326Sed      << LHS.getRange();
465193326Sed    return true;
466193326Sed  }
467198092Srdivacky
468193326Sed  while (1) {
469193326Sed    // If this token has a lower precedence than we are allowed to parse, return
470193326Sed    // it so that higher levels of the recursion can parse it.
471193326Sed    if (PeekPrec < MinPrec)
472193326Sed      return false;
473198092Srdivacky
474193326Sed    tok::TokenKind Operator = PeekTok.getKind();
475198092Srdivacky
476193326Sed    // If this is a short-circuiting operator, see if the RHS of the operator is
477198092Srdivacky    // dead.  Note that this cannot just clobber ValueLive.  Consider
478193326Sed    // "0 && 1 ? 4 : 1 / 0", which is parsed as "(0 && 1) ? 4 : (1 / 0)".  In
479193326Sed    // this example, the RHS of the && being dead does not make the rest of the
480193326Sed    // expr dead.
481193326Sed    bool RHSIsLive;
482193326Sed    if (Operator == tok::ampamp && LHS.Val == 0)
483193326Sed      RHSIsLive = false;   // RHS of "0 && x" is dead.
484193326Sed    else if (Operator == tok::pipepipe && LHS.Val != 0)
485193326Sed      RHSIsLive = false;   // RHS of "1 || x" is dead.
486193326Sed    else if (Operator == tok::question && LHS.Val == 0)
487193326Sed      RHSIsLive = false;   // RHS (x) of "0 ? x : y" is dead.
488193326Sed    else
489193326Sed      RHSIsLive = ValueLive;
490193326Sed
491193326Sed    // Consume the operator, remembering the operator's location for reporting.
492193326Sed    SourceLocation OpLoc = PeekTok.getLocation();
493193326Sed    PP.LexNonComment(PeekTok);
494193326Sed
495193326Sed    PPValue RHS(LHS.getBitWidth());
496193326Sed    // Parse the RHS of the operator.
497193326Sed    DefinedTracker DT;
498193326Sed    if (EvaluateValue(RHS, PeekTok, DT, RHSIsLive, PP)) return true;
499193326Sed
500193326Sed    // Remember the precedence of this operator and get the precedence of the
501193326Sed    // operator immediately to the right of the RHS.
502193326Sed    unsigned ThisPrec = PeekPrec;
503193326Sed    PeekPrec = getPrecedence(PeekTok.getKind());
504193326Sed
505193326Sed    // If this token isn't valid, report the error.
506193326Sed    if (PeekPrec == ~0U) {
507193326Sed      PP.Diag(PeekTok.getLocation(), diag::err_pp_expr_bad_token_binop)
508193326Sed        << RHS.getRange();
509193326Sed      return true;
510193326Sed    }
511198092Srdivacky
512193326Sed    // Decide whether to include the next binop in this subexpression.  For
513193326Sed    // example, when parsing x+y*z and looking at '*', we want to recursively
514193326Sed    // handle y*z as a single subexpression.  We do this because the precedence
515193326Sed    // of * is higher than that of +.  The only strange case we have to handle
516193326Sed    // here is for the ?: operator, where the precedence is actually lower than
517193326Sed    // the LHS of the '?'.  The grammar rule is:
518193326Sed    //
519193326Sed    // conditional-expression ::=
520193326Sed    //    logical-OR-expression ? expression : conditional-expression
521193326Sed    // where 'expression' is actually comma-expression.
522193326Sed    unsigned RHSPrec;
523193326Sed    if (Operator == tok::question)
524193326Sed      // The RHS of "?" should be maximally consumed as an expression.
525193326Sed      RHSPrec = getPrecedence(tok::comma);
526193326Sed    else  // All others should munch while higher precedence.
527193326Sed      RHSPrec = ThisPrec+1;
528198092Srdivacky
529193326Sed    if (PeekPrec >= RHSPrec) {
530193326Sed      if (EvaluateDirectiveSubExpr(RHS, RHSPrec, PeekTok, RHSIsLive, PP))
531193326Sed        return true;
532193326Sed      PeekPrec = getPrecedence(PeekTok.getKind());
533193326Sed    }
534193326Sed    assert(PeekPrec <= ThisPrec && "Recursion didn't work!");
535198092Srdivacky
536193326Sed    // Usual arithmetic conversions (C99 6.3.1.8p1): result is unsigned if
537198092Srdivacky    // either operand is unsigned.
538193326Sed    llvm::APSInt Res(LHS.getBitWidth());
539193326Sed    switch (Operator) {
540193326Sed    case tok::question:       // No UAC for x and y in "x ? y : z".
541193326Sed    case tok::lessless:       // Shift amount doesn't UAC with shift value.
542193326Sed    case tok::greatergreater: // Shift amount doesn't UAC with shift value.
543193326Sed    case tok::comma:          // Comma operands are not subject to UACs.
544193326Sed    case tok::pipepipe:       // Logical || does not do UACs.
545193326Sed    case tok::ampamp:         // Logical && does not do UACs.
546193326Sed      break;                  // No UAC
547193326Sed    default:
548193326Sed      Res.setIsUnsigned(LHS.isUnsigned()|RHS.isUnsigned());
549193326Sed      // If this just promoted something from signed to unsigned, and if the
550193326Sed      // value was negative, warn about it.
551193326Sed      if (ValueLive && Res.isUnsigned()) {
552193326Sed        if (!LHS.isUnsigned() && LHS.Val.isNegative())
553193326Sed          PP.Diag(OpLoc, diag::warn_pp_convert_lhs_to_positive)
554193326Sed            << LHS.Val.toString(10, true) + " to " +
555193326Sed               LHS.Val.toString(10, false)
556193326Sed            << LHS.getRange() << RHS.getRange();
557193326Sed        if (!RHS.isUnsigned() && RHS.Val.isNegative())
558193326Sed          PP.Diag(OpLoc, diag::warn_pp_convert_rhs_to_positive)
559193326Sed            << RHS.Val.toString(10, true) + " to " +
560193326Sed               RHS.Val.toString(10, false)
561193326Sed            << LHS.getRange() << RHS.getRange();
562193326Sed      }
563193326Sed      LHS.Val.setIsUnsigned(Res.isUnsigned());
564193326Sed      RHS.Val.setIsUnsigned(Res.isUnsigned());
565193326Sed    }
566198092Srdivacky
567193326Sed    bool Overflow = false;
568193326Sed    switch (Operator) {
569226633Sdim    default: llvm_unreachable("Unknown operator token!");
570193326Sed    case tok::percent:
571193326Sed      if (RHS.Val != 0)
572193326Sed        Res = LHS.Val % RHS.Val;
573193326Sed      else if (ValueLive) {
574193326Sed        PP.Diag(OpLoc, diag::err_pp_remainder_by_zero)
575193326Sed          << LHS.getRange() << RHS.getRange();
576193326Sed        return true;
577193326Sed      }
578193326Sed      break;
579193326Sed    case tok::slash:
580193326Sed      if (RHS.Val != 0) {
581218893Sdim        if (LHS.Val.isSigned())
582218893Sdim          Res = llvm::APSInt(LHS.Val.sdiv_ov(RHS.Val, Overflow), false);
583218893Sdim        else
584218893Sdim          Res = LHS.Val / RHS.Val;
585193326Sed      } else if (ValueLive) {
586193326Sed        PP.Diag(OpLoc, diag::err_pp_division_by_zero)
587193326Sed          << LHS.getRange() << RHS.getRange();
588193326Sed        return true;
589193326Sed      }
590193326Sed      break;
591198092Srdivacky
592193326Sed    case tok::star:
593218893Sdim      if (Res.isSigned())
594218893Sdim        Res = llvm::APSInt(LHS.Val.smul_ov(RHS.Val, Overflow), false);
595218893Sdim      else
596218893Sdim        Res = LHS.Val * RHS.Val;
597193326Sed      break;
598193326Sed    case tok::lessless: {
599193326Sed      // Determine whether overflow is about to happen.
600193326Sed      unsigned ShAmt = static_cast<unsigned>(RHS.Val.getLimitedValue());
601218893Sdim      if (LHS.isUnsigned()) {
602218893Sdim        Overflow = ShAmt >= LHS.Val.getBitWidth();
603218893Sdim        if (Overflow)
604218893Sdim          ShAmt = LHS.Val.getBitWidth()-1;
605218893Sdim        Res = LHS.Val << ShAmt;
606218893Sdim      } else {
607218893Sdim        Res = llvm::APSInt(LHS.Val.sshl_ov(ShAmt, Overflow), false);
608218893Sdim      }
609193326Sed      break;
610193326Sed    }
611193326Sed    case tok::greatergreater: {
612193326Sed      // Determine whether overflow is about to happen.
613193326Sed      unsigned ShAmt = static_cast<unsigned>(RHS.Val.getLimitedValue());
614193326Sed      if (ShAmt >= LHS.getBitWidth())
615193326Sed        Overflow = true, ShAmt = LHS.getBitWidth()-1;
616193326Sed      Res = LHS.Val >> ShAmt;
617193326Sed      break;
618193326Sed    }
619193326Sed    case tok::plus:
620193326Sed      if (LHS.isUnsigned())
621218893Sdim        Res = LHS.Val + RHS.Val;
622218893Sdim      else
623218893Sdim        Res = llvm::APSInt(LHS.Val.sadd_ov(RHS.Val, Overflow), false);
624193326Sed      break;
625193326Sed    case tok::minus:
626193326Sed      if (LHS.isUnsigned())
627218893Sdim        Res = LHS.Val - RHS.Val;
628218893Sdim      else
629218893Sdim        Res = llvm::APSInt(LHS.Val.ssub_ov(RHS.Val, Overflow), false);
630193326Sed      break;
631193326Sed    case tok::lessequal:
632193326Sed      Res = LHS.Val <= RHS.Val;
633193326Sed      Res.setIsUnsigned(false);  // C99 6.5.8p6, result is always int (signed)
634193326Sed      break;
635193326Sed    case tok::less:
636193326Sed      Res = LHS.Val < RHS.Val;
637193326Sed      Res.setIsUnsigned(false);  // C99 6.5.8p6, result is always int (signed)
638193326Sed      break;
639193326Sed    case tok::greaterequal:
640193326Sed      Res = LHS.Val >= RHS.Val;
641193326Sed      Res.setIsUnsigned(false);  // C99 6.5.8p6, result is always int (signed)
642193326Sed      break;
643193326Sed    case tok::greater:
644193326Sed      Res = LHS.Val > RHS.Val;
645193326Sed      Res.setIsUnsigned(false);  // C99 6.5.8p6, result is always int (signed)
646193326Sed      break;
647193326Sed    case tok::exclaimequal:
648193326Sed      Res = LHS.Val != RHS.Val;
649193326Sed      Res.setIsUnsigned(false);  // C99 6.5.9p3, result is always int (signed)
650193326Sed      break;
651193326Sed    case tok::equalequal:
652193326Sed      Res = LHS.Val == RHS.Val;
653193326Sed      Res.setIsUnsigned(false);  // C99 6.5.9p3, result is always int (signed)
654193326Sed      break;
655193326Sed    case tok::amp:
656193326Sed      Res = LHS.Val & RHS.Val;
657193326Sed      break;
658193326Sed    case tok::caret:
659193326Sed      Res = LHS.Val ^ RHS.Val;
660193326Sed      break;
661193326Sed    case tok::pipe:
662193326Sed      Res = LHS.Val | RHS.Val;
663193326Sed      break;
664193326Sed    case tok::ampamp:
665193326Sed      Res = (LHS.Val != 0 && RHS.Val != 0);
666193326Sed      Res.setIsUnsigned(false);  // C99 6.5.13p3, result is always int (signed)
667193326Sed      break;
668193326Sed    case tok::pipepipe:
669193326Sed      Res = (LHS.Val != 0 || RHS.Val != 0);
670193326Sed      Res.setIsUnsigned(false);  // C99 6.5.14p3, result is always int (signed)
671193326Sed      break;
672193326Sed    case tok::comma:
673193326Sed      // Comma is invalid in pp expressions in c89/c++ mode, but is valid in C99
674193326Sed      // if not being evaluated.
675234353Sdim      if (!PP.getLangOpts().C99 || ValueLive)
676193326Sed        PP.Diag(OpLoc, diag::ext_pp_comma_expr)
677193326Sed          << LHS.getRange() << RHS.getRange();
678193326Sed      Res = RHS.Val; // LHS = LHS,RHS -> RHS.
679198092Srdivacky      break;
680193326Sed    case tok::question: {
681193326Sed      // Parse the : part of the expression.
682193326Sed      if (PeekTok.isNot(tok::colon)) {
683193326Sed        PP.Diag(PeekTok.getLocation(), diag::err_expected_colon)
684193326Sed          << LHS.getRange(), RHS.getRange();
685193326Sed        PP.Diag(OpLoc, diag::note_matching) << "?";
686193326Sed        return true;
687193326Sed      }
688193326Sed      // Consume the :.
689193326Sed      PP.LexNonComment(PeekTok);
690193326Sed
691193326Sed      // Evaluate the value after the :.
692193326Sed      bool AfterColonLive = ValueLive && LHS.Val == 0;
693193326Sed      PPValue AfterColonVal(LHS.getBitWidth());
694193326Sed      DefinedTracker DT;
695193326Sed      if (EvaluateValue(AfterColonVal, PeekTok, DT, AfterColonLive, PP))
696193326Sed        return true;
697193326Sed
698193326Sed      // Parse anything after the : with the same precedence as ?.  We allow
699193326Sed      // things of equal precedence because ?: is right associative.
700193326Sed      if (EvaluateDirectiveSubExpr(AfterColonVal, ThisPrec,
701193326Sed                                   PeekTok, AfterColonLive, PP))
702193326Sed        return true;
703198092Srdivacky
704193326Sed      // Now that we have the condition, the LHS and the RHS of the :, evaluate.
705193326Sed      Res = LHS.Val != 0 ? RHS.Val : AfterColonVal.Val;
706193326Sed      RHS.setEnd(AfterColonVal.getRange().getEnd());
707193326Sed
708193326Sed      // Usual arithmetic conversions (C99 6.3.1.8p1): result is unsigned if
709193326Sed      // either operand is unsigned.
710193326Sed      Res.setIsUnsigned(RHS.isUnsigned() | AfterColonVal.isUnsigned());
711198092Srdivacky
712193326Sed      // Figure out the precedence of the token after the : part.
713193326Sed      PeekPrec = getPrecedence(PeekTok.getKind());
714193326Sed      break;
715193326Sed    }
716193326Sed    case tok::colon:
717193326Sed      // Don't allow :'s to float around without being part of ?: exprs.
718193326Sed      PP.Diag(OpLoc, diag::err_pp_colon_without_question)
719193326Sed        << LHS.getRange() << RHS.getRange();
720193326Sed      return true;
721193326Sed    }
722193326Sed
723193326Sed    // If this operator is live and overflowed, report the issue.
724193326Sed    if (Overflow && ValueLive)
725193326Sed      PP.Diag(OpLoc, diag::warn_pp_expr_overflow)
726193326Sed        << LHS.getRange() << RHS.getRange();
727198092Srdivacky
728193326Sed    // Put the result back into 'LHS' for our next iteration.
729193326Sed    LHS.Val = Res;
730193326Sed    LHS.setEnd(RHS.getRange().getEnd());
731193326Sed  }
732193326Sed}
733193326Sed
734193326Sed/// EvaluateDirectiveExpression - Evaluate an integer constant expression that
735193326Sed/// may occur after a #if or #elif directive.  If the expression is equivalent
736193326Sed/// to "!defined(X)" return X in IfNDefMacro.
737193326Sedbool Preprocessor::
738193326SedEvaluateDirectiveExpression(IdentifierInfo *&IfNDefMacro) {
739249423Sdim  SaveAndRestore<bool> PPDir(ParsingIfOrElifDirective, true);
740200583Srdivacky  // Save the current state of 'DisableMacroExpansion' and reset it to false. If
741200583Srdivacky  // 'DisableMacroExpansion' is true, then we must be in a macro argument list
742200583Srdivacky  // in which case a directive is undefined behavior.  We want macros to be able
743200583Srdivacky  // to recursively expand in order to get more gcc-list behavior, so we force
744200583Srdivacky  // DisableMacroExpansion to false and restore it when we're done parsing the
745200583Srdivacky  // expression.
746200583Srdivacky  bool DisableMacroExpansionAtStartOfDirective = DisableMacroExpansion;
747200583Srdivacky  DisableMacroExpansion = false;
748200583Srdivacky
749193326Sed  // Peek ahead one token.
750193326Sed  Token Tok;
751226633Sdim  LexNonComment(Tok);
752212904Sdim
753193326Sed  // C99 6.10.1p3 - All expressions are evaluated as intmax_t or uintmax_t.
754193326Sed  unsigned BitWidth = getTargetInfo().getIntMaxTWidth();
755198092Srdivacky
756193326Sed  PPValue ResVal(BitWidth);
757193326Sed  DefinedTracker DT;
758193326Sed  if (EvaluateValue(ResVal, Tok, DT, true, *this)) {
759193326Sed    // Parse error, skip the rest of the macro line.
760221345Sdim    if (Tok.isNot(tok::eod))
761193326Sed      DiscardUntilEndOfDirective();
762200583Srdivacky
763200583Srdivacky    // Restore 'DisableMacroExpansion'.
764200583Srdivacky    DisableMacroExpansion = DisableMacroExpansionAtStartOfDirective;
765193326Sed    return false;
766193326Sed  }
767198092Srdivacky
768193326Sed  // If we are at the end of the expression after just parsing a value, there
769193326Sed  // must be no (unparenthesized) binary operators involved, so we can exit
770193326Sed  // directly.
771221345Sdim  if (Tok.is(tok::eod)) {
772193326Sed    // If the expression we parsed was of the form !defined(macro), return the
773193326Sed    // macro in IfNDefMacro.
774193326Sed    if (DT.State == DefinedTracker::NotDefinedMacro)
775193326Sed      IfNDefMacro = DT.TheMacro;
776198092Srdivacky
777200583Srdivacky    // Restore 'DisableMacroExpansion'.
778200583Srdivacky    DisableMacroExpansion = DisableMacroExpansionAtStartOfDirective;
779193326Sed    return ResVal.Val != 0;
780193326Sed  }
781198092Srdivacky
782193326Sed  // Otherwise, we must have a binary operator (e.g. "#if 1 < 2"), so parse the
783193326Sed  // operator and the stuff after it.
784193326Sed  if (EvaluateDirectiveSubExpr(ResVal, getPrecedence(tok::question),
785193326Sed                               Tok, true, *this)) {
786193326Sed    // Parse error, skip the rest of the macro line.
787221345Sdim    if (Tok.isNot(tok::eod))
788193326Sed      DiscardUntilEndOfDirective();
789200583Srdivacky
790200583Srdivacky    // Restore 'DisableMacroExpansion'.
791200583Srdivacky    DisableMacroExpansion = DisableMacroExpansionAtStartOfDirective;
792193326Sed    return false;
793193326Sed  }
794198092Srdivacky
795221345Sdim  // If we aren't at the tok::eod token, something bad happened, like an extra
796193326Sed  // ')' token.
797221345Sdim  if (Tok.isNot(tok::eod)) {
798193326Sed    Diag(Tok, diag::err_pp_expected_eol);
799193326Sed    DiscardUntilEndOfDirective();
800193326Sed  }
801198092Srdivacky
802200583Srdivacky  // Restore 'DisableMacroExpansion'.
803200583Srdivacky  DisableMacroExpansion = DisableMacroExpansionAtStartOfDirective;
804193326Sed  return ResVal.Val != 0;
805193326Sed}
806