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.
PPValue(unsigned BitWidth)53 PPValue(unsigned BitWidth) : Val(BitWidth) {}
54
55 // If this value was produced by directly evaluating an identifier, produce
56 // that identifier.
getIdentifier() const57 IdentifierInfo *getIdentifier() const { return II; }
setIdentifier(IdentifierInfo * II)58 void setIdentifier(IdentifierInfo *II) { this->II = II; }
59
getBitWidth() const60 unsigned getBitWidth() const { return Val.getBitWidth(); }
isUnsigned() const61 bool isUnsigned() const { return Val.isUnsigned(); }
62
getRange() const63 SourceRange getRange() const { return Range; }
64
setRange(SourceLocation L)65 void setRange(SourceLocation L) { Range.setBegin(L); Range.setEnd(L); }
setRange(SourceLocation B,SourceLocation E)66 void setRange(SourceLocation B, SourceLocation E) {
67 Range.setBegin(B); Range.setEnd(E);
68 }
setBegin(SourceLocation L)69 void setBegin(SourceLocation L) { Range.setBegin(L); }
setEnd(SourceLocation L)70 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.
EvaluateDefined(PPValue & Result,Token & PeekTok,DefinedTracker & DT,bool ValueLive,Preprocessor & PP)102 static bool EvaluateDefined(PPValue &Result, Token &PeekTok, DefinedTracker &DT,
103 bool ValueLive, Preprocessor &PP) {
104 SourceLocation beginLoc(PeekTok.getLocation());
105 Result.setBegin(beginLoc);
106
107 // Get the next token, don't expand it.
108 PP.LexUnexpandedNonComment(PeekTok);
109
110 // Two options, it can either be a pp-identifier or a (.
111 SourceLocation LParenLoc;
112 if (PeekTok.is(tok::l_paren)) {
113 // Found a paren, remember we saw it and skip it.
114 LParenLoc = PeekTok.getLocation();
115 PP.LexUnexpandedNonComment(PeekTok);
116 }
117
118 if (PeekTok.is(tok::code_completion)) {
119 if (PP.getCodeCompletionHandler())
120 PP.getCodeCompletionHandler()->CodeCompleteMacroName(false);
121 PP.setCodeCompletionReached();
122 PP.LexUnexpandedNonComment(PeekTok);
123 }
124
125 // If we don't have a pp-identifier now, this is an error.
126 if (PP.CheckMacroName(PeekTok, MU_Other))
127 return true;
128
129 // Otherwise, we got an identifier, is it defined to something?
130 IdentifierInfo *II = PeekTok.getIdentifierInfo();
131 MacroDefinition Macro = PP.getMacroDefinition(II);
132 Result.Val = !!Macro;
133 Result.Val.setIsUnsigned(false); // Result is signed intmax_t.
134 DT.IncludedUndefinedIds = !Macro;
135
136 PP.emitMacroExpansionWarnings(PeekTok);
137
138 // If there is a macro, mark it used.
139 if (Result.Val != 0 && ValueLive)
140 PP.markMacroAsUsed(Macro.getMacroInfo());
141
142 // Save macro token for callback.
143 Token macroToken(PeekTok);
144
145 // If we are in parens, ensure we have a trailing ).
146 if (LParenLoc.isValid()) {
147 // Consume identifier.
148 Result.setEnd(PeekTok.getLocation());
149 PP.LexUnexpandedNonComment(PeekTok);
150
151 if (PeekTok.isNot(tok::r_paren)) {
152 PP.Diag(PeekTok.getLocation(), diag::err_pp_expected_after)
153 << "'defined'" << tok::r_paren;
154 PP.Diag(LParenLoc, diag::note_matching) << tok::l_paren;
155 return true;
156 }
157 // Consume the ).
158 PP.LexNonComment(PeekTok);
159 Result.setEnd(PeekTok.getLocation());
160 } else {
161 // Consume identifier.
162 Result.setEnd(PeekTok.getLocation());
163 PP.LexNonComment(PeekTok);
164 }
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 if (beginLoc.isMacroID()) {
185 bool IsFunctionTypeMacro =
186 PP.getSourceManager()
187 .getSLocEntry(PP.getSourceManager().getFileID(beginLoc))
188 .getExpansion()
189 .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 if (IsFunctionTypeMacro)
206 PP.Diag(beginLoc, diag::warn_defined_in_function_type_macro);
207 else
208 PP.Diag(beginLoc, diag::warn_defined_in_object_type_macro);
209 }
210
211 // Invoke the 'defined' callback.
212 if (PPCallbacks *Callbacks = PP.getPPCallbacks()) {
213 Callbacks->Defined(macroToken, Macro,
214 SourceRange(beginLoc, PeekTok.getLocation()));
215 }
216
217 // Success, remember that we saw defined(X).
218 DT.State = DefinedTracker::DefinedMacro;
219 DT.TheMacro = II;
220 return false;
221 }
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.
EvaluateValue(PPValue & Result,Token & PeekTok,DefinedTracker & DT,bool ValueLive,Preprocessor & PP)231 static bool EvaluateValue(PPValue &Result, Token &PeekTok, DefinedTracker &DT,
232 bool ValueLive, Preprocessor &PP) {
233 DT.State = DefinedTracker::Unknown;
234
235 Result.setIdentifier(nullptr);
236
237 if (PeekTok.is(tok::code_completion)) {
238 if (PP.getCodeCompletionHandler())
239 PP.getCodeCompletionHandler()->CodeCompletePreprocessorExpression();
240 PP.setCodeCompletionReached();
241 PP.LexNonComment(PeekTok);
242 }
243
244 switch (PeekTok.getKind()) {
245 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 if (IdentifierInfo *II = PeekTok.getIdentifierInfo()) {
250 // Handle "defined X" and "defined(X)".
251 if (II->isStr("defined"))
252 return EvaluateDefined(Result, PeekTok, DT, ValueLive, PP);
253
254 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 if (ValueLive) {
259 PP.Diag(PeekTok, diag::warn_pp_undef_identifier) << II;
260
261 const DiagnosticsEngine &DiagEngine = PP.getDiagnostics();
262 // If 'Wundef' is enabled, do not emit 'undef-prefix' diagnostics.
263 if (DiagEngine.isIgnored(diag::warn_pp_undef_identifier,
264 PeekTok.getLocation())) {
265 const std::vector<std::string> UndefPrefixes =
266 DiagEngine.getDiagnosticOptions().UndefPrefixes;
267 const StringRef IdentifierName = II->getName();
268 if (llvm::any_of(UndefPrefixes,
269 [&IdentifierName](const std::string &Prefix) {
270 return IdentifierName.startswith(Prefix);
271 }))
272 PP.Diag(PeekTok, diag::warn_pp_undef_prefix)
273 << AddFlagValue{llvm::join(UndefPrefixes, ",")} << II;
274 }
275 }
276 Result.Val = 0;
277 Result.Val.setIsUnsigned(false); // "0" is signed intmax_t 0.
278 Result.setIdentifier(II);
279 Result.setRange(PeekTok.getLocation());
280 DT.IncludedUndefinedIds = true;
281 PP.LexNonComment(PeekTok);
282 return false;
283 }
284 }
285 PP.Diag(PeekTok, diag::err_pp_expr_bad_token_start_expr);
286 return true;
287 case tok::eod:
288 case tok::r_paren:
289 // If there is no expression, report and exit.
290 PP.Diag(PeekTok, diag::err_pp_expected_value_in_expr);
291 return true;
292 case tok::numeric_constant: {
293 SmallString<64> IntegerBuffer;
294 bool NumberInvalid = false;
295 StringRef Spelling = PP.getSpelling(PeekTok, IntegerBuffer,
296 &NumberInvalid);
297 if (NumberInvalid)
298 return true; // a diagnostic was already reported
299
300 NumericLiteralParser Literal(Spelling, PeekTok.getLocation(),
301 PP.getSourceManager(), PP.getLangOpts(),
302 PP.getTargetInfo(), PP.getDiagnostics());
303 if (Literal.hadError)
304 return true; // a diagnostic was already reported.
305
306 if (Literal.isFloatingLiteral() || Literal.isImaginary) {
307 PP.Diag(PeekTok, diag::err_pp_illegal_floating_literal);
308 return true;
309 }
310 assert(Literal.isIntegerLiteral() && "Unknown ppnumber");
311
312 // Complain about, and drop, any ud-suffix.
313 if (Literal.hasUDSuffix())
314 PP.Diag(PeekTok, diag::err_pp_invalid_udl) << /*integer*/1;
315
316 // 'long long' is a C99 or C++11 feature.
317 if (!PP.getLangOpts().C99 && Literal.isLongLong) {
318 if (PP.getLangOpts().CPlusPlus)
319 PP.Diag(PeekTok,
320 PP.getLangOpts().CPlusPlus11 ?
321 diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong);
322 else
323 PP.Diag(PeekTok, diag::ext_c99_longlong);
324 }
325
326 // 'z/uz' literals are a C++2b feature.
327 if (Literal.isSizeT)
328 PP.Diag(PeekTok, PP.getLangOpts().CPlusPlus
329 ? PP.getLangOpts().CPlusPlus2b
330 ? diag::warn_cxx20_compat_size_t_suffix
331 : diag::ext_cxx2b_size_t_suffix
332 : diag::err_cxx2b_size_t_suffix);
333
334 // Parse the integer literal into Result.
335 if (Literal.GetIntegerValue(Result.Val)) {
336 // Overflow parsing integer literal.
337 if (ValueLive)
338 PP.Diag(PeekTok, diag::err_integer_literal_too_large)
339 << /* Unsigned */ 1;
340 Result.Val.setIsUnsigned(true);
341 } else {
342 // Set the signedness of the result to match whether there was a U suffix
343 // or not.
344 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 if (!Literal.isUnsigned && Result.Val.isNegative()) {
351 // Octal, hexadecimal, and binary literals are implicitly unsigned if
352 // the value does not fit into a signed integer type.
353 if (ValueLive && Literal.getRadix() == 10)
354 PP.Diag(PeekTok, diag::ext_integer_literal_too_large_for_signed);
355 Result.Val.setIsUnsigned(true);
356 }
357 }
358
359 // Consume the token.
360 Result.setRange(PeekTok.getLocation());
361 PP.LexNonComment(PeekTok);
362 return false;
363 }
364 case tok::char_constant: // 'x'
365 case tok::wide_char_constant: // L'x'
366 case tok::utf8_char_constant: // u8'x'
367 case tok::utf16_char_constant: // u'x'
368 case tok::utf32_char_constant: { // U'x'
369 // Complain about, and drop, any ud-suffix.
370 if (PeekTok.hasUDSuffix())
371 PP.Diag(PeekTok, diag::err_pp_invalid_udl) << /*character*/0;
372
373 SmallString<32> CharBuffer;
374 bool CharInvalid = false;
375 StringRef ThisTok = PP.getSpelling(PeekTok, CharBuffer, &CharInvalid);
376 if (CharInvalid)
377 return true;
378
379 CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(),
380 PeekTok.getLocation(), PP, PeekTok.getKind());
381 if (Literal.hadError())
382 return true; // A diagnostic was already emitted.
383
384 // Character literals are always int or wchar_t, expand to intmax_t.
385 const TargetInfo &TI = PP.getTargetInfo();
386 unsigned NumBits;
387 if (Literal.isMultiChar())
388 NumBits = TI.getIntWidth();
389 else if (Literal.isWide())
390 NumBits = TI.getWCharWidth();
391 else if (Literal.isUTF16())
392 NumBits = TI.getChar16Width();
393 else if (Literal.isUTF32())
394 NumBits = TI.getChar32Width();
395 else // char or char8_t
396 NumBits = TI.getCharWidth();
397
398 // Set the width.
399 llvm::APSInt Val(NumBits);
400 // Set the value.
401 Val = Literal.getValue();
402 // Set the signedness. UTF-16 and UTF-32 are always unsigned
403 if (Literal.isWide())
404 Val.setIsUnsigned(!TargetInfo::isTypeSigned(TI.getWCharType()));
405 else if (!Literal.isUTF16() && !Literal.isUTF32())
406 Val.setIsUnsigned(!PP.getLangOpts().CharIsSigned);
407
408 if (Result.Val.getBitWidth() > Val.getBitWidth()) {
409 Result.Val = Val.extend(Result.Val.getBitWidth());
410 } else {
411 assert(Result.Val.getBitWidth() == Val.getBitWidth() &&
412 "intmax_t smaller than char/wchar_t?");
413 Result.Val = Val;
414 }
415
416 // Consume the token.
417 Result.setRange(PeekTok.getLocation());
418 PP.LexNonComment(PeekTok);
419 return false;
420 }
421 case tok::l_paren: {
422 SourceLocation Start = PeekTok.getLocation();
423 PP.LexNonComment(PeekTok); // Eat the (.
424 // Parse the value and if there are any binary operators involved, parse
425 // them.
426 if (EvaluateValue(Result, PeekTok, DT, ValueLive, PP)) return true;
427
428 // If this is a silly value like (X), which doesn't need parens, check for
429 // !(defined X).
430 if (PeekTok.is(tok::r_paren)) {
431 // Just use DT unmodified as our result.
432 } else {
433 // Otherwise, we have something like (x+y), and we consumed '(x'.
434 if (EvaluateDirectiveSubExpr(Result, 1, PeekTok, ValueLive,
435 DT.IncludedUndefinedIds, PP))
436 return true;
437
438 if (PeekTok.isNot(tok::r_paren)) {
439 PP.Diag(PeekTok.getLocation(), diag::err_pp_expected_rparen)
440 << Result.getRange();
441 PP.Diag(Start, diag::note_matching) << tok::l_paren;
442 return true;
443 }
444 DT.State = DefinedTracker::Unknown;
445 }
446 Result.setRange(Start, PeekTok.getLocation());
447 Result.setIdentifier(nullptr);
448 PP.LexNonComment(PeekTok); // Eat the ).
449 return false;
450 }
451 case tok::plus: {
452 SourceLocation Start = PeekTok.getLocation();
453 // Unary plus doesn't modify the value.
454 PP.LexNonComment(PeekTok);
455 if (EvaluateValue(Result, PeekTok, DT, ValueLive, PP)) return true;
456 Result.setBegin(Start);
457 Result.setIdentifier(nullptr);
458 return false;
459 }
460 case tok::minus: {
461 SourceLocation Loc = PeekTok.getLocation();
462 PP.LexNonComment(PeekTok);
463 if (EvaluateValue(Result, PeekTok, DT, ValueLive, PP)) return true;
464 Result.setBegin(Loc);
465 Result.setIdentifier(nullptr);
466
467 // C99 6.5.3.3p3: The sign of the result matches the sign of the operand.
468 Result.Val = -Result.Val;
469
470 // -MININT is the only thing that overflows. Unsigned never overflows.
471 bool Overflow = !Result.isUnsigned() && Result.Val.isMinSignedValue();
472
473 // If this operator is live and overflowed, report the issue.
474 if (Overflow && ValueLive)
475 PP.Diag(Loc, diag::warn_pp_expr_overflow) << Result.getRange();
476
477 DT.State = DefinedTracker::Unknown;
478 return false;
479 }
480
481 case tok::tilde: {
482 SourceLocation Start = PeekTok.getLocation();
483 PP.LexNonComment(PeekTok);
484 if (EvaluateValue(Result, PeekTok, DT, ValueLive, PP)) return true;
485 Result.setBegin(Start);
486 Result.setIdentifier(nullptr);
487
488 // C99 6.5.3.3p4: The sign of the result matches the sign of the operand.
489 Result.Val = ~Result.Val;
490 DT.State = DefinedTracker::Unknown;
491 return false;
492 }
493
494 case tok::exclaim: {
495 SourceLocation Start = PeekTok.getLocation();
496 PP.LexNonComment(PeekTok);
497 if (EvaluateValue(Result, PeekTok, DT, ValueLive, PP)) return true;
498 Result.setBegin(Start);
499 Result.Val = !Result.Val;
500 // C99 6.5.3.3p5: The sign of the result is 'int', aka it is signed.
501 Result.Val.setIsUnsigned(false);
502 Result.setIdentifier(nullptr);
503
504 if (DT.State == DefinedTracker::DefinedMacro)
505 DT.State = DefinedTracker::NotDefinedMacro;
506 else if (DT.State == DefinedTracker::NotDefinedMacro)
507 DT.State = DefinedTracker::DefinedMacro;
508 return false;
509 }
510 case tok::kw_true:
511 case tok::kw_false:
512 Result.Val = PeekTok.getKind() == tok::kw_true;
513 Result.Val.setIsUnsigned(false); // "0" is signed intmax_t 0.
514 Result.setIdentifier(PeekTok.getIdentifierInfo());
515 Result.setRange(PeekTok.getLocation());
516 PP.LexNonComment(PeekTok);
517 return false;
518
519 // FIXME: Handle #assert
520 }
521 }
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 ')'
getPrecedence(tok::TokenKind Kind)528 static unsigned getPrecedence(tok::TokenKind Kind) {
529 switch (Kind) {
530 default: return ~0U;
531 case tok::percent:
532 case tok::slash:
533 case tok::star: return 14;
534 case tok::plus:
535 case tok::minus: return 13;
536 case tok::lessless:
537 case tok::greatergreater: return 12;
538 case tok::lessequal:
539 case tok::less:
540 case tok::greaterequal:
541 case tok::greater: return 11;
542 case tok::exclaimequal:
543 case tok::equalequal: return 10;
544 case tok::amp: return 9;
545 case tok::caret: return 8;
546 case tok::pipe: return 7;
547 case tok::ampamp: return 6;
548 case tok::pipepipe: return 5;
549 case tok::question: return 4;
550 case tok::comma: return 3;
551 case tok::colon: return 2;
552 case tok::r_paren: return 0;// Lowest priority, end of expr.
553 case tok::eod: return 0;// Lowest priority, end of directive.
554 }
555 }
556
diagnoseUnexpectedOperator(Preprocessor & PP,PPValue & LHS,Token & Tok)557 static void diagnoseUnexpectedOperator(Preprocessor &PP, PPValue &LHS,
558 Token &Tok) {
559 if (Tok.is(tok::l_paren) && LHS.getIdentifier())
560 PP.Diag(LHS.getRange().getBegin(), diag::err_pp_expr_bad_token_lparen)
561 << LHS.getIdentifier();
562 else
563 PP.Diag(Tok.getLocation(), diag::err_pp_expr_bad_token_binop)
564 << LHS.getRange();
565 }
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.
EvaluateDirectiveSubExpr(PPValue & LHS,unsigned MinPrec,Token & PeekTok,bool ValueLive,bool & IncludedUndefinedIds,Preprocessor & PP)573 static bool EvaluateDirectiveSubExpr(PPValue &LHS, unsigned MinPrec,
574 Token &PeekTok, bool ValueLive,
575 bool &IncludedUndefinedIds,
576 Preprocessor &PP) {
577 unsigned PeekPrec = getPrecedence(PeekTok.getKind());
578 // If this token isn't valid, report the error.
579 if (PeekPrec == ~0U) {
580 diagnoseUnexpectedOperator(PP, LHS, PeekTok);
581 return true;
582 }
583
584 while (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 if (PeekPrec < MinPrec)
588 return false;
589
590 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 bool RHSIsLive;
598 if (Operator == tok::ampamp && LHS.Val == 0)
599 RHSIsLive = false; // RHS of "0 && x" is dead.
600 else if (Operator == tok::pipepipe && LHS.Val != 0)
601 RHSIsLive = false; // RHS of "1 || x" is dead.
602 else if (Operator == tok::question && LHS.Val == 0)
603 RHSIsLive = false; // RHS (x) of "0 ? x : y" is dead.
604 else
605 RHSIsLive = ValueLive;
606
607 // Consume the operator, remembering the operator's location for reporting.
608 SourceLocation OpLoc = PeekTok.getLocation();
609 PP.LexNonComment(PeekTok);
610
611 PPValue RHS(LHS.getBitWidth());
612 // Parse the RHS of the operator.
613 DefinedTracker DT;
614 if (EvaluateValue(RHS, PeekTok, DT, RHSIsLive, PP)) return true;
615 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 unsigned ThisPrec = PeekPrec;
620 PeekPrec = getPrecedence(PeekTok.getKind());
621
622 // If this token isn't valid, report the error.
623 if (PeekPrec == ~0U) {
624 diagnoseUnexpectedOperator(PP, RHS, PeekTok);
625 return true;
626 }
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 unsigned RHSPrec;
639 if (Operator == tok::question)
640 // The RHS of "?" should be maximally consumed as an expression.
641 RHSPrec = getPrecedence(tok::comma);
642 else // All others should munch while higher precedence.
643 RHSPrec = ThisPrec+1;
644
645 if (PeekPrec >= RHSPrec) {
646 if (EvaluateDirectiveSubExpr(RHS, RHSPrec, PeekTok, RHSIsLive,
647 IncludedUndefinedIds, PP))
648 return true;
649 PeekPrec = getPrecedence(PeekTok.getKind());
650 }
651 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 llvm::APSInt Res(LHS.getBitWidth());
656 switch (Operator) {
657 case tok::question: // No UAC for x and y in "x ? y : z".
658 case tok::lessless: // Shift amount doesn't UAC with shift value.
659 case tok::greatergreater: // Shift amount doesn't UAC with shift value.
660 case tok::comma: // Comma operands are not subject to UACs.
661 case tok::pipepipe: // Logical || does not do UACs.
662 case tok::ampamp: // Logical && does not do UACs.
663 break; // No UAC
664 default:
665 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 if (ValueLive && Res.isUnsigned()) {
669 if (!LHS.isUnsigned() && LHS.Val.isNegative())
670 PP.Diag(OpLoc, diag::warn_pp_convert_to_positive) << 0
671 << toString(LHS.Val, 10, true) + " to " +
672 toString(LHS.Val, 10, false)
673 << LHS.getRange() << RHS.getRange();
674 if (!RHS.isUnsigned() && RHS.Val.isNegative())
675 PP.Diag(OpLoc, diag::warn_pp_convert_to_positive) << 1
676 << toString(RHS.Val, 10, true) + " to " +
677 toString(RHS.Val, 10, false)
678 << LHS.getRange() << RHS.getRange();
679 }
680 LHS.Val.setIsUnsigned(Res.isUnsigned());
681 RHS.Val.setIsUnsigned(Res.isUnsigned());
682 }
683
684 bool Overflow = false;
685 switch (Operator) {
686 default: llvm_unreachable("Unknown operator token!");
687 case tok::percent:
688 if (RHS.Val != 0)
689 Res = LHS.Val % RHS.Val;
690 else if (ValueLive) {
691 PP.Diag(OpLoc, diag::err_pp_remainder_by_zero)
692 << LHS.getRange() << RHS.getRange();
693 return true;
694 }
695 break;
696 case tok::slash:
697 if (RHS.Val != 0) {
698 if (LHS.Val.isSigned())
699 Res = llvm::APSInt(LHS.Val.sdiv_ov(RHS.Val, Overflow), false);
700 else
701 Res = LHS.Val / RHS.Val;
702 } else if (ValueLive) {
703 PP.Diag(OpLoc, diag::err_pp_division_by_zero)
704 << LHS.getRange() << RHS.getRange();
705 return true;
706 }
707 break;
708
709 case tok::star:
710 if (Res.isSigned())
711 Res = llvm::APSInt(LHS.Val.smul_ov(RHS.Val, Overflow), false);
712 else
713 Res = LHS.Val * RHS.Val;
714 break;
715 case tok::lessless: {
716 // Determine whether overflow is about to happen.
717 if (LHS.isUnsigned())
718 Res = LHS.Val.ushl_ov(RHS.Val, Overflow);
719 else
720 Res = llvm::APSInt(LHS.Val.sshl_ov(RHS.Val, Overflow), false);
721 break;
722 }
723 case tok::greatergreater: {
724 // Determine whether overflow is about to happen.
725 unsigned ShAmt = static_cast<unsigned>(RHS.Val.getLimitedValue());
726 if (ShAmt >= LHS.getBitWidth()) {
727 Overflow = true;
728 ShAmt = LHS.getBitWidth()-1;
729 }
730 Res = LHS.Val >> ShAmt;
731 break;
732 }
733 case tok::plus:
734 if (LHS.isUnsigned())
735 Res = LHS.Val + RHS.Val;
736 else
737 Res = llvm::APSInt(LHS.Val.sadd_ov(RHS.Val, Overflow), false);
738 break;
739 case tok::minus:
740 if (LHS.isUnsigned())
741 Res = LHS.Val - RHS.Val;
742 else
743 Res = llvm::APSInt(LHS.Val.ssub_ov(RHS.Val, Overflow), false);
744 break;
745 case tok::lessequal:
746 Res = LHS.Val <= RHS.Val;
747 Res.setIsUnsigned(false); // C99 6.5.8p6, result is always int (signed)
748 break;
749 case tok::less:
750 Res = LHS.Val < RHS.Val;
751 Res.setIsUnsigned(false); // C99 6.5.8p6, result is always int (signed)
752 break;
753 case tok::greaterequal:
754 Res = LHS.Val >= RHS.Val;
755 Res.setIsUnsigned(false); // C99 6.5.8p6, result is always int (signed)
756 break;
757 case tok::greater:
758 Res = LHS.Val > RHS.Val;
759 Res.setIsUnsigned(false); // C99 6.5.8p6, result is always int (signed)
760 break;
761 case tok::exclaimequal:
762 Res = LHS.Val != RHS.Val;
763 Res.setIsUnsigned(false); // C99 6.5.9p3, result is always int (signed)
764 break;
765 case tok::equalequal:
766 Res = LHS.Val == RHS.Val;
767 Res.setIsUnsigned(false); // C99 6.5.9p3, result is always int (signed)
768 break;
769 case tok::amp:
770 Res = LHS.Val & RHS.Val;
771 break;
772 case tok::caret:
773 Res = LHS.Val ^ RHS.Val;
774 break;
775 case tok::pipe:
776 Res = LHS.Val | RHS.Val;
777 break;
778 case tok::ampamp:
779 Res = (LHS.Val != 0 && RHS.Val != 0);
780 Res.setIsUnsigned(false); // C99 6.5.13p3, result is always int (signed)
781 break;
782 case tok::pipepipe:
783 Res = (LHS.Val != 0 || RHS.Val != 0);
784 Res.setIsUnsigned(false); // C99 6.5.14p3, result is always int (signed)
785 break;
786 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 if (!PP.getLangOpts().C99 || ValueLive)
790 PP.Diag(OpLoc, diag::ext_pp_comma_expr)
791 << LHS.getRange() << RHS.getRange();
792 Res = RHS.Val; // LHS = LHS,RHS -> RHS.
793 break;
794 case tok::question: {
795 // Parse the : part of the expression.
796 if (PeekTok.isNot(tok::colon)) {
797 PP.Diag(PeekTok.getLocation(), diag::err_expected)
798 << tok::colon << LHS.getRange() << RHS.getRange();
799 PP.Diag(OpLoc, diag::note_matching) << tok::question;
800 return true;
801 }
802 // Consume the :.
803 PP.LexNonComment(PeekTok);
804
805 // Evaluate the value after the :.
806 bool AfterColonLive = ValueLive && LHS.Val == 0;
807 PPValue AfterColonVal(LHS.getBitWidth());
808 DefinedTracker DT;
809 if (EvaluateValue(AfterColonVal, PeekTok, DT, AfterColonLive, PP))
810 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 if (EvaluateDirectiveSubExpr(AfterColonVal, ThisPrec,
815 PeekTok, AfterColonLive,
816 IncludedUndefinedIds, PP))
817 return true;
818
819 // Now that we have the condition, the LHS and the RHS of the :, evaluate.
820 Res = LHS.Val != 0 ? RHS.Val : AfterColonVal.Val;
821 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 Res.setIsUnsigned(RHS.isUnsigned() || AfterColonVal.isUnsigned());
826
827 // Figure out the precedence of the token after the : part.
828 PeekPrec = getPrecedence(PeekTok.getKind());
829 break;
830 }
831 case tok::colon:
832 // Don't allow :'s to float around without being part of ?: exprs.
833 PP.Diag(OpLoc, diag::err_pp_colon_without_question)
834 << LHS.getRange() << RHS.getRange();
835 return true;
836 }
837
838 // If this operator is live and overflowed, report the issue.
839 if (Overflow && ValueLive)
840 PP.Diag(OpLoc, diag::warn_pp_expr_overflow)
841 << LHS.getRange() << RHS.getRange();
842
843 // Put the result back into 'LHS' for our next iteration.
844 LHS.Val = Res;
845 LHS.setEnd(RHS.getRange().getEnd());
846 RHS.setIdentifier(nullptr);
847 }
848 }
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
EvaluateDirectiveExpression(IdentifierInfo * & IfNDefMacro)854 Preprocessor::EvaluateDirectiveExpression(IdentifierInfo *&IfNDefMacro) {
855 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 bool DisableMacroExpansionAtStartOfDirective = DisableMacroExpansion;
863 DisableMacroExpansion = false;
864
865 // Peek ahead one token.
866 Token Tok;
867 LexNonComment(Tok);
868
869 // C99 6.10.1p3 - All expressions are evaluated as intmax_t or uintmax_t.
870 unsigned BitWidth = getTargetInfo().getIntMaxTWidth();
871
872 PPValue ResVal(BitWidth);
873 DefinedTracker DT;
874 SourceLocation ExprStartLoc = SourceMgr.getExpansionLoc(Tok.getLocation());
875 if (EvaluateValue(ResVal, Tok, DT, true, *this)) {
876 // Parse error, skip the rest of the macro line.
877 SourceRange ConditionRange = ExprStartLoc;
878 if (Tok.isNot(tok::eod))
879 ConditionRange = DiscardUntilEndOfDirective();
880
881 // Restore 'DisableMacroExpansion'.
882 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 return {false,
888 DT.IncludedUndefinedIds,
889 {ExprStartLoc, ConditionRange.getEnd()}};
890 }
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 if (Tok.is(tok::eod)) {
896 // If the expression we parsed was of the form !defined(macro), return the
897 // macro in IfNDefMacro.
898 if (DT.State == DefinedTracker::NotDefinedMacro)
899 IfNDefMacro = DT.TheMacro;
900
901 // Restore 'DisableMacroExpansion'.
902 DisableMacroExpansion = DisableMacroExpansionAtStartOfDirective;
903 return {ResVal.Val != 0, DT.IncludedUndefinedIds, ResVal.getRange()};
904 }
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 if (EvaluateDirectiveSubExpr(ResVal, getPrecedence(tok::question),
909 Tok, true, DT.IncludedUndefinedIds, *this)) {
910 // Parse error, skip the rest of the macro line.
911 if (Tok.isNot(tok::eod))
912 DiscardUntilEndOfDirective();
913
914 // Restore 'DisableMacroExpansion'.
915 DisableMacroExpansion = DisableMacroExpansionAtStartOfDirective;
916 return {false, DT.IncludedUndefinedIds, ResVal.getRange()};
917 }
918
919 // If we aren't at the tok::eod token, something bad happened, like an extra
920 // ')' token.
921 if (Tok.isNot(tok::eod)) {
922 Diag(Tok, diag::err_pp_expected_eol);
923 DiscardUntilEndOfDirective();
924 }
925
926 // Restore 'DisableMacroExpansion'.
927 DisableMacroExpansion = DisableMacroExpansionAtStartOfDirective;
928 return {ResVal.Val != 0, DT.IncludedUndefinedIds, ResVal.getRange()};
929 }
930