Coverage Report

Created: 2021-09-21 08:58

/Users/buildslave/jenkins/workspace/coverage/llvm-project/clang/lib/Lex/PPExpressions.cpp
Line
Count
Source (jump to first uncovered line)
1
//===--- PPExpressions.cpp - Preprocessor Expression Evaluation -----------===//
2
//
3
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4
// See https://llvm.org/LICENSE.txt for license information.
5
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6
//
7
//===----------------------------------------------------------------------===//
8
//
9
// This file implements the Preprocessor::EvaluateDirectiveExpression method,
10
// which parses and evaluates integer constant expressions for #if directives.
11
//
12
//===----------------------------------------------------------------------===//
13
//
14
// FIXME: implement testing for #assert's.
15
//
16
//===----------------------------------------------------------------------===//
17
18
#include "clang/Basic/IdentifierTable.h"
19
#include "clang/Basic/SourceLocation.h"
20
#include "clang/Basic/SourceManager.h"
21
#include "clang/Basic/TargetInfo.h"
22
#include "clang/Basic/TokenKinds.h"
23
#include "clang/Lex/CodeCompletionHandler.h"
24
#include "clang/Lex/LexDiagnostic.h"
25
#include "clang/Lex/LiteralSupport.h"
26
#include "clang/Lex/MacroInfo.h"
27
#include "clang/Lex/PPCallbacks.h"
28
#include "clang/Lex/Preprocessor.h"
29
#include "clang/Lex/Token.h"
30
#include "llvm/ADT/APSInt.h"
31
#include "llvm/ADT/STLExtras.h"
32
#include "llvm/ADT/SmallString.h"
33
#include "llvm/ADT/StringExtras.h"
34
#include "llvm/ADT/StringRef.h"
35
#include "llvm/Support/ErrorHandling.h"
36
#include "llvm/Support/SaveAndRestore.h"
37
#include <cassert>
38
39
using namespace clang;
40
41
namespace {
42
43
/// PPValue - Represents the value of a subexpression of a preprocessor
44
/// conditional and the source range covered by it.
45
class PPValue {
46
  SourceRange Range;
47
  IdentifierInfo *II;
48
49
public:
50
  llvm::APSInt Val;
51
52
  // Default ctor - Construct an 'invalid' PPValue.
53
3.62M
  PPValue(unsigned BitWidth) : Val(BitWidth) {}
54
55
  // If this value was produced by directly evaluating an identifier, produce
56
  // that identifier.
57
11
  IdentifierInfo *getIdentifier() const { return II; }
58
6.79M
  void setIdentifier(IdentifierInfo *II) { this->II = II; }
59
60
2.84M
  unsigned getBitWidth() const { return Val.getBitWidth(); }
61
1.19M
  bool isUnsigned() const { return Val.isUnsigned(); }
62
63
3.62M
  SourceRange getRange() const { return Range; }
64
65
2.15M
  void setRange(SourceLocation L) { Range.setBegin(L); Range.setEnd(L); }
66
165k
  void setRange(SourceLocation B, SourceLocation E) {
67
165k
    Range.setBegin(B); Range.setEnd(E);
68
165k
  }
69
2.09M
  void setBegin(SourceLocation L) { Range.setBegin(L); }
70
4.35M
  void setEnd(SourceLocation L) { Range.setEnd(L); }
71
};
72
73
} // end anonymous namespace
74
75
static bool EvaluateDirectiveSubExpr(PPValue &LHS, unsigned MinPrec,
76
                                     Token &PeekTok, bool ValueLive,
77
                                     bool &IncludedUndefinedIds,
78
                                     Preprocessor &PP);
