clang 22.0.0git
PPExpressions.cpp
Go to the documentation of this file.
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
26#include "clang/Lex/MacroInfo.h"
30#include "clang/Lex/Token.h"
31#include "llvm/ADT/APSInt.h"
32#include "llvm/ADT/STLExtras.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
39using namespace clang;
40
41namespace {
42
43/// PPValue - Represents the value of a subexpression of a preprocessor
44/// conditional and the source range covered by it.
45class PPValue {
46 SourceRange Range;
47 IdentifierInfo *II = nullptr;
48
49public:
50 llvm::APSInt Val;
51
52 // Default ctor - Construct an 'invalid' PPValue.
53 PPValue(unsigned BitWidth) : Val(BitWidth) {}
54
55 // If this value was produced by directly evaluating an identifier, produce
56 // that identifier.
57 IdentifierInfo *getIdentifier() const { return II; }
58 void setIdentifier(IdentifierInfo *II) { this->II = II; }
59
60 unsigned getBitWidth() const { return Val.getBitWidth(); }
61 bool isUnsigned() const { return Val.isUnsigned(); }
62
63 SourceRange getRange() const { return Range; }
64
65 void setRange(SourceLocation L) { Range.setBegin(L); Range.setEnd(L); }
66 void setRange(SourceLocation B, SourceLocation E) {
67 Range.setBegin(B); Range.setEnd(E);
68 }
69 void setBegin(SourceLocation L) { Range.setBegin(L); }
70 void setEnd(SourceLocation L) { Range.setEnd(L); }
71};
72
73} // end anonymous namespace
74
75static 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)).
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.
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.
99};
100
101/// EvaluateDefined - Process a 'defined(sym)' expression.
102static 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)) {
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();
132 Result.Val = !!Macro;
133 Result.Val.setIsUnsigned(false); // Result is signed intmax_t.
135
137 PeekTok,
138 (II->getName() == "INFINITY" || II->getName() == "NAN") ? true : false);
139
140 // If there is a macro, mark it used.
141 if (Result.Val != 0 && ValueLive)
142 PP.markMacroAsUsed(Macro.getMacroInfo());
143
144 // Save macro token for callback.
145 Token macroToken(PeekTok);
146
147 // If we are in parens, ensure we have a trailing ).
148 if (LParenLoc.isValid()) {
149 // Consume identifier.
150 Result.setEnd(PeekTok.getLocation());
151 PP.LexUnexpandedNonComment(PeekTok);
152
153 if (PeekTok.isNot(tok::r_paren)) {
154 PP.Diag(PeekTok.getLocation(), diag::err_pp_expected_after)
155 << "'defined'" << tok::r_paren;
156 PP.Diag(LParenLoc, diag::note_matching) << tok::l_paren;
157 return true;
158 }
159 // Consume the ).
160 PP.LexNonComment(PeekTok);
161 Result.setEnd(PeekTok.getLocation());
162 } else {
163 // Consume identifier.
164 Result.setEnd(PeekTok.getLocation());
165 PP.LexNonComment(PeekTok);
166 }
167
168 // [cpp.cond]p4:
169 // Prior to evaluation, macro invocations in the list of preprocessing
170 // tokens that will become the controlling constant expression are replaced
171 // (except for those macro names modified by the 'defined' unary operator),
172 // just as in normal text. If the token 'defined' is generated as a result
173 // of this replacement process or use of the 'defined' unary operator does
174 // not match one of the two specified forms prior to macro replacement, the
175 // behavior is undefined.
176 // This isn't an idle threat, consider this program:
177 // #define FOO
178 // #define BAR defined(FOO)
179 // #if BAR
180 // ...
181 // #else
182 // ...
183 // #endif
184 // clang and gcc will pick the #if branch while Visual Studio will take the
185 // #else branch. Emit a warning about this undefined behavior.
186 if (beginLoc.isMacroID()) {
187 bool IsFunctionTypeMacro =
190 .getExpansion()
192 // For object-type macros, it's easy to replace
193 // #define FOO defined(BAR)
194 // with
195 // #if defined(BAR)
196 // #define FOO 1
197 // #else
198 // #define FOO 0
199 // #endif
200 // and doing so makes sense since compilers handle this differently in
201 // practice (see example further up). But for function-type macros,
202 // there is no good way to write
203 // # define FOO(x) (defined(M_ ## x) && M_ ## x)
204 // in a different way, and compilers seem to agree on how to behave here.
205 // So warn by default on object-type macros, but only warn in -pedantic
206 // mode on function-type macros.
207 if (IsFunctionTypeMacro)
208 PP.Diag(beginLoc, diag::warn_defined_in_function_type_macro);
209 else
210 PP.Diag(beginLoc, diag::warn_defined_in_object_type_macro);
211 }
212
213 // Invoke the 'defined' callback.
214 if (PPCallbacks *Callbacks = PP.getPPCallbacks()) {
215 Callbacks->Defined(macroToken, Macro,
216 SourceRange(beginLoc, PeekTok.getLocation()));
217 }
218
219 // Success, remember that we saw defined(X).
221 DT.TheMacro = II;
222 return false;
223}
224
225/// EvaluateValue - Evaluate the token PeekTok (and any others needed) and
226/// return the computed value in Result. Return true if there was an error
227/// parsing. This function also returns information about the form of the
228/// expression in DT. See above for information on what DT means.
229///
230/// If ValueLive is false, then this value is being evaluated in a context where
231/// the result is not used. As such, avoid diagnostics that relate to
232/// evaluation.
233static bool EvaluateValue(PPValue &Result, Token &PeekTok, DefinedTracker &DT,
234 bool ValueLive, Preprocessor &PP) {
236
237 Result.setIdentifier(nullptr);
238
239 if (PeekTok.is(tok::code_completion)) {
243 PP.LexNonComment(PeekTok);
244 }
245
246 switch (PeekTok.getKind()) {
247 default:
248 // If this token's spelling is a pp-identifier, check to see if it is
249 // 'defined' or if it is a macro. Note that we check here because many
250 // keywords are pp-identifiers, so we can't check the kind.
251 if (IdentifierInfo *II = PeekTok.getIdentifierInfo()) {
252 // Handle "defined X" and "defined(X)".
253 if (II->isStr("defined"))
254 return EvaluateDefined(Result, PeekTok, DT, ValueLive, PP);
255
256 if (!II->isCPlusPlusOperatorKeyword()) {
257 // If this identifier isn't 'defined' or one of the special
258 // preprocessor keywords and it wasn't macro expanded, it turns
259 // into a simple 0
260 if (ValueLive) {
261 unsigned DiagID = II->getName() == "true"
262 ? diag::warn_pp_undef_true_identifier
263 : diag::warn_pp_undef_identifier;
264 PP.Diag(PeekTok, DiagID) << II;
265
266 const DiagnosticsEngine &DiagEngine = PP.getDiagnostics();
267 // If 'Wundef' is enabled, do not emit 'undef-prefix' diagnostics.
268 if (DiagEngine.isIgnored(DiagID, PeekTok.getLocation())) {
269 const std::vector<std::string> UndefPrefixes =
271 const StringRef IdentifierName = II->getName();
272 if (llvm::any_of(UndefPrefixes,
273 [&IdentifierName](const std::string &Prefix) {
274 return IdentifierName.starts_with(Prefix);
275 }))
276 PP.Diag(PeekTok, diag::warn_pp_undef_prefix)
277 << AddFlagValue{llvm::join(UndefPrefixes, ",")} << II;
278 }
279 }
280 Result.Val = 0;
281 Result.Val.setIsUnsigned(false); // "0" is signed intmax_t 0.
282 Result.setIdentifier(II);
283 Result.setRange(PeekTok.getLocation());
284 DT.IncludedUndefinedIds = true;
285 PP.LexNonComment(PeekTok);
286 return false;
287 }
288 }
289 PP.Diag(PeekTok, diag::err_pp_expr_bad_token_start_expr);
290 return true;
291 case tok::eod:
292 case tok::r_paren:
293 // If there is no expression, report and exit.
294 PP.Diag(PeekTok, diag::err_pp_expected_value_in_expr);
295 return true;
296 case tok::numeric_constant: {
297 SmallString<64> IntegerBuffer;
298 bool NumberInvalid = false;
299 StringRef Spelling = PP.getSpelling(PeekTok, IntegerBuffer,
300 &NumberInvalid);
301 if (NumberInvalid)
302 return true; // a diagnostic was already reported
303
304 NumericLiteralParser Literal(Spelling, PeekTok.getLocation(),
305 PP.getSourceManager(), PP.getLangOpts(),
306 PP.getTargetInfo(), PP.getDiagnostics());
307 if (Literal.hadError)
308 return true; // a diagnostic was already reported.
309
310 if (Literal.isFloatingLiteral() || Literal.isImaginary) {
311 PP.Diag(PeekTok, diag::err_pp_illegal_floating_literal);
312 return true;
313 }
314 assert(Literal.isIntegerLiteral() && "Unknown ppnumber");
315
316 // Complain about, and drop, any ud-suffix.
317 if (Literal.hasUDSuffix())
318 PP.Diag(PeekTok, diag::err_pp_invalid_udl) << /*integer*/1;
319
320 // 'long long' is a C99 or C++11 feature.
321 if (!PP.getLangOpts().C99 && Literal.isLongLong) {
322 if (PP.getLangOpts().CPlusPlus)
323 PP.Diag(PeekTok,
324 PP.getLangOpts().CPlusPlus11 ?
325 diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong);
326 else
327 PP.Diag(PeekTok, diag::ext_c99_longlong);
328 }
329
330 // 'z/uz' literals are a C++23 feature.
331 if (Literal.isSizeT)
332 PP.Diag(PeekTok, PP.getLangOpts().CPlusPlus
333 ? PP.getLangOpts().CPlusPlus23
334 ? diag::warn_cxx20_compat_size_t_suffix
335 : diag::ext_cxx23_size_t_suffix
336 : diag::err_cxx23_size_t_suffix);
337
338 // 'wb/uwb' literals are a C23 feature.
339 // '__wb/__uwb' are a C++ extension.
340 if (Literal.isBitInt)
341 PP.Diag(PeekTok, PP.getLangOpts().CPlusPlus ? diag::ext_cxx_bitint_suffix
342 : PP.getLangOpts().C23
343 ? diag::warn_c23_compat_bitint_suffix
344 : diag::ext_c23_bitint_suffix);
345
346 // Parse the integer literal into Result.
347 if (Literal.GetIntegerValue(Result.Val)) {
348 // Overflow parsing integer literal.
349 PP.Diag(PeekTok, diag::err_integer_literal_too_large) << /* Unsigned */ 1;
350 Result.Val.setIsUnsigned(true);
351 } else {
352 // Set the signedness of the result to match whether there was a U suffix
353 // or not.
354 Result.Val.setIsUnsigned(Literal.isUnsigned);
355
356 // Detect overflow based on whether the value is signed. If signed
357 // and if the value is too large, emit a warning "integer constant is so
358 // large that it is unsigned" e.g. on 12345678901234567890 where intmax_t
359 // is 64-bits.
360 if (!Literal.isUnsigned && Result.Val.isNegative()) {
361 // Octal, hexadecimal, and binary literals are implicitly unsigned if
362 // the value does not fit into a signed integer type.
363 if (ValueLive && Literal.getRadix() == 10)
364 PP.Diag(PeekTok, diag::ext_integer_literal_too_large_for_signed);
365 Result.Val.setIsUnsigned(true);
366 }
367 }
368
369 // Consume the token.
370 Result.setRange(PeekTok.getLocation());
371 PP.LexNonComment(PeekTok);
372 return false;
373 }
374 case tok::char_constant: // 'x'
375 case tok::wide_char_constant: // L'x'
376 case tok::utf8_char_constant: // u8'x'
377 case tok::utf16_char_constant: // u'x'
378 case tok::utf32_char_constant: { // U'x'
379 // Complain about, and drop, any ud-suffix.
380 if (PeekTok.hasUDSuffix())
381 PP.Diag(PeekTok, diag::err_pp_invalid_udl) << /*character*/0;
382
383 SmallString<32> CharBuffer;
384 bool CharInvalid = false;
385 StringRef ThisTok = PP.getSpelling(PeekTok, CharBuffer, &CharInvalid);
386 if (CharInvalid)
387 return true;
388
389 CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(),
390 PeekTok.getLocation(), PP, PeekTok.getKind());
391 if (Literal.hadError())
392 return true; // A diagnostic was already emitted.
393
394 // Character literals are always int or wchar_t, expand to intmax_t.
395 const TargetInfo &TI = PP.getTargetInfo();
396 unsigned NumBits;
397 if (Literal.isMultiChar())
398 NumBits = TI.getIntWidth();
399 else if (Literal.isWide())
400 NumBits = TI.getWCharWidth();
401 else if (Literal.isUTF16())
402 NumBits = TI.getChar16Width();
403 else if (Literal.isUTF32())
404 NumBits = TI.getChar32Width();
405 else // char or char8_t
406 NumBits = TI.getCharWidth();
407
408 // Set the width.
409 llvm::APSInt Val(NumBits);
410 // Set the value.
411 Val = Literal.getValue();
412 // Set the signedness. UTF-16 and UTF-32 are always unsigned
413 // UTF-8 is unsigned if -fchar8_t is specified.
414 if (Literal.isWide())
415 Val.setIsUnsigned(!TargetInfo::isTypeSigned(TI.getWCharType()));
416 else if (Literal.isUTF16() || Literal.isUTF32())
417 Val.setIsUnsigned(true);
418 else if (Literal.isUTF8()) {
419 if (PP.getLangOpts().CPlusPlus)
420 Val.setIsUnsigned(
421 PP.getLangOpts().Char8 ? true : !PP.getLangOpts().CharIsSigned);
422 else
423 Val.setIsUnsigned(true);
424 } else
425 Val.setIsUnsigned(!PP.getLangOpts().CharIsSigned);
426
427 if (Result.Val.getBitWidth() > Val.getBitWidth()) {
428 Result.Val = Val.extend(Result.Val.getBitWidth());
429 } else {
430 assert(Result.Val.getBitWidth() == Val.getBitWidth() &&
431 "intmax_t smaller than char/wchar_t?");
432 Result.Val = Val;
433 }
434
435 // Consume the token.
436 Result.setRange(PeekTok.getLocation());
437 PP.LexNonComment(PeekTok);
438 return false;
439 }
440 case tok::l_paren: {
441 SourceLocation Start = PeekTok.getLocation();
442 PP.LexNonComment(PeekTok); // Eat the (.
443 // Parse the value and if there are any binary operators involved, parse
444 // them.
445 if (EvaluateValue(Result, PeekTok, DT, ValueLive, PP)) return true;
446
447 // If this is a silly value like (X), which doesn't need parens, check for
448 // !(defined X).
449 if (PeekTok.is(tok::r_paren)) {
450 // Just use DT unmodified as our result.
451 } else {
452 // Otherwise, we have something like (x+y), and we consumed '(x'.
453 if (EvaluateDirectiveSubExpr(Result, 1, PeekTok, ValueLive,
454 DT.IncludedUndefinedIds, PP))
455 return true;
456
457 if (PeekTok.isNot(tok::r_paren)) {
458 PP.Diag(PeekTok.getLocation(), diag::err_pp_expected_rparen)
459 << Result.getRange();
460 PP.Diag(Start, diag::note_matching) << tok::l_paren;
461 return true;
462 }
464 }
465 Result.setRange(Start, PeekTok.getLocation());
466 Result.setIdentifier(nullptr);
467 PP.LexNonComment(PeekTok); // Eat the ).
468 return false;
469 }
470 case tok::plus: {
471 SourceLocation Start = PeekTok.getLocation();
472 // Unary plus doesn't modify the value.
473 PP.LexNonComment(PeekTok);
474 if (EvaluateValue(Result, PeekTok, DT, ValueLive, PP)) return true;
475 Result.setBegin(Start);
476 Result.setIdentifier(nullptr);
477 return false;
478 }
479 case tok::minus: {
480 SourceLocation Loc = PeekTok.getLocation();
481 PP.LexNonComment(PeekTok);
482 if (EvaluateValue(Result, PeekTok, DT, ValueLive, PP)) return true;
483 Result.setBegin(Loc);
484 Result.setIdentifier(nullptr);
485
486 // C99 6.5.3.3p3: The sign of the result matches the sign of the operand.
487 Result.Val = -Result.Val;
488
489 // -MININT is the only thing that overflows. Unsigned never overflows.
490 bool Overflow = !Result.isUnsigned() && Result.Val.isMinSignedValue();
491
492 // If this operator is live and overflowed, report the issue.
493 if (Overflow && ValueLive)
494 PP.Diag(Loc, diag::warn_pp_expr_overflow) << Result.getRange();
495
497 return false;
498 }
499
500 case tok::tilde: {
501 SourceLocation Start = PeekTok.getLocation();
502 PP.LexNonComment(PeekTok);
503 if (EvaluateValue(Result, PeekTok, DT, ValueLive, PP)) return true;
504 Result.setBegin(Start);
505 Result.setIdentifier(nullptr);
506
507 // C99 6.5.3.3p4: The sign of the result matches the sign of the operand.
508 Result.Val = ~Result.Val;
510 return false;
511 }
512
513 case tok::exclaim: {
514 SourceLocation Start = PeekTok.getLocation();
515 PP.LexNonComment(PeekTok);
516 if (EvaluateValue(Result, PeekTok, DT, ValueLive, PP)) return true;
517 Result.setBegin(Start);
518 Result.Val = !Result.Val;
519 // C99 6.5.3.3p5: The sign of the result is 'int', aka it is signed.
520 Result.Val.setIsUnsigned(false);
521 Result.setIdentifier(nullptr);
522
527 return false;
528 }
529 case tok::kw_true:
530 case tok::kw_false:
531 Result.Val = PeekTok.getKind() == tok::kw_true;
532 Result.Val.setIsUnsigned(false); // "0" is signed intmax_t 0.
533 Result.setIdentifier(PeekTok.getIdentifierInfo());
534 Result.setRange(PeekTok.getLocation());
535 PP.LexNonComment(PeekTok);
536 return false;
537
538 // FIXME: Handle #assert
539 }
540}
541
542/// getPrecedence - Return the precedence of the specified binary operator
543/// token. This returns:
544/// ~0 - Invalid token.
545/// 14 -> 3 - various operators.
546/// 0 - 'eod' or ')'
547static unsigned getPrecedence(tok::TokenKind Kind) {
548 switch (Kind) {
549 default: return ~0U;
550 case tok::percent:
551 case tok::slash:
552 case tok::star: return 14;
553 case tok::plus:
554 case tok::minus: return 13;
555 case tok::lessless:
556 case tok::greatergreater: return 12;
557 case tok::lessequal:
558 case tok::less:
559 case tok::greaterequal:
560 case tok::greater: return 11;
561 case tok::exclaimequal:
562 case tok::equalequal: return 10;
563 case tok::amp: return 9;
564 case tok::caret: return 8;
565 case tok::pipe: return 7;
566 case tok::ampamp: return 6;
567 case tok::pipepipe: return 5;
568 case tok::question: return 4;
569 case tok::comma: return 3;
570 case tok::colon: return 2;
571 case tok::r_paren: return 0;// Lowest priority, end of expr.
572 case tok::eod: return 0;// Lowest priority, end of directive.
573 }
574}
575
576static void diagnoseUnexpectedOperator(Preprocessor &PP, PPValue &LHS,
577 Token &Tok) {
578 if (Tok.is(tok::l_paren) && LHS.getIdentifier())
579 PP.Diag(LHS.getRange().getBegin(), diag::err_pp_expr_bad_token_lparen)
580 << LHS.getIdentifier();
581 else
582 PP.Diag(Tok.getLocation(), diag::err_pp_expr_bad_token_binop)
583 << LHS.getRange();
584}
585
586/// EvaluateDirectiveSubExpr - Evaluate the subexpression whose first token is
587/// PeekTok, and whose precedence is PeekPrec. This returns the result in LHS.
588///
589/// If ValueLive is false, then this value is being evaluated in a context where
590/// the result is not used. As such, avoid diagnostics that relate to
591/// evaluation, such as division by zero warnings.
592static bool EvaluateDirectiveSubExpr(PPValue &LHS, unsigned MinPrec,
593 Token &PeekTok, bool ValueLive,
594 bool &IncludedUndefinedIds,
595 Preprocessor &PP) {
598 IncludedUndefinedIds) {
599 // The single-{file,module}-parse mode behavior kicks in as soon as single
600 // identifier is undefined. If we've already seen one, there's no point in
601 // continuing with the rest of the expression. Besides saving work, this
602 // also prevents calling undefined function-like macros.
603 PP.DiscardUntilEndOfDirective(PeekTok);
604 return true;
605 }
606
607 unsigned PeekPrec = getPrecedence(PeekTok.getKind());
608 // If this token isn't valid, report the error.
609 if (PeekPrec == ~0U) {
610 diagnoseUnexpectedOperator(PP, LHS, PeekTok);
611 return true;
612 }
613
614 while (true) {
615 // If this token has a lower precedence than we are allowed to parse, return
616 // it so that higher levels of the recursion can parse it.
617 if (PeekPrec < MinPrec)
618 return false;
619
620 tok::TokenKind Operator = PeekTok.getKind();
621
622 // If this is a short-circuiting operator, see if the RHS of the operator is
623 // dead. Note that this cannot just clobber ValueLive. Consider
624 // "0 && 1 ? 4 : 1 / 0", which is parsed as "(0 && 1) ? 4 : (1 / 0)". In
625 // this example, the RHS of the && being dead does not make the rest of the
626 // expr dead.
627 bool RHSIsLive;
628 if (Operator == tok::ampamp && LHS.Val == 0)
629 RHSIsLive = false; // RHS of "0 && x" is dead.
630 else if (Operator == tok::pipepipe && LHS.Val != 0)
631 RHSIsLive = false; // RHS of "1 || x" is dead.
632 else if (Operator == tok::question && LHS.Val == 0)
633 RHSIsLive = false; // RHS (x) of "0 ? x : y" is dead.
634 else
635 RHSIsLive = ValueLive;
636
637 // Consume the operator, remembering the operator's location for reporting.
638 SourceLocation OpLoc = PeekTok.getLocation();
639 PP.LexNonComment(PeekTok);
640
641 PPValue RHS(LHS.getBitWidth());
642 // Parse the RHS of the operator.
644 if (EvaluateValue(RHS, PeekTok, DT, RHSIsLive, PP)) return true;
645 IncludedUndefinedIds = DT.IncludedUndefinedIds;
646
647 // Remember the precedence of this operator and get the precedence of the
648 // operator immediately to the right of the RHS.
649 unsigned ThisPrec = PeekPrec;
650 PeekPrec = getPrecedence(PeekTok.getKind());
651
652 // If this token isn't valid, report the error.
653 if (PeekPrec == ~0U) {
654 diagnoseUnexpectedOperator(PP, RHS, PeekTok);
655 return true;
656 }
657
658 // Decide whether to include the next binop in this subexpression. For
659 // example, when parsing x+y*z and looking at '*', we want to recursively
660 // handle y*z as a single subexpression. We do this because the precedence
661 // of * is higher than that of +. The only strange case we have to handle
662 // here is for the ?: operator, where the precedence is actually lower than
663 // the LHS of the '?'. The grammar rule is:
664 //
665 // conditional-expression ::=
666 // logical-OR-expression ? expression : conditional-expression
667 // where 'expression' is actually comma-expression.
668 unsigned RHSPrec;
669 if (Operator == tok::question)
670 // The RHS of "?" should be maximally consumed as an expression.
671 RHSPrec = getPrecedence(tok::comma);
672 else // All others should munch while higher precedence.
673 RHSPrec = ThisPrec+1;
674
675 if (PeekPrec >= RHSPrec) {
676 if (EvaluateDirectiveSubExpr(RHS, RHSPrec, PeekTok, RHSIsLive,
677 IncludedUndefinedIds, PP))
678 return true;
679 PeekPrec = getPrecedence(PeekTok.getKind());
680 }
681 assert(PeekPrec <= ThisPrec && "Recursion didn't work!");
682
683 // Usual arithmetic conversions (C99 6.3.1.8p1): result is unsigned if
684 // either operand is unsigned.
685 llvm::APSInt Res(LHS.getBitWidth());
686 switch (Operator) {
687 case tok::question: // No UAC for x and y in "x ? y : z".
688 case tok::lessless: // Shift amount doesn't UAC with shift value.
689 case tok::greatergreater: // Shift amount doesn't UAC with shift value.
690 case tok::comma: // Comma operands are not subject to UACs.
691 case tok::pipepipe: // Logical || does not do UACs.
692 case tok::ampamp: // Logical && does not do UACs.
693 break; // No UAC
694 default:
695 Res.setIsUnsigned(LHS.isUnsigned() || RHS.isUnsigned());
696 // If this just promoted something from signed to unsigned, and if the
697 // value was negative, warn about it.
698 if (ValueLive && Res.isUnsigned()) {
699 if (!LHS.isUnsigned() && LHS.Val.isNegative())
700 PP.Diag(OpLoc, diag::warn_pp_convert_to_positive) << 0
701 << toString(LHS.Val, 10, true) + " to " +
702 toString(LHS.Val, 10, false)
703 << LHS.getRange() << RHS.getRange();
704 if (!RHS.isUnsigned() && RHS.Val.isNegative())
705 PP.Diag(OpLoc, diag::warn_pp_convert_to_positive) << 1
706 << toString(RHS.Val, 10, true) + " to " +
707 toString(RHS.Val, 10, false)
708 << LHS.getRange() << RHS.getRange();
709 }
710 LHS.Val.setIsUnsigned(Res.isUnsigned());
711 RHS.Val.setIsUnsigned(Res.isUnsigned());
712 }
713
714 bool Overflow = false;
715 switch (Operator) {
716 default: llvm_unreachable("Unknown operator token!");
717 case tok::percent:
718 if (RHS.Val != 0)
719 Res = LHS.Val % RHS.Val;
720 else if (ValueLive) {
721 PP.Diag(OpLoc, diag::err_pp_remainder_by_zero)
722 << LHS.getRange() << RHS.getRange();
723 return true;
724 }
725 break;
726 case tok::slash:
727 if (RHS.Val != 0) {
728 if (LHS.Val.isSigned())
729 Res = llvm::APSInt(LHS.Val.sdiv_ov(RHS.Val, Overflow), false);
730 else
731 Res = LHS.Val / RHS.Val;
732 } else if (ValueLive) {
733 PP.Diag(OpLoc, diag::err_pp_division_by_zero)
734 << LHS.getRange() << RHS.getRange();
735 return true;
736 }
737 break;
738
739 case tok::star:
740 if (Res.isSigned())
741 Res = llvm::APSInt(LHS.Val.smul_ov(RHS.Val, Overflow), false);
742 else
743 Res = LHS.Val * RHS.Val;
744 break;
745 case tok::lessless: {
746 // Determine whether overflow is about to happen.
747 if (LHS.isUnsigned())
748 Res = LHS.Val.ushl_ov(RHS.Val, Overflow);
749 else
750 Res = llvm::APSInt(LHS.Val.sshl_ov(RHS.Val, Overflow), false);
751 break;
752 }
753 case tok::greatergreater: {
754 // Determine whether overflow is about to happen.
755 unsigned ShAmt = static_cast<unsigned>(RHS.Val.getLimitedValue());
756 if (ShAmt >= LHS.getBitWidth()) {
757 Overflow = true;
758 ShAmt = LHS.getBitWidth()-1;
759 }
760 Res = LHS.Val >> ShAmt;
761 break;
762 }
763 case tok::plus:
764 if (LHS.isUnsigned())
765 Res = LHS.Val + RHS.Val;
766 else
767 Res = llvm::APSInt(LHS.Val.sadd_ov(RHS.Val, Overflow), false);
768 break;
769 case tok::minus:
770 if (LHS.isUnsigned())
771 Res = LHS.Val - RHS.Val;
772 else
773 Res = llvm::APSInt(LHS.Val.ssub_ov(RHS.Val, Overflow), false);
774 break;
775 case tok::lessequal:
776 Res = LHS.Val <= RHS.Val;
777 Res.setIsUnsigned(false); // C99 6.5.8p6, result is always int (signed)
778 break;
779 case tok::less:
780 Res = LHS.Val < RHS.Val;
781 Res.setIsUnsigned(false); // C99 6.5.8p6, result is always int (signed)
782 break;
783 case tok::greaterequal:
784 Res = LHS.Val >= RHS.Val;
785 Res.setIsUnsigned(false); // C99 6.5.8p6, result is always int (signed)
786 break;
787 case tok::greater:
788 Res = LHS.Val > RHS.Val;
789 Res.setIsUnsigned(false); // C99 6.5.8p6, result is always int (signed)
790 break;
791 case tok::exclaimequal:
792 Res = LHS.Val != RHS.Val;
793 Res.setIsUnsigned(false); // C99 6.5.9p3, result is always int (signed)
794 break;
795 case tok::equalequal:
796 Res = LHS.Val == RHS.Val;
797 Res.setIsUnsigned(false); // C99 6.5.9p3, result is always int (signed)
798 break;
799 case tok::amp:
800 Res = LHS.Val & RHS.Val;
801 break;
802 case tok::caret:
803 Res = LHS.Val ^ RHS.Val;
804 break;
805 case tok::pipe:
806 Res = LHS.Val | RHS.Val;
807 break;
808 case tok::ampamp:
809 Res = (LHS.Val != 0 && RHS.Val != 0);
810 Res.setIsUnsigned(false); // C99 6.5.13p3, result is always int (signed)
811 break;
812 case tok::pipepipe:
813 Res = (LHS.Val != 0 || RHS.Val != 0);
814 Res.setIsUnsigned(false); // C99 6.5.14p3, result is always int (signed)
815 break;
816 case tok::comma:
817 // Comma is invalid in pp expressions in c89/c++ mode, but is valid in C99
818 // if not being evaluated.
819 if (!PP.getLangOpts().C99 || ValueLive)
820 PP.Diag(OpLoc, diag::ext_pp_comma_expr)
821 << LHS.getRange() << RHS.getRange();
822 Res = RHS.Val; // LHS = LHS,RHS -> RHS.
823 break;
824 case tok::question: {
825 // Parse the : part of the expression.
826 if (PeekTok.isNot(tok::colon)) {
827 PP.Diag(PeekTok.getLocation(), diag::err_expected)
828 << tok::colon << LHS.getRange() << RHS.getRange();
829 PP.Diag(OpLoc, diag::note_matching) << tok::question;
830 return true;
831 }
832 // Consume the :.
833 PP.LexNonComment(PeekTok);
834
835 // Evaluate the value after the :.
836 bool AfterColonLive = ValueLive && LHS.Val == 0;
837 PPValue AfterColonVal(LHS.getBitWidth());
839 if (EvaluateValue(AfterColonVal, PeekTok, DT, AfterColonLive, PP))
840 return true;
841
842 // Parse anything after the : with the same precedence as ?. We allow
843 // things of equal precedence because ?: is right associative.
844 if (EvaluateDirectiveSubExpr(AfterColonVal, ThisPrec,
845 PeekTok, AfterColonLive,
846 IncludedUndefinedIds, PP))
847 return true;
848
849 // Now that we have the condition, the LHS and the RHS of the :, evaluate.
850 Res = LHS.Val != 0 ? RHS.Val : AfterColonVal.Val;
851 RHS.setEnd(AfterColonVal.getRange().getEnd());
852
853 // Usual arithmetic conversions (C99 6.3.1.8p1): result is unsigned if
854 // either operand is unsigned.
855 Res.setIsUnsigned(RHS.isUnsigned() || AfterColonVal.isUnsigned());
856
857 // Figure out the precedence of the token after the : part.
858 PeekPrec = getPrecedence(PeekTok.getKind());
859 break;
860 }
861 case tok::colon:
862 // Don't allow :'s to float around without being part of ?: exprs.
863 PP.Diag(OpLoc, diag::err_pp_colon_without_question)
864 << LHS.getRange() << RHS.getRange();
865 return true;
866 }
867
868 // If this operator is live and overflowed, report the issue.
869 if (Overflow && ValueLive)
870 PP.Diag(OpLoc, diag::warn_pp_expr_overflow)
871 << LHS.getRange() << RHS.getRange();
872
873 // Put the result back into 'LHS' for our next iteration.
874 LHS.Val = Res;
875 LHS.setEnd(RHS.getRange().getEnd());
876 RHS.setIdentifier(nullptr);
877 }
878}
879
880/// EvaluateDirectiveExpression - Evaluate an integer constant expression that
881/// may occur after a #if or #elif directive. If the expression is equivalent
882/// to "!defined(X)" return X in IfNDefMacro.
883Preprocessor::DirectiveEvalResult
884Preprocessor::EvaluateDirectiveExpression(IdentifierInfo *&IfNDefMacro,
885 Token &Tok, bool &EvaluatedDefined,
886 bool CheckForEoD) {
887 SaveAndRestore PPDir(ParsingIfOrElifDirective, true);
888 // Save the current state of 'DisableMacroExpansion' and reset it to false. If
889 // 'DisableMacroExpansion' is true, then we must be in a macro argument list
890 // in which case a directive is undefined behavior. We want macros to be able
891 // to recursively expand in order to get more gcc-list behavior, so we force
892 // DisableMacroExpansion to false and restore it when we're done parsing the
893 // expression.
894 bool DisableMacroExpansionAtStartOfDirective = DisableMacroExpansion;
895 DisableMacroExpansion = false;
896
897 // Peek ahead one token.
899
900 // C99 6.10.1p3 - All expressions are evaluated as intmax_t or uintmax_t.
901 unsigned BitWidth = getTargetInfo().getIntMaxTWidth();
902
903 PPValue ResVal(BitWidth);
904 DefinedTracker DT;
905 SourceLocation ExprStartLoc = SourceMgr.getExpansionLoc(Tok.getLocation());
906 if (EvaluateValue(ResVal, Tok, DT, true, *this)) {
907 // Parse error, skip the rest of the macro line.
908 if (Tok.isNot(tok::eod))
910
911 // Restore 'DisableMacroExpansion'.
912 DisableMacroExpansion = DisableMacroExpansionAtStartOfDirective;
913
914 // We cannot trust the source range from the value because there was a
915 // parse error. Track the range manually -- the end of the directive is the
916 // end of the condition range.
917 return {std::nullopt,
918 false,
920 {ExprStartLoc, Tok.getLocation()}};
921 }
922
923 EvaluatedDefined = DT.State != DefinedTracker::Unknown;
924
925 // If we are at the end of the expression after just parsing a value, there
926 // must be no (unparenthesized) binary operators involved, so we can exit
927 // directly.
928 if (Tok.is(tok::eod)) {
929 // If the expression we parsed was of the form !defined(macro), return the
930 // macro in IfNDefMacro.
932 IfNDefMacro = DT.TheMacro;
933
934 // Restore 'DisableMacroExpansion'.
935 DisableMacroExpansion = DisableMacroExpansionAtStartOfDirective;
936 bool IsNonZero = ResVal.Val != 0;
937 SourceRange ValRange = ResVal.getRange();
938 return {std::move(ResVal.Val), IsNonZero, DT.IncludedUndefinedIds,
939 ValRange};
940 }
941
942 // Otherwise, we must have a binary operator (e.g. "#if 1 < 2"), so parse the
943 // operator and the stuff after it.
944 if (EvaluateDirectiveSubExpr(ResVal, getPrecedence(tok::question),
945 Tok, true, DT.IncludedUndefinedIds, *this)) {
946 // Parse error, skip the rest of the macro line.
947 if (Tok.isNot(tok::eod))
949
950 // Restore 'DisableMacroExpansion'.
951 DisableMacroExpansion = DisableMacroExpansionAtStartOfDirective;
952 return {std::nullopt,
953 false,
955 {ExprStartLoc, Tok.getLocation()}};
956 }
957
958 if (CheckForEoD) {
959 // If we aren't at the tok::eod token, something bad happened, like an extra
960 // ')' token.
961 if (Tok.isNot(tok::eod)) {
962 Diag(Tok, diag::err_pp_expected_eol);
964 }
965 }
966
967 EvaluatedDefined = EvaluatedDefined || DT.State != DefinedTracker::Unknown;
968
969 // Restore 'DisableMacroExpansion'.
970 DisableMacroExpansion = DisableMacroExpansionAtStartOfDirective;
971 bool IsNonZero = ResVal.Val != 0;
972 SourceRange ValRange = ResVal.getRange();
973 return {std::move(ResVal.Val), IsNonZero, DT.IncludedUndefinedIds, ValRange};
974}
975
976Preprocessor::DirectiveEvalResult
977Preprocessor::EvaluateDirectiveExpression(IdentifierInfo *&IfNDefMacro,
978 bool CheckForEoD) {
979 Token Tok;
980 bool EvaluatedDefined;
981 return EvaluateDirectiveExpression(IfNDefMacro, Tok, EvaluatedDefined,
982 CheckForEoD);
983}
984
985static std::optional<CXXStandardLibraryVersionInfo>
988 MacroInfo *Macro = PP.getMacroInfo(PP.getIdentifierInfo(MacroName));
989 if (!Macro || Macro->getNumTokens() != 1 || !Macro->isObjectLike())
990 return std::nullopt;
991
992 const Token &RevisionDateTok = Macro->getReplacementToken(0);
993
994 bool Invalid = false;
996 llvm::StringRef RevisionDate =
997 PP.getSpelling(RevisionDateTok, Buffer, &Invalid);
998 if (!Invalid) {
999 std::uint64_t Value;
1000 // We don't use NumericParser to avoid diagnostics
1001 if (!RevisionDate.consumeInteger(10, Value))
1003 }
1005 0};
1006}
1007
1008std::optional<uint64_t> Preprocessor::getStdLibCxxVersion() {
1009 if (!CXXStandardLibraryVersion)
1010 CXXStandardLibraryVersion = getCXXStandardLibraryVersion(
1011 *this, "__GLIBCXX__", CXXStandardLibraryVersionInfo::LibStdCXX);
1012 if (!CXXStandardLibraryVersion)
1013 return std::nullopt;
1014
1015 if (CXXStandardLibraryVersion->Lib ==
1017 return CXXStandardLibraryVersion->Version;
1018 return std::nullopt;
1019}
1020
1022 assert(FixedVersion >= 2000'00'00 && FixedVersion <= 2100'00'00 &&
1023 "invalid value for __GLIBCXX__");
1024 std::optional<std::uint64_t> Ver = getStdLibCxxVersion();
1025 if (!Ver)
1026 return false;
1027 return *Ver < FixedVersion;
1028}
static bool isUnsigned(SValBuilder &SVB, NonLoc Value)
static uint32_t getBitWidth(const Expr *E)
Token Tok
The Token.
Defines the clang::IdentifierInfo, clang::IdentifierTable, and clang::Selector interfaces.
Defines the clang::MacroInfo and clang::MacroDirective classes.
Defines the PPCallbacks interface.
static bool EvaluateValue(PPValue &Result, Token &PeekTok, DefinedTracker &DT, bool ValueLive, Preprocessor &PP)
EvaluateValue - Evaluate the token PeekTok (and any others needed) and return the computed value in R...
static void diagnoseUnexpectedOperator(Preprocessor &PP, PPValue &LHS, Token &Tok)
static bool EvaluateDirectiveSubExpr(PPValue &LHS, unsigned MinPrec, Token &PeekTok, bool ValueLive, bool &IncludedUndefinedIds, Preprocessor &PP)
EvaluateDirectiveSubExpr - Evaluate the subexpression whose first token is PeekTok,...
static std::optional< CXXStandardLibraryVersionInfo > getCXXStandardLibraryVersion(Preprocessor &PP, StringRef MacroName, CXXStandardLibraryVersionInfo::Library Lib)
static unsigned getPrecedence(tok::TokenKind Kind)
getPrecedence - Return the precedence of the specified binary operator token.
static bool EvaluateDefined(PPValue &Result, Token &PeekTok, DefinedTracker &DT, bool ValueLive, Preprocessor &PP)
EvaluateDefined - Process a 'defined(sym)' expression.
static StringRef getIdentifier(const Token &Tok)
Defines the clang::Preprocessor interface.
static std::string toString(const clang::SanitizerSet &Sanitizers)
Produce a string containing comma-separated names of sanitizers in Sanitizers set.
static CharSourceRange getRange(const CharSourceRange &EditRange, const SourceManager &SM, const LangOptions &LangOpts, bool IncludeMacroExpansion)
Defines the clang::SourceLocation class and associated facilities.
Defines the SourceManager interface.
Defines the clang::TokenKind enum and support functions.
CharLiteralParser - Perform interpretation and semantic analysis of a character literal.
void setBegin(SourceLocation b)
virtual void CodeCompleteMacroName(bool IsDefinition)
Callback invoked when performing code completion in a context where the name of a macro is expected.
virtual void CodeCompletePreprocessorExpression()
Callback invoked when performing code completion in a preprocessor expression, such as the condition ...
std::vector< std::string > UndefPrefixes
The list of prefixes from -Wundef-prefix=... used to generate warnings for undefined macros.
Concrete class used by the front-end to report problems and issues.
Definition Diagnostic.h:232
DiagnosticOptions & getDiagnosticOptions() const
Retrieve the diagnostic options.
Definition Diagnostic.h:597
bool isIgnored(unsigned DiagID, SourceLocation Loc) const
Determine whether the diagnostic is known to be ignored.
Definition Diagnostic.h:951
One of these records is kept for each identifier that is lexed.
bool isCPlusPlusOperatorKeyword() const
bool isStr(const char(&Str)[StrLen]) const
Return true if this is the identifier for the specified string.
StringRef getName() const
Return the actual identifier string.
A description of the current definition of a macro.
Definition MacroInfo.h:590
Encapsulates the data about a macro definition (e.g.
Definition MacroInfo.h:39
NumericLiteralParser - This performs strict semantic analysis of the content of a ppnumber,...
This interface provides a way to observe the actions of the preprocessor as it does its thing.
Definition PPCallbacks.h:37
bool SingleFileParseMode
When enabled, preprocessor is in a mode for parsing a single file only.
bool SingleModuleParseMode
When enabled, preprocessor is in a mode for parsing a single module only.
Engages in a tight little dance with the lexer to efficiently preprocess tokens.
PPCallbacks * getPPCallbacks() const
const MacroInfo * getMacroInfo(const IdentifierInfo *II) const
void markMacroAsUsed(MacroInfo *MI)
A macro is used, update information about macros that need unused warnings.
void setCodeCompletionReached()
Note that we hit the code-completion point.
void LexNonComment(Token &Result)
Lex a token.
SourceRange DiscardUntilEndOfDirective()
Read and discard all tokens remaining on the current line until the tok::eod token is found.
IdentifierInfo * getIdentifierInfo(StringRef Name) const
Return information about the specified preprocessor identifier token.
SourceManager & getSourceManager() const
MacroDefinition getMacroDefinition(const IdentifierInfo *II)
bool CheckMacroName(Token &MacroNameTok, MacroUse isDefineUndef, bool *ShadowFlag=nullptr)
std::optional< std::uint64_t > getStdLibCxxVersion()
const TargetInfo & getTargetInfo() const
void LexUnexpandedNonComment(Token &Result)
Like LexNonComment, but this disables macro expansion of identifier tokens.
StringRef getSpelling(SourceLocation loc, SmallVectorImpl< char > &buffer, bool *invalid=nullptr) const
Return the 'spelling' of the token at the given location; does not go up to the spelling location or ...
void emitMacroExpansionWarnings(const Token &Identifier, bool IsIfnDef=false) const
bool NeedsStdLibCxxWorkaroundBefore(std::uint64_t FixedVersion)
CodeCompletionHandler * getCodeCompletionHandler() const
Retrieve the current code-completion handler.
const PreprocessorOptions & getPreprocessorOpts() const
Retrieve the preprocessor options used to initialize this preprocessor.
const LangOptions & getLangOpts() const
DiagnosticsEngine & getDiagnostics() const
DiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID) const
Forwarding function for diagnostics.
Encodes a location in the source.
bool isValid() const
Return true if this is a valid SourceLocation object.
FileID getFileID(SourceLocation SpellingLoc) const
Return the FileID for a SourceLocation.
const SrcMgr::SLocEntry & getSLocEntry(FileID FID, bool *Invalid=nullptr) const
A trivial tuple used to represent a source range.
const ExpansionInfo & getExpansion() const
Exposes information about the current target.
Definition TargetInfo.h:226
unsigned getChar32Width() const
getChar32Width/Align - Return the size of 'char32_t' for this target, in bits.
Definition TargetInfo.h:782
static bool isTypeSigned(IntType T)
Returns true if the type is signed; false otherwise.
unsigned getChar16Width() const
getChar16Width/Align - Return the size of 'char16_t' for this target, in bits.
Definition TargetInfo.h:777
unsigned getIntWidth() const
getIntWidth/Align - Return the size of 'signed int' and 'unsigned int' for this target,...
Definition TargetInfo.h:530
IntType getWCharType() const
Definition TargetInfo.h:418
unsigned getWCharWidth() const
getWCharWidth/Align - Return the size of 'wchar_t' for this target, in bits.
Definition TargetInfo.h:772
unsigned getIntMaxTWidth() const
Return the size of intmax_t and uintmax_t for this target, in bits.
Definition TargetInfo.h:893
unsigned getCharWidth() const
Definition TargetInfo.h:520
Token - This structure provides full information about a lexed token.
Definition Token.h:36
IdentifierInfo * getIdentifierInfo() const
Definition Token.h:195
SourceLocation getLocation() const
Return a source location identifier for the specified offset in the current file.
Definition Token.h:140
bool is(tok::TokenKind K) const
is/isNot - Predicates to check if this token is a specific kind, as in "if (Tok.is(tok::l_brace)) {....
Definition Token.h:102
tok::TokenKind getKind() const
Definition Token.h:97
bool isNot(tok::TokenKind K) const
Definition Token.h:109
bool hasUDSuffix() const
Return true if this token is a string or character literal which has a ud-suffix.
Definition Token.h:311
Defines the clang::TargetInfo interface.
TokenKind
Provides a simple uniform namespace for tokens from all C languages.
Definition TokenKinds.h:25
The JSON file list parser is used to communicate input to InstallAPI.
DefinedTracker - This struct is used while parsing expressions to keep track of whether !...
TrackerState
Each time a Value is evaluated, it returns information about whether the parsed value is of the form ...
IdentifierInfo * TheMacro
TheMacro - When the state is DefinedMacro or NotDefinedMacro, this indicates the macro that was check...
enum DefinedTracker::TrackerState State