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