79
80
/// DefinedTracker - This struct is used while parsing expressions to keep track
81
/// of whether !defined(X) has been seen.
82
///
83
/// With this simple scheme, we handle the basic forms:
84
///    !defined(X)   and !defined X
85
/// but we also trivially handle (silly) stuff like:
86
///    !!!defined(X) and +!defined(X) and !+!+!defined(X) and !(defined(X)).
87
struct DefinedTracker {
88
  /// Each time a Value is evaluated, it returns information about whether the
89
  /// parsed value is of the form defined(X), !defined(X) or is something else.
90
  enum TrackerState {
91
    DefinedMacro,        // defined(X)
92
    NotDefinedMacro,     // !defined(X)
93
    Unknown              // Something else.
94
  } State;
95
  /// TheMacro - When the state is DefinedMacro or NotDefinedMacro, this
96
  /// indicates the macro that was checked.
97
  IdentifierInfo *TheMacro;
98
  bool IncludedUndefinedIds = false;
99
};
100
101
/// EvaluateDefined - Process a 'defined(sym)' expression.
102
static bool EvaluateDefined(PPValue &Result, Token &PeekTok, DefinedTracker &DT,
103
1.47M
                            bool ValueLive, Preprocessor &PP) {
104
1.47M
  SourceLocation beginLoc(PeekTok.getLocation());
105
1.47M
  Result.setBegin(beginLoc);
106
107
  // Get the next token, don't expand it.
108
1.47M
  PP.LexUnexpandedNonComment(PeekTok);
109
110
  // Two options, it can either be a pp-identifier or a (.
111
1.47M
  SourceLocation LParenLoc;
112
1.47M
  if (PeekTok.is(tok::l_paren)) {
113
    // Found a paren, remember we saw it and skip it.
114
1.45M
    LParenLoc = PeekTok.getLocation();
115
1.45M
    PP.LexUnexpandedNonComment(PeekTok);
116
1.45M
  }
117
118
1.47M
  if (PeekTok.is(tok::code_completion)) {
119
2
    if (PP.getCodeCompletionHandler())
120
2
      PP.getCodeCompletionHandler()->CodeCompleteMacroName(false);
121
2
    PP.setCodeCompletionReached();
122
2
    PP.LexUnexpandedNonComment(PeekTok);
123
2
  }
124
125
  // If we don't have a pp-identifier now, this is an error.
126
1.47M
  if (PP.CheckMacroName(PeekTok, MU_Other))
127
4
    return true;
128
129
  // Otherwise, we got an identifier, is it defined to something?
130
1.47M
  IdentifierInfo *II = PeekTok.getIdentifierInfo();
131
1.47M
  MacroDefinition Macro = PP.getMacroDefinition(II);
132
1.47M
  Result.Val = !!Macro;
133
1.47M
  Result.Val.setIsUnsigned(false); // Result is signed intmax_t.
134
1.47M
  DT.IncludedUndefinedIds = !Macro;
135
136
1.47M
  PP.emitMacroExpansionWarnings(PeekTok);
137
138
  // If there is a macro, mark it used.
139
1.47M
  if (Result.Val != 0 && 
ValueLive392k
)
140
311k
    PP.markMacroAsUsed(Macro.getMacroInfo());
141
142
  // Save macro token for callback.
143
1.47M
  Token macroToken(PeekTok);
144
145
  // If we are in parens, ensure we have a trailing ).
146
1.47M
  if (LParenLoc.isValid()) {
147
    // Consume identifier.
148
1.45M
    Result.setEnd(PeekTok.getLocation());
149
1.45M
    PP.LexUnexpandedNonComment(PeekTok);
150
151
1.45M
    if (PeekTok.isNot(tok::r_paren)) {
152
1
      PP.Diag(PeekTok.getLocation(), diag::err_pp_expected_after)
153
1
          << "'defined'" << tok::r_paren;
154
1
      PP.Diag(LParenLoc, diag::note_matching) << tok::l_paren;
155
1
      return true;
156
1
    }
157
    // Consume the ).
158
1.45M
    PP.LexNonComment(PeekTok);
159
1.45M
    Result.setEnd(PeekTok.getLocation());
160
1.45M
  } else {
161
    // Consume identifier.
162
13.3k
    Result.setEnd(PeekTok.getLocation());
163
13.3k
    PP.LexNonComment(PeekTok);
164
13.3k
  }
165
166
  // [cpp.cond]p4:
167
  //   Prior to evaluation, macro invocations in the list of preprocessing
168
  //   tokens that will become the controlling constant expression are replaced
169
  //   (except for those macro names modified by the 'defined' unary operator),
170
  //   just as in normal text. If the token 'defined' is generated as a result
171
  //   of this replacement process or use of the 'defined' unary operator does
172
  //   not match one of the two specified forms prior to macro replacement, the
173
  //   behavior is undefined.
174
  // This isn't an idle threat, consider this program:
175
  //   #define FOO
176
  //   #define BAR defined(FOO)
177
  //   #if BAR
178
  //   ...
179
  //   #else
180
  //   ...
181
  //   #endif
182
  // clang and gcc will pick the #if branch while Visual Studio will take the
183
  // #else branch.  Emit a warning about this undefined behavior.
184
1.47M
  if (beginLoc.isMacroID()) {
185
2.77k
    bool IsFunctionTypeMacro =
186
2.77k
        PP.getSourceManager()
187
2.77k
            .getSLocEntry(PP.getSourceManager().getFileID(beginLoc))
188
2.77k
            .getExpansion()
189
2.77k
            .isFunctionMacroExpansion();
190
    // For object-type macros, it's easy to replace
191
    //   #define FOO defined(BAR)
192
    // with
193
    //   #if defined(BAR)
194
    //   #define FOO 1
195
    //   #else
196
    //   #define FOO 0
197
    //   #endif
198
    // and doing so makes sense since compilers handle this differently in
199
    // practice (see example further up).  But for function-type macros,
200
    // there is no good way to write
201
    //   # define FOO(x) (defined(M_ ## x) && M_ ## x)
202
    // in a different way, and compilers seem to agree on how to behave here.
203
    // So warn by default on object-type macros, but only warn in -pedantic
204
    // mode on function-type macros.
205
2.77k
    if (IsFunctionTypeMacro)
206
926
      PP.Diag(beginLoc, diag::warn_defined_in_function_type_macro);
207
1.84k
    else
208
1.84k
      PP.Diag(beginLoc, diag::warn_defined_in_object_type_macro);
209
2.77k
  }
210
211
  // Invoke the 'defined' callback.
212
1.47M
  if (PPCallbacks *Callbacks = PP.getPPCallbacks()) {
213
1.47M
    Callbacks->Defined(macroToken, Macro,
214
1.47M
                       SourceRange(beginLoc, PeekTok.getLocation()));
215
1.47M
  }
216
217
  // Success, remember that we saw defined(X).
218
1.47M
  DT.State = DefinedTracker::DefinedMacro;
219
1.47M
  DT.TheMacro = II;
220
1.47M
  return false;
221
1.47M
}
222
223
/// EvaluateValue - Evaluate the token PeekTok (and any others needed) and
224
/// return the computed value in Result.  Return true if there was an error
225
/// parsing.  This function also returns information about the form of the
226
/// expression in DT.  See above for information on what DT means.
227
///
228
/// If ValueLive is false, then this value is being evaluated in a context where
229
/// the result is not used.  As such, avoid diagnostics that relate to
230
/// evaluation.
231
static bool EvaluateValue(PPValue &Result, Token &PeekTok, DefinedTracker &DT,
232
4.42M
                          bool ValueLive, Preprocessor &PP) {
233
4.42M
  DT.State = DefinedTracker::Unknown;
234
235
4.42M
  Result.setIdentifier(nullptr);
236
237
4.42M
  if (PeekTok.is(tok::code_completion)) {
238
8
    if (PP.getCodeCompletionHandler())
239
8
      PP.getCodeCompletionHandler()->CodeCompletePreprocessorExpression();
240
8
    PP.setCodeCompletionReached();
241
8
    PP.LexNonComment(PeekTok);
242
8
  }
243
244
4.42M
  switch (PeekTok.getKind()) {
245
1.63M
  default:
246
    // If this token's spelling is a pp-identifier, check to see if it is
247
    // 'defined' or if it is a macro.  Note that we check here because many
248
    // keywords are pp-identifiers, so we can't check the kind.
249
1.63M
    if (IdentifierInfo *II = PeekTok.getIdentifierInfo()) {
250
      // Handle "defined X" and "defined(X)".
251
1.63M
      if (II->isStr("defined"))
252
1.47M
        return EvaluateDefined(Result, PeekTok, DT, ValueLive, PP);
253
254
158k
      if (!II->isCPlusPlusOperatorKeyword()) {
255
        // If this identifier isn't 'defined' or one of the special
256
        // preprocessor keywords and it wasn't macro expanded, it turns
257
        // into a simple 0
258
158k
        if (ValueLive) {
259
31.1k
          PP.Diag(PeekTok, diag::warn_pp_undef_identifier) << II;
260
261
31.1k
          const DiagnosticsEngine &DiagEngine = PP.getDiagnostics();
262
          // If 'Wundef' is enabled, do not emit 'undef-prefix' diagnostics.
263
31.1k
          if (DiagEngine.isIgnored(diag::warn_pp_undef_identifier,
264
31.1k
                                   PeekTok.getLocation())) {
265
31.1k
            const std::vector<std::string> UndefPrefixes =
266
31.1k
                DiagEngine.getDiagnosticOptions().UndefPrefixes;
267
31.1k
            const StringRef IdentifierName = II->getName();
268
31.1k
            if (llvm::any_of(UndefPrefixes,
269
31.1k
                             [&IdentifierName](const std::string &Prefix) {
270
27.2k
                               return IdentifierName.startswith(Prefix);
271
27.2k
                             }))
272
2.43k
              PP.Diag(PeekTok, diag::warn_pp_undef_prefix)
273
2.43k
                  << AddFlagValue{llvm::join(UndefPrefixes, ",")} << II;
274
31.1k
          }
275
31.1k
        }
276
158k
        Result.Val = 0;
277
158k
        Result.Val.setIsUnsigned(false); // "0" is signed intmax_t 0.
278
158k
        Result.setIdentifier(II);
279
158k
        Result.setRange(PeekTok.getLocation());
280
158k
        DT.IncludedUndefinedIds = true;
281
158k
        PP.LexNonComment(PeekTok);
282
158k
        return false;
283
158k
      }
284
158k
    }
285
20
    PP.Diag(PeekTok, diag::err_pp_expr_bad_token_start_expr);
286
20
    return true;
287
14
  case tok::eod:
288
14
  case tok::r_paren:
289
    // If there is no expression, report and exit.
290
14
    PP.Diag(PeekTok, diag::err_pp_expected_value_in_expr);
291
14
    return true;
292
1.99M
  case tok::numeric_constant: {
293
1.99M
    SmallString<64> IntegerBuffer;
294
1.99M
    bool NumberInvalid = false;
295
1.99M
    StringRef Spelling = PP.getSpelling(PeekTok, IntegerBuffer,
296
1.99M
                                              &NumberInvalid);
297
1.99M
    if (NumberInvalid)
298
0
      return true; // a diagnostic was already reported
299
300
1.99M
    NumericLiteralParser Literal(Spelling, PeekTok.getLocation(),
301
1.99M
                                 PP.getSourceManager(), PP.getLangOpts(),
302
1.99M
                                 PP.getTargetInfo(), PP.getDiagnostics());
303
1.99M
    if (Literal.hadError)
304
0
      return true; // a diagnostic was already reported.
305
306
1.99M
    if (Literal.isFloatingLiteral() || Literal.isImaginary) {
307
0
      PP.Diag(PeekTok, diag::err_pp_illegal_floating_literal);
308
0
      return true;
309
0
    }
310
1.99M
    assert(Literal.isIntegerLiteral() && "Unknown ppnumber");
311
312
    // Complain about, and drop, any ud-suffix.
313
1.99M
    if (Literal.hasUDSuffix())
314
1
      PP.Diag(PeekTok, diag::err_pp_invalid_udl) << /*integer*/1;
315
316
    // 'long long' is a C99 or C++11 feature.
317
1.99M
    if (!PP.getLangOpts().C99 && 
Literal.isLongLong1.18M
) {
318
3
      if (PP.getLangOpts().CPlusPlus)
319
2
        PP.Diag(PeekTok,
320
2
             PP.getLangOpts().CPlusPlus11 ?
321
1
             diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong);
322
1
      else
323
1
        PP.Diag(PeekTok, diag::ext_c99_longlong);
324
3
    }
325
326
    // 'z/uz' literals are a C++2b feature.
327
1.99M
    if (Literal.isSizeT)
328
4
      PP.Diag(PeekTok, PP.getLangOpts().CPlusPlus
329
4
                           ? PP.getLangOpts().CPlusPlus2b
330
4
                                 ? diag::warn_cxx20_compat_size_t_suffix
331
4
                                 : 
diag::ext_cxx2b_size_t_suffix0
332
4
                           : 
diag::err_cxx2b_size_t_suffix0
);
333
334
    // Parse the integer literal into Result.
335
1.99M
    if (Literal.GetIntegerValue(Result.Val)) {
336
      // Overflow parsing integer literal.
337
1
      if (ValueLive)
338
1
        PP.Diag(PeekTok, diag::err_integer_literal_too_large)
339
1
            << /* Unsigned */ 1;
340
1
      Result.Val.setIsUnsigned(true);
341
1.99M
    } else {
342
      // Set the signedness of the result to match whether there was a U suffix
343
      // or not.
344
1.99M
      Result.Val.setIsUnsigned(Literal.isUnsigned);
345
346
      // Detect overflow based on whether the value is signed.  If signed
347
      // and if the value is too large, emit a warning "integer constant is so
348
      // large that it is unsigned" e.g. on 12345678901234567890 where intmax_t
349
      // is 64-bits.
350
1.99M
      if (!Literal.isUnsigned && 
Result.Val.isNegative()1.99M
) {
351
        // Octal, hexadecimal, and binary literals are implicitly unsigned if
352
        // the value does not fit into a signed integer type.
353
16
        if (ValueLive && 
Literal.getRadix() == 1011
)
354
1
          PP.Diag(PeekTok, diag::ext_integer_literal_too_large_for_signed);
355
16
        Result.Val.setIsUnsigned(true);
356
16
      }
357
1.99M
    }
358
359
    // Consume the token.
360
1.99M
    Result.setRange(PeekTok.getLocation());
361
1.99M
    PP.LexNonComment(PeekTok);
362
1.99M
    return false;
363
1.99M
  }
364
7
  case tok::char_constant:          // 'x'
365
11
  case tok::wide_char_constant:     // L'x'
366
11
  case tok::utf8_char_constant:     // u8'x'
367
12
  case tok::utf16_char_constant:    // u'x'
368
12
  case tok::utf32_char_constant: {  // U'x'
369
    // Complain about, and drop, any ud-suffix.
370
12
    if (PeekTok.hasUDSuffix())
371
2
      PP.Diag(PeekTok, diag::err_pp_invalid_udl) << /*character*/0;
372
373
12
    SmallString<32> CharBuffer;
374
12
    bool CharInvalid = false;
375
12
    StringRef ThisTok = PP.getSpelling(PeekTok, CharBuffer, &CharInvalid);
376
12
    if (CharInvalid)
377
0
      return true;
378
379
12
    CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(),
380
12
                              PeekTok.getLocation(), PP, PeekTok.getKind());
381
12
    if (Literal.hadError())
382
0
      return true;  // A diagnostic was already emitted.
383
384
    // Character literals are always int or wchar_t, expand to intmax_t.
385
12
    const TargetInfo &TI = PP.getTargetInfo();
386
12
    unsigned NumBits;
387
12
    if (Literal.isMultiChar())
388
2
      NumBits = TI.getIntWidth();
389
10
    else if (Literal.isWide())
390
4
      NumBits = TI.getWCharWidth();
391
6
    else if (Literal.isUTF16())
392
1
      NumBits = TI.getChar16Width();
393
5
    else if (Literal.isUTF32())
394
0
      NumBits = TI.getChar32Width();
395
5
    else // char or char8_t
396
5
      NumBits = TI.getCharWidth();
397
398
    // Set the width.
399
12
    llvm::APSInt Val(NumBits);
400
    // Set the value.
401
12
    Val = Literal.getValue();
402
    // Set the signedness. UTF-16 and UTF-32 are always unsigned
403
12
    if (Literal.isWide())
404
4
      Val.setIsUnsigned(!TargetInfo::isTypeSigned(TI.getWCharType()));
405
8
    else if (!Literal.isUTF16() && 
!Literal.isUTF32()7
)
406
7
      Val.setIsUnsigned(!PP.getLangOpts().CharIsSigned);
407
408
12
    if (Result.Val.getBitWidth() > Val.getBitWidth()) {
409
12
      Result.Val = Val.extend(Result.Val.getBitWidth());
410
12
    } else {
411
0
      assert(Result.Val.getBitWidth() == Val.getBitWidth() &&
412
0
             "intmax_t smaller than char/wchar_t?");
413
0
      Result.Val = Val;
414
0
    }
415
416
    // Consume the token.
417
0
    Result.setRange(PeekTok.getLocation());
418
12
    PP.LexNonComment(PeekTok);
419
12
    return false;
420
12
  }
421
165k
  case tok::l_paren: {
422
165k
    SourceLocation Start = PeekTok.getLocation();
423
165k
    PP.LexNonComment(PeekTok);  // Eat the (.
424
    // Parse the value and if there are any binary operators involved, parse
425
    // them.
426
165k
    if (EvaluateValue(Result, PeekTok, DT, ValueLive, PP)) 
return true0
;
427
428
    // If this is a silly value like (X), which doesn't need parens, check for
429
    // !(defined X).
430
165k
    if (PeekTok.is(tok::r_paren)) {
431
      // Just use DT unmodified as our result.
432
145k
    } else {
433
      // Otherwise, we have something like (x+y), and we consumed '(x'.
434
145k
      if (EvaluateDirectiveSubExpr(Result, 1, PeekTok, ValueLive,
435
145k
                                   DT.IncludedUndefinedIds, PP))
436
0
        return true;
437
438
145k
      if (PeekTok.isNot(tok::r_paren)) {
439
0
        PP.Diag(PeekTok.getLocation(), diag::err_pp_expected_rparen)
440
0
          << Result.getRange();
441
0
        PP.Diag(Start, diag::note_matching) << tok::l_paren;
442
0
        return true;
443
0
      }
444
145k
      DT.State = DefinedTracker::Unknown;
445
145k
    }
446
165k
    Result.setRange(Start, PeekTok.getLocation());
447
165k
    Result.setIdentifier(nullptr);
448
165k
    PP.LexNonComment(PeekTok);  // Eat the ).
449
165k
    return false;
450
165k
  }
451
0
  case tok::plus: {
452
0
    SourceLocation Start = PeekTok.getLocation();
453
    // Unary plus doesn't modify the value.
454
0
    PP.LexNonComment(PeekTok);
455
0
    if (EvaluateValue(Result, PeekTok, DT, ValueLive, PP)) return true;
456
0
    Result.setBegin(Start);
457
0
    Result.setIdentifier(nullptr);
458
0
    return false;
459
0
  }
460
112
  case tok::minus: {
461
112
    SourceLocation Loc = PeekTok.getLocation();
462
112
    PP.LexNonComment(PeekTok);
463
112
    if (EvaluateValue(Result, PeekTok, DT, ValueLive, PP)) 
return true0
;
464
112
    Result.setBegin(Loc);
465
112
    Result.setIdentifier(nullptr);
466
467
    // C99 6.5.3.3p3: The sign of the result matches the sign of the operand.
468
112
    Result.Val = -Result.Val;
469
470
    // -MININT is the only thing that overflows.  Unsigned never overflows.
471
112
    bool Overflow = !Result.isUnsigned() && 
Result.Val.isMinSignedValue()109
;
472
473
    // If this operator is live and overflowed, report the issue.
474
112
    if (Overflow && 
ValueLive0
)
475
0
      PP.Diag(Loc, diag::warn_pp_expr_overflow) << Result.getRange();
476
477
112
    DT.State = DefinedTracker::Unknown;
478
112
    return false;
479
112
  }
480
481
7
  case tok::tilde: {
482
7
    SourceLocation Start = PeekTok.getLocation();
483
7
    PP.LexNonComment(PeekTok);
484
7
    if (EvaluateValue(Result, PeekTok, DT, ValueLive, PP)) 
return true0
;
485
7
    Result.setBegin(Start);
486
7
    Result.setIdentifier(nullptr);
487
488
    // C99 6.5.3.3p4: The sign of the result matches the sign of the operand.
489
7
    Result.Val = ~Result.Val;
490
7
    DT.State = DefinedTracker::Unknown;
491
7
    return false;
492
7
  }
493
494
626k
  case tok::exclaim: {
495
626k
    SourceLocation Start = PeekTok.getLocation();
496
626k
    PP.LexNonComment(PeekTok);
497
626k
    if (EvaluateValue(Result, PeekTok, DT, ValueLive, PP)) 
return true0
;
498
626k
    Result.setBegin(Start);
499
626k
    Result.Val = !Result.Val;
500
    // C99 6.5.3.3p5: The sign of the result is 'int', aka it is signed.
501
626k
    Result.Val.setIsUnsigned(false);
502
626k
    Result.setIdentifier(nullptr);
503
504
626k
    if (DT.State == DefinedTracker::DefinedMacro)
505
504k
      DT.State = DefinedTracker::NotDefinedMacro;
506
121k
    else if (DT.State == DefinedTracker::NotDefinedMacro)
507
0
      DT.State = DefinedTracker::DefinedMacro;
508
626k
    return false;
509
626k
  }
510
2
  case tok::kw_true:
511
4
  case tok::kw_false:
512
4
    Result.Val = PeekTok.getKind() == tok::kw_true;
513
4
    Result.Val.setIsUnsigned(false); // "0" is signed intmax_t 0.
514
4
    Result.setIdentifier(PeekTok.getIdentifierInfo());
515
4
    Result.setRange(PeekTok.getLocation());
516
4
    PP.LexNonComment(PeekTok);
517
4
    return false;
518
519
  // FIXME: Handle #assert
520
4.42M
  }
521
4.42M
}
522
523
/// getPrecedence - Return the precedence of the specified binary operator
524
/// token.  This returns:
525
///   ~0 - Invalid token.
526
///   14 -> 3 - various operators.
527
///    0 - 'eod' or ')'
528
3.58M
static unsigned getPrecedence(tok::TokenKind Kind) {
529
3.58M
  switch (Kind) {
530
15
  default: return ~0U;
531
0
  case tok::percent:
532
16
  case tok::slash:
533
2.32k
  case tok::star:                 return 14;
534
2.30k
  case tok::plus:
535
10.1k
  case tok::minus:                return 13;
536
1
  case tok::lessless:
537
11
  case tok::greatergreater:       return 12;
538
49.6k
  case tok::lessequal:
539
110k
  case tok::less:
540
549k
  case tok::greaterequal:
541
709k
  case tok::greater:              return 11;
542
2.61k
  case tok::exclaimequal:
543
73.9k
  case tok::equalequal:           return 10;
544
586
  case tok::amp:                  return 9;
545
10
  case tok::caret:                return 8;
546
10
  case tok::pipe:                 return 7;
547
462k
  case tok::ampamp:               return 6;
548
381k
  case tok::pipepipe:             return 5;
549
799k
  case tok::question:             return 4;
550
1.67k
  case tok::comma:                return 3;
551
1.67k
  case tok::colon:                return 2;
552
164k
  case tok::r_paren:              return 0;// Lowest priority, end of expr.
553
982k
  case tok::eod:                  return 0;// Lowest priority, end of directive.
554
3.58M
  }
555
3.58M
}
556
557
static void diagnoseUnexpectedOperator(Preprocessor &PP, PPValue &LHS,
558
15
                                       Token &Tok) {
559
15
  if (Tok.is(tok::l_paren) && 
LHS.getIdentifier()6
)
560
5
    PP.Diag(LHS.getRange().getBegin(), diag::err_pp_expr_bad_token_lparen)
561
5
        << LHS.getIdentifier();
562
10
  else
563
10
    PP.Diag(Tok.getLocation(), diag::err_pp_expr_bad_token_binop)
564
10
        << LHS.getRange();
565
15
}
566
567
/// EvaluateDirectiveSubExpr - Evaluate the subexpression whose first token is
568
/// PeekTok, and whose precedence is PeekPrec.  This returns the result in LHS.
569
///
570
/// If ValueLive is false, then this value is being evaluated in a context where
571
/// the result is not used.  As such, avoid diagnostics that relate to
572
/// evaluation, such as division by zero warnings.
573
static bool EvaluateDirectiveSubExpr(PPValue &LHS, unsigned MinPrec,
574
                                     Token &PeekTok, bool ValueLive,
575
                                     bool &IncludedUndefinedIds,
576
1.15M
                                     Preprocessor &PP) {
577
1.15M
  unsigned PeekPrec = getPrecedence(PeekTok.getKind());
578
  // If this token isn't valid, report the error.
579
1.15M
  if (PeekPrec == ~0U) {
580
14
    diagnoseUnexpectedOperator(PP, LHS, PeekTok);
581
14
    return true;
582
14
  }
583
584
2.57M
  
while (1.15M
true) {
585
    // If this token has a lower precedence than we are allowed to parse, return
586
    // it so that higher levels of the recursion can parse it.
587
2.57M
    if (PeekPrec < MinPrec)
588
1.15M
      return false;
589
590
1.42M
    tok::TokenKind Operator = PeekTok.getKind();
591
592
    // If this is a short-circuiting operator, see if the RHS of the operator is
593
    // dead.  Note that this cannot just clobber ValueLive.  Consider
594
    // "0 && 1 ? 4 : 1 / 0", which is parsed as "(0 && 1) ? 4 : (1 / 0)".  In
595
    // this example, the RHS of the && being dead does not make the rest of the
596
    // expr dead.
597
1.42M
    bool RHSIsLive;
598
1.42M
    if (Operator == tok::ampamp && 
LHS.Val == 0456k
)
599
237k
      RHSIsLive = false;   // RHS of "0 && x" is dead.
600
1.18M
    else if (Operator == tok::pipepipe && 
LHS.Val != 0378k
)
601
233k
      RHSIsLive = false;   // RHS of "1 || x" is dead.
602
949k
    else if (Operator == tok::question && 
LHS.Val == 01.67k
)
603
1.29k
      RHSIsLive = false;   // RHS (x) of "0 ? x : y" is dead.
604
948k
    else
605
948k
      RHSIsLive = ValueLive;
606
607
    // Consume the operator, remembering the operator's location for reporting.
608
1.42M
    SourceLocation OpLoc = PeekTok.getLocation();
609
1.42M
    PP.LexNonComment(PeekTok);
610
611
1.42M
    PPValue RHS(LHS.getBitWidth());
612
    // Parse the RHS of the operator.
613
1.42M
    DefinedTracker DT;
614
1.42M
    if (EvaluateValue(RHS, PeekTok, DT, RHSIsLive, PP)) 
return true1
;
615
1.42M
    IncludedUndefinedIds = DT.IncludedUndefinedIds;
616
617
    // Remember the precedence of this operator and get the precedence of the
618
    // operator immediately to the right of the RHS.
619
1.42M
    unsigned ThisPrec = PeekPrec;
620
1.42M
    PeekPrec = getPrecedence(PeekTok.getKind());
621
622
    // If this token isn't valid, report the error.
623
1.42M
    if (PeekPrec == ~0U) {
624
1
      diagnoseUnexpectedOperator(PP, RHS, PeekTok);
625
1
      return true;
626
1
    }
627
628
    // Decide whether to include the next binop in this subexpression.  For
629
    // example, when parsing x+y*z and looking at '*', we want to recursively
630
    // handle y*z as a single subexpression.  We do this because the precedence
631
    // of * is higher than that of +.  The only strange case we have to handle
632
    // here is for the ?: operator, where the precedence is actually lower than
633
    // the LHS of the '?'.  The grammar rule is:
634
    //
635
    // conditional-expression ::=
636
    //    logical-OR-expression ? expression : conditional-expression
637
    // where 'expression' is actually comma-expression.
638
1.42M
    unsigned RHSPrec;
639
1.42M
    if (Operator == tok::question)
640
      // The RHS of "?" should be maximally consumed as an expression.
641
1.67k
      RHSPrec = getPrecedence(tok::comma);
642
1.41M
    else  // All others should munch while higher precedence.
643
1.41M
      RHSPrec = ThisPrec+1;
644
645
1.42M
    if (PeekPrec >= RHSPrec) {
646
211k
      if (EvaluateDirectiveSubExpr(RHS, RHSPrec, PeekTok, RHSIsLive,
647
211k
                                   IncludedUndefinedIds, PP))
648
0
        return true;
649
211k
      PeekPrec = getPrecedence(PeekTok.getKind());
650
211k
    }
651
1.42M
    assert(PeekPrec <= ThisPrec && "Recursion didn't work!");
652
653
    // Usual arithmetic conversions (C99 6.3.1.8p1): result is unsigned if
654
    // either operand is unsigned.
655
0
    llvm::APSInt Res(LHS.getBitWidth());
656
1.42M
    switch (Operator) {
657
1.67k
    case tok::question:       // No UAC for x and y in "x ? y : z".
658
1.67k
    case tok::lessless:       // Shift amount doesn't UAC with shift value.
659
1.68k
    case tok::greatergreater: // Shift amount doesn't UAC with shift value.
660
1.68k
    case tok::comma:          // Comma operands are not subject to UACs.
661
379k
    case tok::pipepipe:       // Logical || does not do UACs.
662
835k
    case tok::ampamp:         // Logical && does not do UACs.
663
835k
      break;                  // No UAC
664
585k
    default:
665
585k
      Res.setIsUnsigned(LHS.isUnsigned()|RHS.isUnsigned());
666
      // If this just promoted something from signed to unsigned, and if the
667
      // value was negative, warn about it.
668
585k
      if (ValueLive && 
Res.isUnsigned()443k
) {
669
4.79k
        if (!LHS.isUnsigned() && 
LHS.Val.isNegative()2.02k
)
670
2
          PP.Diag(OpLoc, diag::warn_pp_convert_to_positive) << 0
671
2
            << toString(LHS.Val, 10, true) + " to " +
672
2
               toString(LHS.Val, 10, false)
673
2
            << LHS.getRange() << RHS.getRange();
674
4.79k
        if (!RHS.isUnsigned() && 
RHS.Val.isNegative()2.75k
)
675
2
          PP.Diag(OpLoc, diag::warn_pp_convert_to_positive) << 1
676
2
            << toString(RHS.Val, 10, true) + " to " +
677
2
               toString(RHS.Val, 10, false)
678
2
            << LHS.getRange() << RHS.getRange();
679
4.79k
      }
680
585k
      LHS.Val.setIsUnsigned(Res.isUnsigned());
681
585k
      RHS.Val.setIsUnsigned(Res.isUnsigned());
682
1.42M
    }
683
684
1.42M
    bool Overflow = false;
685
1.42M
    switch (Operator) {
686
0
    default: llvm_unreachable("Unknown operator token!");
687
0
    case tok::percent:
688
0
      if (RHS.Val != 0)
689
0
        Res = LHS.Val % RHS.Val;
690
0
      else if (ValueLive) {
691
0
        PP.Diag(OpLoc, diag::err_pp_remainder_by_zero)
692
0
          << LHS.getRange() << RHS.getRange();
693
0
        return true;
694
0
      }
695
0
      break;
696
11
    case tok::slash:
697
11
      if (RHS.Val != 0) {
698
1
        if (LHS.Val.isSigned())
699
0
          Res = llvm::APSInt(LHS.Val.sdiv_ov(RHS.Val, Overflow), false);
700
1
        else
701
1
          Res = LHS.Val / RHS.Val;
702
10
      } else if (ValueLive) {
703
4
        PP.Diag(OpLoc, diag::err_pp_division_by_zero)
704
4
          << LHS.getRange() << RHS.getRange();
705
4
        return true;
706
4
      }
707
7
      break;
708
709
2.30k
    case tok::star:
710
2.30k
      if (Res.isSigned())
711
2.30k
        Res = llvm::APSInt(LHS.Val.smul_ov(RHS.Val, Overflow), false);
712
1
      else
713
1
        Res = LHS.Val * RHS.Val;
714
2.30k
      break;
715
1
    case tok::lessless: {
716
      // Determine whether overflow is about to happen.
717
1
      if (LHS.isUnsigned())
718
0
        Res = LHS.Val.ushl_ov(RHS.Val, Overflow);
719
1
      else
720
1
        Res = llvm::APSInt(LHS.Val.sshl_ov(RHS.Val, Overflow), false);
721
1
      break;
722
11
    }
723
10
    case tok::greatergreater: {
724
      // Determine whether overflow is about to happen.
725
10
      unsigned ShAmt = static_cast<unsigned>(RHS.Val.getLimitedValue());
726
10
      if (ShAmt >= LHS.getBitWidth()) {
727
0
        Overflow = true;
728
0
        ShAmt = LHS.getBitWidth()-1;
729
0
      }
730
10
      Res = LHS.Val >> ShAmt;
731
10
      break;
732
11
    }
733
2.30k
    case tok::plus:
734
2.30k
      if (LHS.isUnsigned())
735
2
        Res = LHS.Val + RHS.Val;
736
2.30k
      else
737
2.30k
        Res = llvm::APSInt(LHS.Val.sadd_ov(RHS.Val, Overflow), false);
738
2.30k
      break;
739
7.82k
    case tok::minus:
740
7.82k
      if (LHS.isUnsigned())
741
13
        Res = LHS.Val - RHS.Val;
742
7.81k
      else
743
7.81k
        Res = llvm::APSInt(LHS.Val.ssub_ov(RHS.Val, Overflow), false);
744
7.82k
      break;
745
47.5k
    case tok::lessequal:
746
47.5k
      Res = LHS.Val <= RHS.Val;
747
47.5k
      Res.setIsUnsigned(false);  // C99 6.5.8p6, result is always int (signed)
748
47.5k
      break;
749
39.4k
    case tok::less:
750
39.4k
      Res = LHS.Val < RHS.Val;
751
39.4k
      Res.setIsUnsigned(false);  // C99 6.5.8p6, result is always int (signed)
752
39.4k
      break;
753
267k
    case tok::greaterequal:
754
267k
      Res = LHS.Val >= RHS.Val;
755
267k
      Res.setIsUnsigned(false);  // C99 6.5.8p6, result is always int (signed)
756
267k
      break;
757
153k
    case tok::greater:
758
153k
      Res = LHS.Val > RHS.Val;
759
153k
      Res.setIsUnsigned(false);  // C99 6.5.8p6, result is always int (signed)
760
153k
      break;
761
1.91k
    case tok::exclaimequal:
762
1.91k
      Res = LHS.Val != RHS.Val;
763
1.91k
      Res.setIsUnsigned(false);  // C99 6.5.9p3, result is always int (signed)
764
1.91k
      break;
765
61.9k
    case tok::equalequal:
766
61.9k
      Res = LHS.Val == RHS.Val;
767
61.9k
      Res.setIsUnsigned(false);  // C99 6.5.9p3, result is always int (signed)
768
61.9k
      break;
769
586
    case tok::amp:
770
586
      Res = LHS.Val & RHS.Val;
771
586
      break;
772
10
    case tok::caret:
773
10
      Res = LHS.Val ^ RHS.Val;
774
10
      break;
775
10
    case tok::pipe:
776
10
      Res = LHS.Val | RHS.Val;
777
10
      break;
778
456k
    case tok::ampamp:
779
456k
      Res = (LHS.Val != 0 && 
RHS.Val != 0218k
);
780
456k
      Res.setIsUnsigned(false);  // C99 6.5.13p3, result is always int (signed)
781
456k
      break;
782
378k
    case tok::pipepipe:
783
378k
      Res = (LHS.Val != 0 || 
RHS.Val != 0144k
);
784
378k
      Res.setIsUnsigned(false);  // C99 6.5.14p3, result is always int (signed)
785
378k
      break;
786
2
    case tok::comma:
787
      // Comma is invalid in pp expressions in c89/c++ mode, but is valid in C99
788
      // if not being evaluated.
789
2
      if (!PP.getLangOpts().C99 || 
ValueLive1
)
790
1
        PP.Diag(OpLoc, diag::ext_pp_comma_expr)
791
1
          << LHS.getRange() << RHS.getRange();
792
2
      Res = RHS.Val; // LHS = LHS,RHS -> RHS.
793
2
      break;
794
1.67k
    case tok::question: {
795
      // Parse the : part of the expression.
796
1.67k
      if (PeekTok.isNot(tok::colon)) {
797
0
        PP.Diag(PeekTok.getLocation(), diag::err_expected)
798
0
            << tok::colon << LHS.getRange() << RHS.getRange();
799
0
        PP.Diag(OpLoc, diag::note_matching) << tok::question;
800
0
        return true;
801
0
      }
802
      // Consume the :.
803
1.67k
      PP.LexNonComment(PeekTok);
804
805
      // Evaluate the value after the :.
806
1.67k
      bool AfterColonLive = ValueLive && 
LHS.Val == 01.58k
;
807
1.67k
      PPValue AfterColonVal(LHS.getBitWidth());
808
1.67k
      DefinedTracker DT;
809
1.67k
      if (EvaluateValue(AfterColonVal, PeekTok, DT, AfterColonLive, PP))
810
0
        return true;
811
812
      // Parse anything after the : with the same precedence as ?.  We allow
813
      // things of equal precedence because ?: is right associative.
814
1.67k
      if (EvaluateDirectiveSubExpr(AfterColonVal, ThisPrec,
815
1.67k
                                   PeekTok, AfterColonLive,
816
1.67k
                                   IncludedUndefinedIds, PP))
817
1
        return true;
818
819
      // Now that we have the condition, the LHS and the RHS of the :, evaluate.
820
1.67k
      Res = LHS.Val != 0 ? 
RHS.Val377
:
AfterColonVal.Val1.29k
;
821
1.67k
      RHS.setEnd(AfterColonVal.getRange().getEnd());
822
823
      // Usual arithmetic conversions (C99 6.3.1.8p1): result is unsigned if
824
      // either operand is unsigned.
825
1.67k
      Res.setIsUnsigned(RHS.isUnsigned() | AfterColonVal.isUnsigned());
826
827
      // Figure out the precedence of the token after the : part.
828
1.67k
      PeekPrec = getPrecedence(PeekTok.getKind());
829
1.67k
      break;
830
1.67k
    }
831
0
    case tok::colon:
832
      // Don't allow :'s to float around without being part of ?: exprs.
833
0
      PP.Diag(OpLoc, diag::err_pp_colon_without_question)
834
0
        << LHS.getRange() << RHS.getRange();
835
0
      return true;
836
1.42M
    }
837
838
    // If this operator is live and overflowed, report the issue.
839
1.42M
    if (Overflow && 
ValueLive3
)
840
3
      PP.Diag(OpLoc, diag::warn_pp_expr_overflow)
841
3
        << LHS.getRange() << RHS.getRange();
842
843
    // Put the result back into 'LHS' for our next iteration.
844
1.42M
    LHS.Val = Res;
845
1.42M
    LHS.setEnd(RHS.getRange().getEnd());
846
1.42M
    RHS.setIdentifier(nullptr);
847
1.42M
  }
848
1.15M
}
849
850
/// EvaluateDirectiveExpression - Evaluate an integer constant expression that
851
/// may occur after a #if or #elif directive.  If the expression is equivalent
852
/// to "!defined(X)" return X in IfNDefMacro.
853
Preprocessor::DirectiveEvalResult
854
2.20M
Preprocessor::EvaluateDirectiveExpression(IdentifierInfo *&IfNDefMacro) {
855
2.20M
  SaveAndRestore<bool> PPDir(ParsingIfOrElifDirective, true);
856
  // Save the current state of 'DisableMacroExpansion' and reset it to false. If
857
  // 'DisableMacroExpansion' is true, then we must be in a macro argument list
858
  // in which case a directive is undefined behavior.  We want macros to be able
859
  // to recursively expand in order to get more gcc-list behavior, so we force
860
  // DisableMacroExpansion to false and restore it when we're done parsing the
861
  // expression.
862
2.20M
  bool DisableMacroExpansionAtStartOfDirective = DisableMacroExpansion;
863
2.20M
  DisableMacroExpansion = false;
864
865
  // Peek ahead one token.
866
2.20M
  Token Tok;
867
2.20M
  LexNonComment(Tok);
868
869
  // C99 6.10.1p3 - All expressions are evaluated as intmax_t or uintmax_t.
870
2.20M
  unsigned BitWidth = getTargetInfo().getIntMaxTWidth();
871
872
2.20M
  PPValue ResVal(BitWidth);
873
2.20M
  DefinedTracker DT;
874
2.20M
  SourceLocation ExprStartLoc = SourceMgr.getExpansionLoc(Tok.getLocation());
875
2.20M
  if (EvaluateValue(ResVal, Tok, DT, true, *this)) {
876
    // Parse error, skip the rest of the macro line.
877
38
    SourceRange ConditionRange = ExprStartLoc;
878
38
    if (Tok.isNot(tok::eod))
879
21
      ConditionRange = DiscardUntilEndOfDirective();
880
881
    // Restore 'DisableMacroExpansion'.
882
38
    DisableMacroExpansion = DisableMacroExpansionAtStartOfDirective;
883
884
    // We cannot trust the source range from the value because there was a
885
    // parse error. Track the range manually -- the end of the directive is the
886
    // end of the condition range.
887
38
    return {false,
888
38
            DT.IncludedUndefinedIds,
889
38
            {ExprStartLoc, ConditionRange.getEnd()}};
890
38
  }
891
892
  // If we are at the end of the expression after just parsing a value, there
893
  // must be no (unparenthesized) binary operators involved, so we can exit
894
  // directly.
895
2.20M
  if (Tok.is(tok::eod)) {
896
    // If the expression we parsed was of the form !defined(macro), return the
897
    // macro in IfNDefMacro.
898
1.40M
    if (DT.State == DefinedTracker::NotDefinedMacro)
899
231k
      IfNDefMacro = DT.TheMacro;
900
901
    // Restore 'DisableMacroExpansion'.
902
1.40M
    DisableMacroExpansion = DisableMacroExpansionAtStartOfDirective;
903
1.40M
    return {ResVal.Val != 0, DT.IncludedUndefinedIds, ResVal.getRange()};
904
1.40M
  }
905
906
  // Otherwise, we must have a binary operator (e.g. "#if 1 < 2"), so parse the
907
  // operator and the stuff after it.
908
797k
  if (EvaluateDirectiveSubExpr(ResVal, getPrecedence(tok::question),
909
797k
                               Tok, true, DT.IncludedUndefinedIds, *this)) {
910
    // Parse error, skip the rest of the macro line.
911
20
    if (Tok.isNot(tok::eod))
912
16
      DiscardUntilEndOfDirective();
913
914
    // Restore 'DisableMacroExpansion'.
915
20
    DisableMacroExpansion = DisableMacroExpansionAtStartOfDirective;
916
20
    return {false, DT.IncludedUndefinedIds, ResVal.getRange()};
917
20
  }
918
919
  // If we aren't at the tok::eod token, something bad happened, like an extra
920
  // ')' token.
921
797k
  if (Tok.isNot(tok::eod)) {
922
2
    Diag(Tok, diag::err_pp_expected_eol);
923
2
    DiscardUntilEndOfDirective();
924
2
  }
925
926
  // Restore 'DisableMacroExpansion'.
927
797k
  DisableMacroExpansion = DisableMacroExpansionAtStartOfDirective;
928
797k
  return {ResVal.Val != 0, DT.IncludedUndefinedIds, ResVal.getRange()};
929
797k
}