clang 20.0.0git
PPMacroExpansion.cpp
Go to the documentation of this file.
1//===--- PPMacroExpansion.cpp - Top level Macro Expansion -----------------===//
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 top level handling of macro expansion for the
10// preprocessor.
11//
12//===----------------------------------------------------------------------===//
13
19#include "clang/Basic/LLVM.h"
30#include "clang/Lex/MacroArgs.h"
31#include "clang/Lex/MacroInfo.h"
35#include "clang/Lex/Token.h"
36#include "llvm/ADT/ArrayRef.h"
37#include "llvm/ADT/DenseMap.h"
38#include "llvm/ADT/DenseSet.h"
39#include "llvm/ADT/FoldingSet.h"
40#include "llvm/ADT/STLExtras.h"
41#include "llvm/ADT/SmallString.h"
42#include "llvm/ADT/SmallVector.h"
43#include "llvm/ADT/StringRef.h"
44#include "llvm/ADT/StringSwitch.h"
45#include "llvm/Support/Casting.h"
46#include "llvm/Support/ErrorHandling.h"
47#include "llvm/Support/Format.h"
48#include "llvm/Support/Path.h"
49#include "llvm/Support/raw_ostream.h"
50#include <algorithm>
51#include <cassert>
52#include <cstddef>
53#include <cstring>
54#include <ctime>
55#include <iomanip>
56#include <optional>
57#include <sstream>
58#include <string>
59#include <tuple>
60#include <utility>
61
62using namespace clang;
63
66 if (!II->hadMacroDefinition())
67 return nullptr;
68 auto Pos = CurSubmoduleState->Macros.find(II);
69 return Pos == CurSubmoduleState->Macros.end() ? nullptr
70 : Pos->second.getLatest();
71}
72
74 assert(MD && "MacroDirective should be non-zero!");
75 assert(!MD->getPrevious() && "Already attached to a MacroDirective history.");
76
77 MacroState &StoredMD = CurSubmoduleState->Macros[II];
78 auto *OldMD = StoredMD.getLatest();
79 MD->setPrevious(OldMD);
80 StoredMD.setLatest(MD);
81 StoredMD.overrideActiveModuleMacros(*this, II);
82
83 if (needModuleMacros()) {
84 // Track that we created a new macro directive, so we know we should
85 // consider building a ModuleMacro for it when we get to the end of
86 // the module.
87 PendingModuleMacroNames.push_back(II);
88 }
89
90 // Set up the identifier as having associated macro history.
91 II->setHasMacroDefinition(true);
92 if (!MD->isDefined() && !LeafModuleMacros.contains(II))
93 II->setHasMacroDefinition(false);
94 if (II->isFromAST())
96}
97
100 MacroDirective *MD) {
101 // Normally, when a macro is defined, it goes through appendMacroDirective()
102 // above, which chains a macro to previous defines, undefs, etc.
103 // However, in a pch, the whole macro history up to the end of the pch is
104 // stored, so ASTReader goes through this function instead.
105 // However, built-in macros are already registered in the Preprocessor
106 // ctor, and ASTWriter stops writing the macro chain at built-in macros,
107 // so in that case the chain from the pch needs to be spliced to the existing
108 // built-in.
109
110 assert(II && MD);
111 MacroState &StoredMD = CurSubmoduleState->Macros[II];
112
113 if (auto *OldMD = StoredMD.getLatest()) {
114 // shouldIgnoreMacro() in ASTWriter also stops at macros from the
115 // predefines buffer in module builds. However, in module builds, modules
116 // are loaded completely before predefines are processed, so StoredMD
117 // will be nullptr for them when they're loaded. StoredMD should only be
118 // non-nullptr for builtins read from a pch file.
119 assert(OldMD->getMacroInfo()->isBuiltinMacro() &&
120 "only built-ins should have an entry here");
121 assert(!OldMD->getPrevious() && "builtin should only have a single entry");
122 ED->setPrevious(OldMD);
123 StoredMD.setLatest(MD);
124 } else {
125 StoredMD = MD;
126 }
127
128 // Setup the identifier as having associated macro history.
129 II->setHasMacroDefinition(true);
130 if (!MD->isDefined() && !LeafModuleMacros.contains(II))
131 II->setHasMacroDefinition(false);
132}
133
135 MacroInfo *Macro,
136 ArrayRef<ModuleMacro *> Overrides,
137 bool &New) {
138 llvm::FoldingSetNodeID ID;
139 ModuleMacro::Profile(ID, Mod, II);
140
141 void *InsertPos;
142 if (auto *MM = ModuleMacros.FindNodeOrInsertPos(ID, InsertPos)) {
143 New = false;
144 return MM;
145 }
146
147 auto *MM = ModuleMacro::create(*this, Mod, II, Macro, Overrides);
148 ModuleMacros.InsertNode(MM, InsertPos);
149
150 // Each overridden macro is now overridden by one more macro.
151 bool HidAny = false;
152 for (auto *O : Overrides) {
153 HidAny |= (O->NumOverriddenBy == 0);
154 ++O->NumOverriddenBy;
155 }
156
157 // If we were the first overrider for any macro, it's no longer a leaf.
158 auto &LeafMacros = LeafModuleMacros[II];
159 if (HidAny) {
160 llvm::erase_if(LeafMacros,
161 [](ModuleMacro *MM) { return MM->NumOverriddenBy != 0; });
162 }
163
164 // The new macro is always a leaf macro.
165 LeafMacros.push_back(MM);
166 // The identifier now has defined macros (that may or may not be visible).
167 II->setHasMacroDefinition(true);
168
169 New = true;
170 return MM;
171}
172
174 const IdentifierInfo *II) {
175 llvm::FoldingSetNodeID ID;
176 ModuleMacro::Profile(ID, Mod, II);
177
178 void *InsertPos;
179 return ModuleMacros.FindNodeOrInsertPos(ID, InsertPos);
180}
181
182void Preprocessor::updateModuleMacroInfo(const IdentifierInfo *II,
183 ModuleMacroInfo &Info) {
184 assert(Info.ActiveModuleMacrosGeneration !=
185 CurSubmoduleState->VisibleModules.getGeneration() &&
186 "don't need to update this macro name info");
187 Info.ActiveModuleMacrosGeneration =
188 CurSubmoduleState->VisibleModules.getGeneration();
189
190 auto Leaf = LeafModuleMacros.find(II);
191 if (Leaf == LeafModuleMacros.end()) {
192 // No imported macros at all: nothing to do.
193 return;
194 }
195
196 Info.ActiveModuleMacros.clear();
197
198 // Every macro that's locally overridden is overridden by a visible macro.
199 llvm::DenseMap<ModuleMacro *, int> NumHiddenOverrides;
200 for (auto *O : Info.OverriddenMacros)
201 NumHiddenOverrides[O] = -1;
202
203 // Collect all macros that are not overridden by a visible macro.
205 for (auto *LeafMM : Leaf->second) {
206 assert(LeafMM->getNumOverridingMacros() == 0 && "leaf macro overridden");
207 if (NumHiddenOverrides.lookup(LeafMM) == 0)
208 Worklist.push_back(LeafMM);
209 }
210 while (!Worklist.empty()) {
211 auto *MM = Worklist.pop_back_val();
212 if (CurSubmoduleState->VisibleModules.isVisible(MM->getOwningModule())) {
213 // We only care about collecting definitions; undefinitions only act
214 // to override other definitions.
215 if (MM->getMacroInfo())
216 Info.ActiveModuleMacros.push_back(MM);
217 } else {
218 for (auto *O : MM->overrides())
219 if ((unsigned)++NumHiddenOverrides[O] == O->getNumOverridingMacros())
220 Worklist.push_back(O);
221 }
222 }
223 // Our reverse postorder walk found the macros in reverse order.
224 std::reverse(Info.ActiveModuleMacros.begin(), Info.ActiveModuleMacros.end());
225
226 // Determine whether the macro name is ambiguous.
227 MacroInfo *MI = nullptr;
228 bool IsSystemMacro = true;
229 bool IsAmbiguous = false;
230 if (auto *MD = Info.MD) {
231 while (isa_and_nonnull<VisibilityMacroDirective>(MD))
232 MD = MD->getPrevious();
233 if (auto *DMD = dyn_cast_or_null<DefMacroDirective>(MD)) {
234 MI = DMD->getInfo();
235 IsSystemMacro &= SourceMgr.isInSystemHeader(DMD->getLocation());
236 }
237 }
238 for (auto *Active : Info.ActiveModuleMacros) {
239 auto *NewMI = Active->getMacroInfo();
240
241 // Before marking the macro as ambiguous, check if this is a case where
242 // both macros are in system headers. If so, we trust that the system
243 // did not get it wrong. This also handles cases where Clang's own
244 // headers have a different spelling of certain system macros:
245 // #define LONG_MAX __LONG_MAX__ (clang's limits.h)
246 // #define LONG_MAX 0x7fffffffffffffffL (system's limits.h)
247 //
248 // FIXME: Remove the defined-in-system-headers check. clang's limits.h
249 // overrides the system limits.h's macros, so there's no conflict here.
250 if (MI && NewMI != MI &&
251 !MI->isIdenticalTo(*NewMI, *this, /*Syntactically=*/true))
252 IsAmbiguous = true;
253 IsSystemMacro &= Active->getOwningModule()->IsSystem ||
254 SourceMgr.isInSystemHeader(NewMI->getDefinitionLoc());
255 MI = NewMI;
256 }
257 Info.IsAmbiguous = IsAmbiguous && !IsSystemMacro;
258}
259
262 auto LeafIt = LeafModuleMacros.find(II);
263 if (LeafIt != LeafModuleMacros.end())
264 Leaf = LeafIt->second;
265 const MacroState *State = nullptr;
266 auto Pos = CurSubmoduleState->Macros.find(II);
267 if (Pos != CurSubmoduleState->Macros.end())
268 State = &Pos->second;
269
270 llvm::errs() << "MacroState " << State << " " << II->getNameStart();
271 if (State && State->isAmbiguous(*this, II))
272 llvm::errs() << " ambiguous";
273 if (State && !State->getOverriddenMacros().empty()) {
274 llvm::errs() << " overrides";
275 for (auto *O : State->getOverriddenMacros())
276 llvm::errs() << " " << O->getOwningModule()->getFullModuleName();
277 }
278 llvm::errs() << "\n";
279
280 // Dump local macro directives.
281 for (auto *MD = State ? State->getLatest() : nullptr; MD;
282 MD = MD->getPrevious()) {
283 llvm::errs() << " ";
284 MD->dump();
285 }
286
287 // Dump module macros.
289 for (auto *MM :
290 State ? State->getActiveModuleMacros(*this, II) : std::nullopt)
291 Active.insert(MM);
293 llvm::SmallVector<ModuleMacro *, 16> Worklist(Leaf.begin(), Leaf.end());
294 while (!Worklist.empty()) {
295 auto *MM = Worklist.pop_back_val();
296 llvm::errs() << " ModuleMacro " << MM << " "
297 << MM->getOwningModule()->getFullModuleName();
298 if (!MM->getMacroInfo())
299 llvm::errs() << " undef";
300
301 if (Active.count(MM))
302 llvm::errs() << " active";
303 else if (!CurSubmoduleState->VisibleModules.isVisible(
304 MM->getOwningModule()))
305 llvm::errs() << " hidden";
306 else if (MM->getMacroInfo())
307 llvm::errs() << " overridden";
308
309 if (!MM->overrides().empty()) {
310 llvm::errs() << " overrides";
311 for (auto *O : MM->overrides()) {
312 llvm::errs() << " " << O->getOwningModule()->getFullModuleName();
313 if (Visited.insert(O).second)
314 Worklist.push_back(O);
315 }
316 }
317 llvm::errs() << "\n";
318 if (auto *MI = MM->getMacroInfo()) {
319 llvm::errs() << " ";
320 MI->dump();
321 llvm::errs() << "\n";
322 }
323 }
324}
325
326/// RegisterBuiltinMacro - Register the specified identifier in the identifier
327/// table and mark it as a builtin macro to be expanded.
328static IdentifierInfo *RegisterBuiltinMacro(Preprocessor &PP, const char *Name){
329 // Get the identifier.
331
332 // Mark it as being a macro that is builtin.
334 MI->setIsBuiltinMacro();
336 return Id;
337}
338
339/// RegisterBuiltinMacros - Register builtin macros, such as __LINE__ with the
340/// identifier table.
341void Preprocessor::RegisterBuiltinMacros() {
342 Ident__LINE__ = RegisterBuiltinMacro(*this, "__LINE__");
343 Ident__FILE__ = RegisterBuiltinMacro(*this, "__FILE__");
344 Ident__DATE__ = RegisterBuiltinMacro(*this, "__DATE__");
345 Ident__TIME__ = RegisterBuiltinMacro(*this, "__TIME__");
346 Ident__COUNTER__ = RegisterBuiltinMacro(*this, "__COUNTER__");
347 Ident_Pragma = RegisterBuiltinMacro(*this, "_Pragma");
348 Ident__FLT_EVAL_METHOD__ = RegisterBuiltinMacro(*this, "__FLT_EVAL_METHOD__");
349
350 // C++ Standing Document Extensions.
352 Ident__has_cpp_attribute =
353 RegisterBuiltinMacro(*this, "__has_cpp_attribute");
354 else
355 Ident__has_cpp_attribute = nullptr;
356
357 // GCC Extensions.
358 Ident__BASE_FILE__ = RegisterBuiltinMacro(*this, "__BASE_FILE__");
359 Ident__INCLUDE_LEVEL__ = RegisterBuiltinMacro(*this, "__INCLUDE_LEVEL__");
360 Ident__TIMESTAMP__ = RegisterBuiltinMacro(*this, "__TIMESTAMP__");
361
362 // Microsoft Extensions.
363 if (getLangOpts().MicrosoftExt) {
364 Ident__identifier = RegisterBuiltinMacro(*this, "__identifier");
365 Ident__pragma = RegisterBuiltinMacro(*this, "__pragma");
366 } else {
367 Ident__identifier = nullptr;
368 Ident__pragma = nullptr;
369 }
370
371 // Clang Extensions.
372 Ident__FILE_NAME__ = RegisterBuiltinMacro(*this, "__FILE_NAME__");
373 Ident__has_feature = RegisterBuiltinMacro(*this, "__has_feature");
374 Ident__has_extension = RegisterBuiltinMacro(*this, "__has_extension");
375 Ident__has_builtin = RegisterBuiltinMacro(*this, "__has_builtin");
376 Ident__has_constexpr_builtin =
377 RegisterBuiltinMacro(*this, "__has_constexpr_builtin");
378 Ident__has_attribute = RegisterBuiltinMacro(*this, "__has_attribute");
379 if (!getLangOpts().CPlusPlus)
380 Ident__has_c_attribute = RegisterBuiltinMacro(*this, "__has_c_attribute");
381 else
382 Ident__has_c_attribute = nullptr;
383
384 Ident__has_declspec = RegisterBuiltinMacro(*this, "__has_declspec_attribute");
385 Ident__has_embed = RegisterBuiltinMacro(*this, "__has_embed");
386 Ident__has_include = RegisterBuiltinMacro(*this, "__has_include");
387 Ident__has_include_next = RegisterBuiltinMacro(*this, "__has_include_next");
388 Ident__has_warning = RegisterBuiltinMacro(*this, "__has_warning");
389 Ident__is_identifier = RegisterBuiltinMacro(*this, "__is_identifier");
390 Ident__is_target_arch = RegisterBuiltinMacro(*this, "__is_target_arch");
391 Ident__is_target_vendor = RegisterBuiltinMacro(*this, "__is_target_vendor");
392 Ident__is_target_os = RegisterBuiltinMacro(*this, "__is_target_os");
393 Ident__is_target_environment =
394 RegisterBuiltinMacro(*this, "__is_target_environment");
395 Ident__is_target_variant_os =
396 RegisterBuiltinMacro(*this, "__is_target_variant_os");
397 Ident__is_target_variant_environment =
398 RegisterBuiltinMacro(*this, "__is_target_variant_environment");
399
400 // Modules.
401 Ident__building_module = RegisterBuiltinMacro(*this, "__building_module");
402 if (!getLangOpts().CurrentModule.empty())
403 Ident__MODULE__ = RegisterBuiltinMacro(*this, "__MODULE__");
404 else
405 Ident__MODULE__ = nullptr;
406}
407
408/// isTrivialSingleTokenExpansion - Return true if MI, which has a single token
409/// in its expansion, currently expands to that token literally.
411 const IdentifierInfo *MacroIdent,
412 Preprocessor &PP) {
414
415 // If the token isn't an identifier, it's always literally expanded.
416 if (!II) return true;
417
418 // If the information about this identifier is out of date, update it from
419 // the external source.
420 if (II->isOutOfDate())
422
423 // If the identifier is a macro, and if that macro is enabled, it may be
424 // expanded so it's not a trivial expansion.
425 if (auto *ExpansionMI = PP.getMacroInfo(II))
426 if (ExpansionMI->isEnabled() &&
427 // Fast expanding "#define X X" is ok, because X would be disabled.
428 II != MacroIdent)
429 return false;
430
431 // If this is an object-like macro invocation, it is safe to trivially expand
432 // it.
433 if (MI->isObjectLike()) return true;
434
435 // If this is a function-like macro invocation, it's safe to trivially expand
436 // as long as the identifier is not a macro argument.
437 return !llvm::is_contained(MI->params(), II);
438}
439
440/// isNextPPTokenLParen - Determine whether the next preprocessor token to be
441/// lexed is a '('. If so, consume the token and return true, if not, this
442/// method should have no observable side-effect on the lexed tokens.
443bool Preprocessor::isNextPPTokenLParen() {
444 // Do some quick tests for rejection cases.
445 unsigned Val;
446 if (CurLexer)
447 Val = CurLexer->isNextPPTokenLParen();
448 else
449 Val = CurTokenLexer->isNextTokenLParen();
450
451 if (Val == 2) {
452 // We have run off the end. If it's a source file we don't
453 // examine enclosing ones (C99 5.1.1.2p4). Otherwise walk up the
454 // macro stack.
455 if (CurPPLexer)
456 return false;
457 for (const IncludeStackInfo &Entry : llvm::reverse(IncludeMacroStack)) {
458 if (Entry.TheLexer)
459 Val = Entry.TheLexer->isNextPPTokenLParen();
460 else
461 Val = Entry.TheTokenLexer->isNextTokenLParen();
462
463 if (Val != 2)
464 break;
465
466 // Ran off the end of a source file?
467 if (Entry.ThePPLexer)
468 return false;
469 }
470 }
471
472 // Okay, if we know that the token is a '(', lex it and return. Otherwise we
473 // have found something that isn't a '(' or we found the end of the
474 // translation unit. In either case, return false.
475 return Val == 1;
476}
477
478/// HandleMacroExpandedIdentifier - If an identifier token is read that is to be
479/// expanded as a macro, handle it and return the next token as 'Identifier'.
480bool Preprocessor::HandleMacroExpandedIdentifier(Token &Identifier,
481 const MacroDefinition &M) {
483
484 MacroInfo *MI = M.getMacroInfo();
485
486 // If this is a macro expansion in the "#if !defined(x)" line for the file,
487 // then the macro could expand to different things in other contexts, we need
488 // to disable the optimization in this case.
489 if (CurPPLexer) CurPPLexer->MIOpt.ExpandedMacro();
490
491 // If this is a builtin macro, like __LINE__ or _Pragma, handle it specially.
492 if (MI->isBuiltinMacro()) {
493 if (Callbacks)
494 Callbacks->MacroExpands(Identifier, M, Identifier.getLocation(),
495 /*Args=*/nullptr);
496 ExpandBuiltinMacro(Identifier);
497 return true;
498 }
499
500 /// Args - If this is a function-like macro expansion, this contains,
501 /// for each macro argument, the list of tokens that were provided to the
502 /// invocation.
503 MacroArgs *Args = nullptr;
504
505 // Remember where the end of the expansion occurred. For an object-like
506 // macro, this is the identifier. For a function-like macro, this is the ')'.
507 SourceLocation ExpansionEnd = Identifier.getLocation();
508
509 // If this is a function-like macro, read the arguments.
510 if (MI->isFunctionLike()) {
511 // Remember that we are now parsing the arguments to a macro invocation.
512 // Preprocessor directives used inside macro arguments are not portable, and
513 // this enables the warning.
514 InMacroArgs = true;
515 ArgMacro = &Identifier;
516
517 Args = ReadMacroCallArgumentList(Identifier, MI, ExpansionEnd);
518
519 // Finished parsing args.
520 InMacroArgs = false;
521 ArgMacro = nullptr;
522
523 // If there was an error parsing the arguments, bail out.
524 if (!Args) return true;
525
526 ++NumFnMacroExpanded;
527 } else {
528 ++NumMacroExpanded;
529 }
530
531 // Notice that this macro has been used.
532 markMacroAsUsed(MI);
533
534 // Remember where the token is expanded.
535 SourceLocation ExpandLoc = Identifier.getLocation();
536 SourceRange ExpansionRange(ExpandLoc, ExpansionEnd);
537
538 if (Callbacks) {
539 if (InMacroArgs) {
540 // We can have macro expansion inside a conditional directive while
541 // reading the function macro arguments. To ensure, in that case, that
542 // MacroExpands callbacks still happen in source order, queue this
543 // callback to have it happen after the function macro callback.
544 DelayedMacroExpandsCallbacks.push_back(
545 MacroExpandsInfo(Identifier, M, ExpansionRange));
546 } else {
547 Callbacks->MacroExpands(Identifier, M, ExpansionRange, Args);
548 if (!DelayedMacroExpandsCallbacks.empty()) {
549 for (const MacroExpandsInfo &Info : DelayedMacroExpandsCallbacks) {
550 // FIXME: We lose macro args info with delayed callback.
551 Callbacks->MacroExpands(Info.Tok, Info.MD, Info.Range,
552 /*Args=*/nullptr);
553 }
554 DelayedMacroExpandsCallbacks.clear();
555 }
556 }
557 }
558
559 // If the macro definition is ambiguous, complain.
560 if (M.isAmbiguous()) {
561 Diag(Identifier, diag::warn_pp_ambiguous_macro)
562 << Identifier.getIdentifierInfo();
563 Diag(MI->getDefinitionLoc(), diag::note_pp_ambiguous_macro_chosen)
564 << Identifier.getIdentifierInfo();
565 M.forAllDefinitions([&](const MacroInfo *OtherMI) {
566 if (OtherMI != MI)
567 Diag(OtherMI->getDefinitionLoc(), diag::note_pp_ambiguous_macro_other)
568 << Identifier.getIdentifierInfo();
569 });
570 }
571
572 // If we started lexing a macro, enter the macro expansion body.
573
574 // If this macro expands to no tokens, don't bother to push it onto the
575 // expansion stack, only to take it right back off.
576 if (MI->getNumTokens() == 0) {
577 // No need for arg info.
578 if (Args) Args->destroy(*this);
579
580 // Propagate whitespace info as if we had pushed, then popped,
581 // a macro context.
583 PropagateLineStartLeadingSpaceInfo(Identifier);
584 ++NumFastMacroExpanded;
585 return false;
586 } else if (MI->getNumTokens() == 1 &&
587 isTrivialSingleTokenExpansion(MI, Identifier.getIdentifierInfo(),
588 *this)) {
589 // Otherwise, if this macro expands into a single trivially-expanded
590 // token: expand it now. This handles common cases like
591 // "#define VAL 42".
592
593 // No need for arg info.
594 if (Args) Args->destroy(*this);
595
596 // Propagate the isAtStartOfLine/hasLeadingSpace markers of the macro
597 // identifier to the expanded token.
598 bool isAtStartOfLine = Identifier.isAtStartOfLine();
599 bool hasLeadingSpace = Identifier.hasLeadingSpace();
600
601 // Replace the result token.
603
604 // Restore the StartOfLine/LeadingSpace markers.
605 Identifier.setFlagValue(Token::StartOfLine , isAtStartOfLine);
606 Identifier.setFlagValue(Token::LeadingSpace, hasLeadingSpace);
607
608 // Update the tokens location to include both its expansion and physical
609 // locations.
611 SourceMgr.createExpansionLoc(Identifier.getLocation(), ExpandLoc,
612 ExpansionEnd,Identifier.getLength());
613 Identifier.setLocation(Loc);
614
615 // If this is a disabled macro or #define X X, we must mark the result as
616 // unexpandable.
617 if (IdentifierInfo *NewII = Identifier.getIdentifierInfo()) {
618 if (MacroInfo *NewMI = getMacroInfo(NewII))
619 if (!NewMI->isEnabled() || NewMI == MI) {
621 // Don't warn for "#define X X" like "#define bool bool" from
622 // stdbool.h.
623 if (NewMI != MI || MI->isFunctionLike())
624 Diag(Identifier, diag::pp_disabled_macro_expansion);
625 }
626 }
627
628 // Since this is not an identifier token, it can't be macro expanded, so
629 // we're done.
630 ++NumFastMacroExpanded;
631 return true;
632 }
633
634 // Start expanding the macro.
635 EnterMacro(Identifier, ExpansionEnd, MI, Args);
636 return false;
637}
638
641 Paren
643
644/// CheckMatchedBrackets - Returns true if the braces and parentheses in the
645/// token vector are properly nested.
648 for (SmallVectorImpl<Token>::const_iterator I = Tokens.begin(),
649 E = Tokens.end();
650 I != E; ++I) {
651 if (I->is(tok::l_paren)) {
652 Brackets.push_back(Paren);
653 } else if (I->is(tok::r_paren)) {
654 if (Brackets.empty() || Brackets.back() == Brace)
655 return false;
656 Brackets.pop_back();
657 } else if (I->is(tok::l_brace)) {
658 Brackets.push_back(Brace);
659 } else if (I->is(tok::r_brace)) {
660 if (Brackets.empty() || Brackets.back() == Paren)
661 return false;
662 Brackets.pop_back();
663 }
664 }
665 return Brackets.empty();
666}
667
668/// GenerateNewArgTokens - Returns true if OldTokens can be converted to a new
669/// vector of tokens in NewTokens. The new number of arguments will be placed
670/// in NumArgs and the ranges which need to surrounded in parentheses will be
671/// in ParenHints.
672/// Returns false if the token stream cannot be changed. If this is because
673/// of an initializer list starting a macro argument, the range of those
674/// initializer lists will be place in InitLists.
676 SmallVectorImpl<Token> &OldTokens,
677 SmallVectorImpl<Token> &NewTokens,
678 unsigned &NumArgs,
680 SmallVectorImpl<SourceRange> &InitLists) {
681 if (!CheckMatchedBrackets(OldTokens))
682 return false;
683
684 // Once it is known that the brackets are matched, only a simple count of the
685 // braces is needed.
686 unsigned Braces = 0;
687
688 // First token of a new macro argument.
689 SmallVectorImpl<Token>::iterator ArgStartIterator = OldTokens.begin();
690
691 // First closing brace in a new macro argument. Used to generate
692 // SourceRanges for InitLists.
693 SmallVectorImpl<Token>::iterator ClosingBrace = OldTokens.end();
694 NumArgs = 0;
695 Token TempToken;
696 // Set to true when a macro separator token is found inside a braced list.
697 // If true, the fixed argument spans multiple old arguments and ParenHints
698 // will be updated.
699 bool FoundSeparatorToken = false;
700 for (SmallVectorImpl<Token>::iterator I = OldTokens.begin(),
701 E = OldTokens.end();
702 I != E; ++I) {
703 if (I->is(tok::l_brace)) {
704 ++Braces;
705 } else if (I->is(tok::r_brace)) {
706 --Braces;
707 if (Braces == 0 && ClosingBrace == E && FoundSeparatorToken)
708 ClosingBrace = I;
709 } else if (I->is(tok::eof)) {
710 // EOF token is used to separate macro arguments
711 if (Braces != 0) {
712 // Assume comma separator is actually braced list separator and change
713 // it back to a comma.
714 FoundSeparatorToken = true;
715 I->setKind(tok::comma);
716 I->setLength(1);
717 } else { // Braces == 0
718 // Separator token still separates arguments.
719 ++NumArgs;
720
721 // If the argument starts with a brace, it can't be fixed with
722 // parentheses. A different diagnostic will be given.
723 if (FoundSeparatorToken && ArgStartIterator->is(tok::l_brace)) {
724 InitLists.push_back(
725 SourceRange(ArgStartIterator->getLocation(),
726 PP.getLocForEndOfToken(ClosingBrace->getLocation())));
727 ClosingBrace = E;
728 }
729
730 // Add left paren
731 if (FoundSeparatorToken) {
732 TempToken.startToken();
733 TempToken.setKind(tok::l_paren);
734 TempToken.setLocation(ArgStartIterator->getLocation());
735 TempToken.setLength(0);
736 NewTokens.push_back(TempToken);
737 }
738
739 // Copy over argument tokens
740 NewTokens.insert(NewTokens.end(), ArgStartIterator, I);
741
742 // Add right paren and store the paren locations in ParenHints
743 if (FoundSeparatorToken) {
744 SourceLocation Loc = PP.getLocForEndOfToken((I - 1)->getLocation());
745 TempToken.startToken();
746 TempToken.setKind(tok::r_paren);
747 TempToken.setLocation(Loc);
748 TempToken.setLength(0);
749 NewTokens.push_back(TempToken);
750 ParenHints.push_back(SourceRange(ArgStartIterator->getLocation(),
751 Loc));
752 }
753
754 // Copy separator token
755 NewTokens.push_back(*I);
756
757 // Reset values
758 ArgStartIterator = I + 1;
759 FoundSeparatorToken = false;
760 }
761 }
762 }
763
764 return !ParenHints.empty() && InitLists.empty();
765}
766
767/// ReadFunctionLikeMacroArgs - After reading "MACRO" and knowing that the next
768/// token is the '(' of the macro, this method is invoked to read all of the
769/// actual arguments specified for the macro invocation. This returns null on
770/// error.
771MacroArgs *Preprocessor::ReadMacroCallArgumentList(Token &MacroName,
772 MacroInfo *MI,
773 SourceLocation &MacroEnd) {
774 // The number of fixed arguments to parse.
775 unsigned NumFixedArgsLeft = MI->getNumParams();
776 bool isVariadic = MI->isVariadic();
777
778 // Outer loop, while there are more arguments, keep reading them.
779 Token Tok;
780
781 // Read arguments as unexpanded tokens. This avoids issues, e.g., where
782 // an argument value in a macro could expand to ',' or '(' or ')'.
784 assert(Tok.is(tok::l_paren) && "Error computing l-paren-ness?");
785
786 // ArgTokens - Build up a list of tokens that make up each argument. Each
787 // argument is separated by an EOF token. Use a SmallVector so we can avoid
788 // heap allocations in the common case.
789 SmallVector<Token, 64> ArgTokens;
790 bool ContainsCodeCompletionTok = false;
791 bool FoundElidedComma = false;
792
793 SourceLocation TooManyArgsLoc;
794
795 unsigned NumActuals = 0;
796 while (Tok.isNot(tok::r_paren)) {
797 if (ContainsCodeCompletionTok && Tok.isOneOf(tok::eof, tok::eod))
798 break;
799
800 assert(Tok.isOneOf(tok::l_paren, tok::comma) &&
801 "only expect argument separators here");
802
803 size_t ArgTokenStart = ArgTokens.size();
804 SourceLocation ArgStartLoc = Tok.getLocation();
805
806 // C99 6.10.3p11: Keep track of the number of l_parens we have seen. Note
807 // that we already consumed the first one.
808 unsigned NumParens = 0;
809
810 while (true) {
811 // Read arguments as unexpanded tokens. This avoids issues, e.g., where
812 // an argument value in a macro could expand to ',' or '(' or ')'.
814
815 if (Tok.isOneOf(tok::eof, tok::eod)) { // "#if f(<eof>" & "#if f(\n"
816 if (!ContainsCodeCompletionTok) {
817 Diag(MacroName, diag::err_unterm_macro_invoc);
818 Diag(MI->getDefinitionLoc(), diag::note_macro_here)
819 << MacroName.getIdentifierInfo();
820 // Do not lose the EOF/EOD. Return it to the client.
821 MacroName = Tok;
822 return nullptr;
823 }
824 // Do not lose the EOF/EOD.
825 auto Toks = std::make_unique<Token[]>(1);
826 Toks[0] = Tok;
827 EnterTokenStream(std::move(Toks), 1, true, /*IsReinject*/ false);
828 break;
829 } else if (Tok.is(tok::r_paren)) {
830 // If we found the ) token, the macro arg list is done.
831 if (NumParens-- == 0) {
832 MacroEnd = Tok.getLocation();
833 if (!ArgTokens.empty() &&
834 ArgTokens.back().commaAfterElided()) {
835 FoundElidedComma = true;
836 }
837 break;
838 }
839 } else if (Tok.is(tok::l_paren)) {
840 ++NumParens;
841 } else if (Tok.is(tok::comma)) {
842 // In Microsoft-compatibility mode, single commas from nested macro
843 // expansions should not be considered as argument separators. We test
844 // for this with the IgnoredComma token flag.
845 if (Tok.getFlags() & Token::IgnoredComma) {
846 // However, in MSVC's preprocessor, subsequent expansions do treat
847 // these commas as argument separators. This leads to a common
848 // workaround used in macros that need to work in both MSVC and
849 // compliant preprocessors. Therefore, the IgnoredComma flag can only
850 // apply once to any given token.
852 } else if (NumParens == 0) {
853 // Comma ends this argument if there are more fixed arguments
854 // expected. However, if this is a variadic macro, and this is part of
855 // the variadic part, then the comma is just an argument token.
856 if (!isVariadic)
857 break;
858 if (NumFixedArgsLeft > 1)
859 break;
860 }
861 } else if (Tok.is(tok::comment) && !KeepMacroComments) {
862 // If this is a comment token in the argument list and we're just in
863 // -C mode (not -CC mode), discard the comment.
864 continue;
865 } else if (!Tok.isAnnotation() && Tok.getIdentifierInfo() != nullptr) {
866 // Reading macro arguments can cause macros that we are currently
867 // expanding from to be popped off the expansion stack. Doing so causes
868 // them to be reenabled for expansion. Here we record whether any
869 // identifiers we lex as macro arguments correspond to disabled macros.
870 // If so, we mark the token as noexpand. This is a subtle aspect of
871 // C99 6.10.3.4p2.
873 if (!MI->isEnabled())
875 } else if (Tok.is(tok::code_completion)) {
876 ContainsCodeCompletionTok = true;
877 if (CodeComplete)
878 CodeComplete->CodeCompleteMacroArgument(MacroName.getIdentifierInfo(),
879 MI, NumActuals);
880 // Don't mark that we reached the code-completion point because the
881 // parser is going to handle the token and there will be another
882 // code-completion callback.
883 }
884
885 ArgTokens.push_back(Tok);
886 }
887
888 // If this was an empty argument list foo(), don't add this as an empty
889 // argument.
890 if (ArgTokens.empty() && Tok.getKind() == tok::r_paren)
891 break;
892
893 // If this is not a variadic macro, and too many args were specified, emit
894 // an error.
895 if (!isVariadic && NumFixedArgsLeft == 0 && TooManyArgsLoc.isInvalid()) {
896 if (ArgTokens.size() != ArgTokenStart)
897 TooManyArgsLoc = ArgTokens[ArgTokenStart].getLocation();
898 else
899 TooManyArgsLoc = ArgStartLoc;
900 }
901
902 // Empty arguments are standard in C99 and C++0x, and are supported as an
903 // extension in other modes.
904 if (ArgTokens.size() == ArgTokenStart && !getLangOpts().C99)
906 ? diag::warn_cxx98_compat_empty_fnmacro_arg
907 : diag::ext_empty_fnmacro_arg);
908
909 // Add a marker EOF token to the end of the token list for this argument.
910 Token EOFTok;
911 EOFTok.startToken();
912 EOFTok.setKind(tok::eof);
913 EOFTok.setLocation(Tok.getLocation());
914 EOFTok.setLength(0);
915 ArgTokens.push_back(EOFTok);
916 ++NumActuals;
917 if (!ContainsCodeCompletionTok && NumFixedArgsLeft != 0)
918 --NumFixedArgsLeft;
919 }
920
921 // Okay, we either found the r_paren. Check to see if we parsed too few
922 // arguments.
923 unsigned MinArgsExpected = MI->getNumParams();
924
925 // If this is not a variadic macro, and too many args were specified, emit
926 // an error.
927 if (!isVariadic && NumActuals > MinArgsExpected &&
928 !ContainsCodeCompletionTok) {
929 // Emit the diagnostic at the macro name in case there is a missing ).
930 // Emitting it at the , could be far away from the macro name.
931 Diag(TooManyArgsLoc, diag::err_too_many_args_in_macro_invoc);
932 Diag(MI->getDefinitionLoc(), diag::note_macro_here)
933 << MacroName.getIdentifierInfo();
934
935 // Commas from braced initializer lists will be treated as argument
936 // separators inside macros. Attempt to correct for this with parentheses.
937 // TODO: See if this can be generalized to angle brackets for templates
938 // inside macro arguments.
939
940 SmallVector<Token, 4> FixedArgTokens;
941 unsigned FixedNumArgs = 0;
942 SmallVector<SourceRange, 4> ParenHints, InitLists;
943 if (!GenerateNewArgTokens(*this, ArgTokens, FixedArgTokens, FixedNumArgs,
944 ParenHints, InitLists)) {
945 if (!InitLists.empty()) {
947 Diag(MacroName,
948 diag::note_init_list_at_beginning_of_macro_argument);
949 for (SourceRange Range : InitLists)
950 DB << Range;
951 }
952 return nullptr;
953 }
954 if (FixedNumArgs != MinArgsExpected)
955 return nullptr;
956
957 DiagnosticBuilder DB = Diag(MacroName, diag::note_suggest_parens_for_macro);
958 for (SourceRange ParenLocation : ParenHints) {
959 DB << FixItHint::CreateInsertion(ParenLocation.getBegin(), "(");
960 DB << FixItHint::CreateInsertion(ParenLocation.getEnd(), ")");
961 }
962 ArgTokens.swap(FixedArgTokens);
963 NumActuals = FixedNumArgs;
964 }
965
966 // See MacroArgs instance var for description of this.
967 bool isVarargsElided = false;
968
969 if (ContainsCodeCompletionTok) {
970 // Recover from not-fully-formed macro invocation during code-completion.
971 Token EOFTok;
972 EOFTok.startToken();
973 EOFTok.setKind(tok::eof);
974 EOFTok.setLocation(Tok.getLocation());
975 EOFTok.setLength(0);
976 for (; NumActuals < MinArgsExpected; ++NumActuals)
977 ArgTokens.push_back(EOFTok);
978 }
979
980 if (NumActuals < MinArgsExpected) {
981 // There are several cases where too few arguments is ok, handle them now.
982 if (NumActuals == 0 && MinArgsExpected == 1) {
983 // #define A(X) or #define A(...) ---> A()
984
985 // If there is exactly one argument, and that argument is missing,
986 // then we have an empty "()" argument empty list. This is fine, even if
987 // the macro expects one argument (the argument is just empty).
988 isVarargsElided = MI->isVariadic();
989 } else if ((FoundElidedComma || MI->isVariadic()) &&
990 (NumActuals+1 == MinArgsExpected || // A(x, ...) -> A(X)
991 (NumActuals == 0 && MinArgsExpected == 2))) {// A(x,...) -> A()
992 // Varargs where the named vararg parameter is missing: OK as extension.
993 // #define A(x, ...)
994 // A("blah")
995 //
996 // If the macro contains the comma pasting extension, the diagnostic
997 // is suppressed; we know we'll get another diagnostic later.
998 if (!MI->hasCommaPasting()) {
999 // C++20 [cpp.replace]p15, C23 6.10.5p12
1000 //
1001 // C++20 and C23 allow this construct, but standards before that
1002 // do not (we allow it as an extension).
1003 unsigned ID;
1005 ID = diag::warn_cxx17_compat_missing_varargs_arg;
1006 else if (getLangOpts().CPlusPlus)
1007 ID = diag::ext_cxx_missing_varargs_arg;
1008 else if (getLangOpts().C23)
1009 ID = diag::warn_c17_compat_missing_varargs_arg;
1010 else
1011 ID = diag::ext_c_missing_varargs_arg;
1012 Diag(Tok, ID);
1013 Diag(MI->getDefinitionLoc(), diag::note_macro_here)
1014 << MacroName.getIdentifierInfo();
1015 }
1016
1017 // Remember this occurred, allowing us to elide the comma when used for
1018 // cases like:
1019 // #define A(x, foo...) blah(a, ## foo)
1020 // #define B(x, ...) blah(a, ## __VA_ARGS__)
1021 // #define C(...) blah(a, ## __VA_ARGS__)
1022 // A(x) B(x) C()
1023 isVarargsElided = true;
1024 } else if (!ContainsCodeCompletionTok) {
1025 // Otherwise, emit the error.
1026 Diag(Tok, diag::err_too_few_args_in_macro_invoc);
1027 Diag(MI->getDefinitionLoc(), diag::note_macro_here)
1028 << MacroName.getIdentifierInfo();
1029 return nullptr;
1030 }
1031
1032 // Add a marker EOF token to the end of the token list for this argument.
1033 SourceLocation EndLoc = Tok.getLocation();
1034 Tok.startToken();
1035 Tok.setKind(tok::eof);
1036 Tok.setLocation(EndLoc);
1037 Tok.setLength(0);
1038 ArgTokens.push_back(Tok);
1039
1040 // If we expect two arguments, add both as empty.
1041 if (NumActuals == 0 && MinArgsExpected == 2)
1042 ArgTokens.push_back(Tok);
1043
1044 } else if (NumActuals > MinArgsExpected && !MI->isVariadic() &&
1045 !ContainsCodeCompletionTok) {
1046 // Emit the diagnostic at the macro name in case there is a missing ).
1047 // Emitting it at the , could be far away from the macro name.
1048 Diag(MacroName, diag::err_too_many_args_in_macro_invoc);
1049 Diag(MI->getDefinitionLoc(), diag::note_macro_here)
1050 << MacroName.getIdentifierInfo();
1051 return nullptr;
1052 }
1053
1054 return MacroArgs::create(MI, ArgTokens, isVarargsElided, *this);
1055}
1056
1057/// Keeps macro expanded tokens for TokenLexers.
1058//
1059/// Works like a stack; a TokenLexer adds the macro expanded tokens that is
1060/// going to lex in the cache and when it finishes the tokens are removed
1061/// from the end of the cache.
1062Token *Preprocessor::cacheMacroExpandedTokens(TokenLexer *tokLexer,
1063 ArrayRef<Token> tokens) {
1064 assert(tokLexer);
1065 if (tokens.empty())
1066 return nullptr;
1067
1068 size_t newIndex = MacroExpandedTokens.size();
1069 bool cacheNeedsToGrow = tokens.size() >
1070 MacroExpandedTokens.capacity()-MacroExpandedTokens.size();
1071 MacroExpandedTokens.append(tokens.begin(), tokens.end());
1072
1073 if (cacheNeedsToGrow) {
1074 // Go through all the TokenLexers whose 'Tokens' pointer points in the
1075 // buffer and update the pointers to the (potential) new buffer array.
1076 for (const auto &Lexer : MacroExpandingLexersStack) {
1077 TokenLexer *prevLexer;
1078 size_t tokIndex;
1079 std::tie(prevLexer, tokIndex) = Lexer;
1080 prevLexer->Tokens = MacroExpandedTokens.data() + tokIndex;
1081 }
1082 }
1083
1084 MacroExpandingLexersStack.push_back(std::make_pair(tokLexer, newIndex));
1085 return MacroExpandedTokens.data() + newIndex;
1086}
1087
1088void Preprocessor::removeCachedMacroExpandedTokensOfLastLexer() {
1089 assert(!MacroExpandingLexersStack.empty());
1090 size_t tokIndex = MacroExpandingLexersStack.back().second;
1091 assert(tokIndex < MacroExpandedTokens.size());
1092 // Pop the cached macro expanded tokens from the end.
1093 MacroExpandedTokens.resize(tokIndex);
1094 MacroExpandingLexersStack.pop_back();
1095}
1096
1097/// ComputeDATE_TIME - Compute the current time, enter it into the specified
1098/// scratch buffer, then return DATELoc/TIMELoc locations with the position of
1099/// the identifier tokens inserted.
1100static void ComputeDATE_TIME(SourceLocation &DATELoc, SourceLocation &TIMELoc,
1101 Preprocessor &PP) {
1102 time_t TT;
1103 std::tm *TM;
1106 TM = std::gmtime(&TT);
1107 } else {
1108 TT = std::time(nullptr);
1109 TM = std::localtime(&TT);
1110 }
1111
1112 static const char * const Months[] = {
1113 "Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"
1114 };
1115
1116 {
1117 SmallString<32> TmpBuffer;
1118 llvm::raw_svector_ostream TmpStream(TmpBuffer);
1119 if (TM)
1120 TmpStream << llvm::format("\"%s %2d %4d\"", Months[TM->tm_mon],
1121 TM->tm_mday, TM->tm_year + 1900);
1122 else
1123 TmpStream << "??? ?? ????";
1124 Token TmpTok;
1125 TmpTok.startToken();
1126 PP.CreateString(TmpStream.str(), TmpTok);
1127 DATELoc = TmpTok.getLocation();
1128 }
1129
1130 {
1131 SmallString<32> TmpBuffer;
1132 llvm::raw_svector_ostream TmpStream(TmpBuffer);
1133 if (TM)
1134 TmpStream << llvm::format("\"%02d:%02d:%02d\"", TM->tm_hour, TM->tm_min,
1135 TM->tm_sec);
1136 else
1137 TmpStream << "??:??:??";
1138 Token TmpTok;
1139 TmpTok.startToken();
1140 PP.CreateString(TmpStream.str(), TmpTok);
1141 TIMELoc = TmpTok.getLocation();
1142 }
1143}
1144
1145/// HasFeature - Return true if we recognize and implement the feature
1146/// specified by the identifier as a standard language feature.
1147static bool HasFeature(const Preprocessor &PP, StringRef Feature) {
1148 const LangOptions &LangOpts = PP.getLangOpts();
1149
1150 // Normalize the feature name, __foo__ becomes foo.
1151 if (Feature.starts_with("__") && Feature.ends_with("__") &&
1152 Feature.size() >= 4)
1153 Feature = Feature.substr(2, Feature.size() - 4);
1154
1155#define FEATURE(Name, Predicate) .Case(#Name, Predicate)
1156 return llvm::StringSwitch<bool>(Feature)
1157#include "clang/Basic/Features.def"
1158 .Default(false);
1159#undef FEATURE
1160}
1161
1162/// HasExtension - Return true if we recognize and implement the feature
1163/// specified by the identifier, either as an extension or a standard language
1164/// feature.
1165static bool HasExtension(const Preprocessor &PP, StringRef Extension) {
1166 if (HasFeature(PP, Extension))
1167 return true;
1168
1169 // If the use of an extension results in an error diagnostic, extensions are
1170 // effectively unavailable, so just return false here.
1173 return false;
1174
1175 const LangOptions &LangOpts = PP.getLangOpts();
1176
1177 // Normalize the extension name, __foo__ becomes foo.
1178 if (Extension.starts_with("__") && Extension.ends_with("__") &&
1179 Extension.size() >= 4)
1180 Extension = Extension.substr(2, Extension.size() - 4);
1181
1182 // Because we inherit the feature list from HasFeature, this string switch
1183 // must be less restrictive than HasFeature's.
1184#define EXTENSION(Name, Predicate) .Case(#Name, Predicate)
1185 return llvm::StringSwitch<bool>(Extension)
1186#include "clang/Basic/Features.def"
1187 .Default(false);
1188#undef EXTENSION
1189}
1190
1191/// EvaluateHasIncludeCommon - Process a '__has_include("path")'
1192/// or '__has_include_next("path")' expression.
1193/// Returns true if successful.
1195 Preprocessor &PP,
1196 ConstSearchDirIterator LookupFrom,
1197 const FileEntry *LookupFromFile) {
1198 // Save the location of the current token. If a '(' is later found, use
1199 // that location. If not, use the end of this location instead.
1200 SourceLocation LParenLoc = Tok.getLocation();
1201
1202 // These expressions are only allowed within a preprocessor directive.
1203 if (!PP.isParsingIfOrElifDirective()) {
1204 PP.Diag(LParenLoc, diag::err_pp_directive_required) << II;
1205 // Return a valid identifier token.
1206 assert(Tok.is(tok::identifier));
1207 Tok.setIdentifierInfo(II);
1208 return false;
1209 }
1210
1211 // Get '('. If we don't have a '(', try to form a header-name token.
1212 do {
1213 if (PP.LexHeaderName(Tok))
1214 return false;
1215 } while (Tok.getKind() == tok::comment);
1216
1217 // Ensure we have a '('.
1218 if (Tok.isNot(tok::l_paren)) {
1219 // No '(', use end of last token.
1220 LParenLoc = PP.getLocForEndOfToken(LParenLoc);
1221 PP.Diag(LParenLoc, diag::err_pp_expected_after) << II << tok::l_paren;
1222 // If the next token looks like a filename or the start of one,
1223 // assume it is and process it as such.
1224 if (Tok.isNot(tok::header_name))
1225 return false;
1226 } else {
1227 // Save '(' location for possible missing ')' message.
1228 LParenLoc = Tok.getLocation();
1229 if (PP.LexHeaderName(Tok))
1230 return false;
1231 }
1232
1233 if (Tok.isNot(tok::header_name)) {
1234 PP.Diag(Tok.getLocation(), diag::err_pp_expects_filename);
1235 return false;
1236 }
1237
1238 // Reserve a buffer to get the spelling.
1239 SmallString<128> FilenameBuffer;
1240 bool Invalid = false;
1241 StringRef Filename = PP.getSpelling(Tok, FilenameBuffer, &Invalid);
1242 if (Invalid)
1243 return false;
1244
1245 SourceLocation FilenameLoc = Tok.getLocation();
1246
1247 // Get ')'.
1248 PP.LexNonComment(Tok);
1249
1250 // Ensure we have a trailing ).
1251 if (Tok.isNot(tok::r_paren)) {
1252 PP.Diag(PP.getLocForEndOfToken(FilenameLoc), diag::err_pp_expected_after)
1253 << II << tok::r_paren;
1254 PP.Diag(LParenLoc, diag::note_matching) << tok::l_paren;
1255 return false;
1256 }
1257
1258 bool isAngled = PP.GetIncludeFilenameSpelling(Tok.getLocation(), Filename);
1259 // If GetIncludeFilenameSpelling set the start ptr to null, there was an
1260 // error.
1261 if (Filename.empty())
1262 return false;
1263
1264 // Passing this to LookupFile forces header search to check whether the found
1265 // file belongs to a module. Skipping that check could incorrectly mark
1266 // modular header as textual, causing issues down the line.
1268
1269 // Search include directories.
1271 PP.LookupFile(FilenameLoc, Filename, isAngled, LookupFrom, LookupFromFile,
1272 nullptr, nullptr, nullptr, &KH, nullptr, nullptr);
1273
1274 if (PPCallbacks *Callbacks = PP.getPPCallbacks()) {
1276 if (File)
1278 Callbacks->HasInclude(FilenameLoc, Filename, isAngled, File, FileType);
1279 }
1280
1281 // Get the result value. A result of true means the file exists.
1282 return File.has_value();
1283}
1284
1285/// EvaluateHasEmbed - Process a '__has_embed("foo" params...)' expression.
1286/// Returns a filled optional with the value if successful; otherwise, empty.
1287EmbedResult Preprocessor::EvaluateHasEmbed(Token &Tok, IdentifierInfo *II) {
1288 // These expressions are only allowed within a preprocessor directive.
1289 if (!this->isParsingIfOrElifDirective()) {
1290 Diag(Tok, diag::err_pp_directive_required) << II;
1291 // Return a valid identifier token.
1292 assert(Tok.is(tok::identifier));
1293 Tok.setIdentifierInfo(II);
1294 return EmbedResult::Invalid;
1295 }
1296
1297 // Ensure we have a '('.
1298 LexUnexpandedToken(Tok);
1299 if (Tok.isNot(tok::l_paren)) {
1300 Diag(Tok, diag::err_pp_expected_after) << II << tok::l_paren;
1301 // If the next token looks like a filename or the start of one,
1302 // assume it is and process it as such.
1303 return EmbedResult::Invalid;
1304 }
1305
1306 // Save '(' location for possible missing ')' message and then lex the header
1307 // name token for the embed resource.
1308 SourceLocation LParenLoc = Tok.getLocation();
1309 if (this->LexHeaderName(Tok))
1310 return EmbedResult::Invalid;
1311
1312 if (Tok.isNot(tok::header_name)) {
1313 Diag(Tok.getLocation(), diag::err_pp_expects_filename);
1314 return EmbedResult::Invalid;
1315 }
1316
1317 SourceLocation FilenameLoc = Tok.getLocation();
1318 Token FilenameTok = Tok;
1319
1320 std::optional<LexEmbedParametersResult> Params =
1321 this->LexEmbedParameters(Tok, /*ForHasEmbed=*/true);
1322 assert((Params || Tok.is(tok::eod)) &&
1323 "expected success or to be at the end of the directive");
1324
1325 if (!Params)
1326 return EmbedResult::Invalid;
1327
1328 if (Params->UnrecognizedParams > 0)
1329 return EmbedResult::NotFound;
1330
1331 if (!Tok.is(tok::r_paren)) {
1332 Diag(this->getLocForEndOfToken(FilenameLoc), diag::err_pp_expected_after)
1333 << II << tok::r_paren;
1334 Diag(LParenLoc, diag::note_matching) << tok::l_paren;
1335 if (Tok.isNot(tok::eod))
1337 return EmbedResult::Invalid;
1338 }
1339
1340 SmallString<128> FilenameBuffer;
1341 StringRef Filename = this->getSpelling(FilenameTok, FilenameBuffer);
1342 bool isAngled =
1343 this->GetIncludeFilenameSpelling(FilenameTok.getLocation(), Filename);
1344 // If GetIncludeFilenameSpelling set the start ptr to null, there was an
1345 // error.
1346 assert(!Filename.empty());
1347 const FileEntry *LookupFromFile =
1349 : static_cast<FileEntry *>(nullptr);
1350 OptionalFileEntryRef MaybeFileEntry =
1351 this->LookupEmbedFile(Filename, isAngled, false, LookupFromFile);
1352 if (Callbacks) {
1353 Callbacks->HasEmbed(LParenLoc, Filename, isAngled, MaybeFileEntry);
1354 }
1355 if (!MaybeFileEntry)
1356 return EmbedResult::NotFound;
1357
1358 size_t FileSize = MaybeFileEntry->getSize();
1359 // First, "offset" into the file (this reduces the amount of data we can read
1360 // from the file).
1361 if (Params->MaybeOffsetParam) {
1362 if (Params->MaybeOffsetParam->Offset > FileSize)
1363 FileSize = 0;
1364 else
1365 FileSize -= Params->MaybeOffsetParam->Offset;
1366 }
1367
1368 // Second, limit the data from the file (this also reduces the amount of data
1369 // we can read from the file).
1370 if (Params->MaybeLimitParam) {
1371 if (Params->MaybeLimitParam->Limit > FileSize)
1372 FileSize = 0;
1373 else
1374 FileSize = Params->MaybeLimitParam->Limit;
1375 }
1376
1377 // If we have no data left to read, the file is empty, otherwise we have the
1378 // expected resource.
1379 if (FileSize == 0)
1380 return EmbedResult::Empty;
1381 return EmbedResult::Found;
1382}
1383
1384bool Preprocessor::EvaluateHasInclude(Token &Tok, IdentifierInfo *II) {
1385 return EvaluateHasIncludeCommon(Tok, II, *this, nullptr, nullptr);
1386}
1387
1388bool Preprocessor::EvaluateHasIncludeNext(Token &Tok, IdentifierInfo *II) {
1389 ConstSearchDirIterator Lookup = nullptr;
1390 const FileEntry *LookupFromFile;
1391 std::tie(Lookup, LookupFromFile) = getIncludeNextStart(Tok);
1392
1393 return EvaluateHasIncludeCommon(Tok, II, *this, Lookup, LookupFromFile);
1394}
1395
1396/// Process single-argument builtin feature-like macros that return
1397/// integer values.
1398static void EvaluateFeatureLikeBuiltinMacro(llvm::raw_svector_ostream& OS,
1399 Token &Tok, IdentifierInfo *II,
1400 Preprocessor &PP, bool ExpandArgs,
1401 llvm::function_ref<
1402 int(Token &Tok,
1403 bool &HasLexedNextTok)> Op) {
1404 // Parse the initial '('.
1405 PP.LexUnexpandedToken(Tok);
1406 if (Tok.isNot(tok::l_paren)) {
1407 PP.Diag(Tok.getLocation(), diag::err_pp_expected_after) << II
1408 << tok::l_paren;
1409
1410 // Provide a dummy '0' value on output stream to elide further errors.
1411 if (!Tok.isOneOf(tok::eof, tok::eod)) {
1412 OS << 0;
1413 Tok.setKind(tok::numeric_constant);
1414 }
1415 return;
1416 }
1417
1418 unsigned ParenDepth = 1;
1419 SourceLocation LParenLoc = Tok.getLocation();
1420 std::optional<int> Result;
1421
1422 Token ResultTok;
1423 bool SuppressDiagnostic = false;
1424 while (true) {
1425 // Parse next token.
1426 if (ExpandArgs)
1427 PP.Lex(Tok);
1428 else
1429 PP.LexUnexpandedToken(Tok);
1430
1431already_lexed:
1432 switch (Tok.getKind()) {
1433 case tok::eof:
1434 case tok::eod:
1435 // Don't provide even a dummy value if the eod or eof marker is
1436 // reached. Simply provide a diagnostic.
1437 PP.Diag(Tok.getLocation(), diag::err_unterm_macro_invoc);
1438 return;
1439
1440 case tok::comma:
1441 if (!SuppressDiagnostic) {
1442 PP.Diag(Tok.getLocation(), diag::err_too_many_args_in_macro_invoc);
1443 SuppressDiagnostic = true;
1444 }
1445 continue;
1446
1447 case tok::l_paren:
1448 ++ParenDepth;
1449 if (Result)
1450 break;
1451 if (!SuppressDiagnostic) {
1452 PP.Diag(Tok.getLocation(), diag::err_pp_nested_paren) << II;
1453 SuppressDiagnostic = true;
1454 }
1455 continue;
1456
1457 case tok::r_paren:
1458 if (--ParenDepth > 0)
1459 continue;
1460
1461 // The last ')' has been reached; return the value if one found or
1462 // a diagnostic and a dummy value.
1463 if (Result) {
1464 OS << *Result;
1465 // For strict conformance to __has_cpp_attribute rules, use 'L'
1466 // suffix for dated literals.
1467 if (*Result > 1)
1468 OS << 'L';
1469 } else {
1470 OS << 0;
1471 if (!SuppressDiagnostic)
1472 PP.Diag(Tok.getLocation(), diag::err_too_few_args_in_macro_invoc);
1473 }
1474 Tok.setKind(tok::numeric_constant);
1475 return;
1476
1477 default: {
1478 // Parse the macro argument, if one not found so far.
1479 if (Result)
1480 break;
1481
1482 bool HasLexedNextToken = false;
1483 Result = Op(Tok, HasLexedNextToken);
1484 ResultTok = Tok;
1485 if (HasLexedNextToken)
1486 goto already_lexed;
1487 continue;
1488 }
1489 }
1490
1491 // Diagnose missing ')'.
1492 if (!SuppressDiagnostic) {
1493 if (auto Diag = PP.Diag(Tok.getLocation(), diag::err_pp_expected_after)) {
1494 if (IdentifierInfo *LastII = ResultTok.getIdentifierInfo())
1495 Diag << LastII;
1496 else
1497 Diag << ResultTok.getKind();
1498 Diag << tok::r_paren << ResultTok.getLocation();
1499 }
1500 PP.Diag(LParenLoc, diag::note_matching) << tok::l_paren;
1501 SuppressDiagnostic = true;
1502 }
1503 }
1504}
1505
1506/// Helper function to return the IdentifierInfo structure of a Token
1507/// or generate a diagnostic if none available.
1509 Preprocessor &PP,
1510 signed DiagID) {
1511 IdentifierInfo *II;
1512 if (!Tok.isAnnotation() && (II = Tok.getIdentifierInfo()))
1513 return II;
1514
1515 PP.Diag(Tok.getLocation(), DiagID);
1516 return nullptr;
1517}
1518
1519/// Implements the __is_target_arch builtin macro.
1520static bool isTargetArch(const TargetInfo &TI, const IdentifierInfo *II) {
1521 std::string ArchName = II->getName().lower() + "--";
1522 llvm::Triple Arch(ArchName);
1523 const llvm::Triple &TT = TI.getTriple();
1524 if (TT.isThumb()) {
1525 // arm matches thumb or thumbv7. armv7 matches thumbv7.
1526 if ((Arch.getSubArch() == llvm::Triple::NoSubArch ||
1527 Arch.getSubArch() == TT.getSubArch()) &&
1528 ((TT.getArch() == llvm::Triple::thumb &&
1529 Arch.getArch() == llvm::Triple::arm) ||
1530 (TT.getArch() == llvm::Triple::thumbeb &&
1531 Arch.getArch() == llvm::Triple::armeb)))
1532 return true;
1533 }
1534 // Check the parsed arch when it has no sub arch to allow Clang to
1535 // match thumb to thumbv7 but to prohibit matching thumbv6 to thumbv7.
1536 return (Arch.getSubArch() == llvm::Triple::NoSubArch ||
1537 Arch.getSubArch() == TT.getSubArch()) &&
1538 Arch.getArch() == TT.getArch();
1539}
1540
1541/// Implements the __is_target_vendor builtin macro.
1542static bool isTargetVendor(const TargetInfo &TI, const IdentifierInfo *II) {
1543 StringRef VendorName = TI.getTriple().getVendorName();
1544 if (VendorName.empty())
1545 VendorName = "unknown";
1546 return VendorName.equals_insensitive(II->getName());
1547}
1548
1549/// Implements the __is_target_os builtin macro.
1550static bool isTargetOS(const TargetInfo &TI, const IdentifierInfo *II) {
1551 std::string OSName =
1552 (llvm::Twine("unknown-unknown-") + II->getName().lower()).str();
1553 llvm::Triple OS(OSName);
1554 if (OS.getOS() == llvm::Triple::Darwin) {
1555 // Darwin matches macos, ios, etc.
1556 return TI.getTriple().isOSDarwin();
1557 }
1558 return TI.getTriple().getOS() == OS.getOS();
1559}
1560
1561/// Implements the __is_target_environment builtin macro.
1562static bool isTargetEnvironment(const TargetInfo &TI,
1563 const IdentifierInfo *II) {
1564 std::string EnvName = (llvm::Twine("---") + II->getName().lower()).str();
1565 llvm::Triple Env(EnvName);
1566 // The unknown environment is matched only if
1567 // '__is_target_environment(unknown)' is used.
1568 if (Env.getEnvironment() == llvm::Triple::UnknownEnvironment &&
1569 EnvName != "---unknown")
1570 return false;
1571 return TI.getTriple().getEnvironment() == Env.getEnvironment();
1572}
1573
1574/// Implements the __is_target_variant_os builtin macro.
1575static bool isTargetVariantOS(const TargetInfo &TI, const IdentifierInfo *II) {
1576 if (TI.getTriple().isOSDarwin()) {
1577 const llvm::Triple *VariantTriple = TI.getDarwinTargetVariantTriple();
1578 if (!VariantTriple)
1579 return false;
1580
1581 std::string OSName =
1582 (llvm::Twine("unknown-unknown-") + II->getName().lower()).str();
1583 llvm::Triple OS(OSName);
1584 if (OS.getOS() == llvm::Triple::Darwin) {
1585 // Darwin matches macos, ios, etc.
1586 return VariantTriple->isOSDarwin();
1587 }
1588 return VariantTriple->getOS() == OS.getOS();
1589 }
1590 return false;
1591}
1592
1593/// Implements the __is_target_variant_environment builtin macro.
1595 const IdentifierInfo *II) {
1596 if (TI.getTriple().isOSDarwin()) {
1597 const llvm::Triple *VariantTriple = TI.getDarwinTargetVariantTriple();
1598 if (!VariantTriple)
1599 return false;
1600 std::string EnvName = (llvm::Twine("---") + II->getName().lower()).str();
1601 llvm::Triple Env(EnvName);
1602 return VariantTriple->getEnvironment() == Env.getEnvironment();
1603 }
1604 return false;
1605}
1606
1607/// ExpandBuiltinMacro - If an identifier token is read that is to be expanded
1608/// as a builtin macro, handle it and return the next token as 'Tok'.
1609void Preprocessor::ExpandBuiltinMacro(Token &Tok) {
1610 // Figure out which token this is.
1612 assert(II && "Can't be a macro without id info!");
1613
1614 // If this is an _Pragma or Microsoft __pragma directive, expand it,
1615 // invoke the pragma handler, then lex the token after it.
1616 if (II == Ident_Pragma)
1617 return Handle_Pragma(Tok);
1618 else if (II == Ident__pragma) // in non-MS mode this is null
1619 return HandleMicrosoft__pragma(Tok);
1620
1621 ++NumBuiltinMacroExpanded;
1622
1623 SmallString<128> TmpBuffer;
1624 llvm::raw_svector_ostream OS(TmpBuffer);
1625
1626 // Set up the return result.
1627 Tok.setIdentifierInfo(nullptr);
1629 bool IsAtStartOfLine = Tok.isAtStartOfLine();
1630 bool HasLeadingSpace = Tok.hasLeadingSpace();
1631
1632 if (II == Ident__LINE__) {
1633 // C99 6.10.8: "__LINE__: The presumed line number (within the current
1634 // source file) of the current source line (an integer constant)". This can
1635 // be affected by #line.
1637
1638 // Advance to the location of the first _, this might not be the first byte
1639 // of the token if it starts with an escaped newline.
1641
1642 // One wrinkle here is that GCC expands __LINE__ to location of the *end* of
1643 // a macro expansion. This doesn't matter for object-like macros, but
1644 // can matter for a function-like macro that expands to contain __LINE__.
1645 // Skip down through expansion points until we find a file loc for the
1646 // end of the expansion history.
1647 Loc = SourceMgr.getExpansionRange(Loc).getEnd();
1648 PresumedLoc PLoc = SourceMgr.getPresumedLoc(Loc);
1649
1650 // __LINE__ expands to a simple numeric value.
1651 OS << (PLoc.isValid()? PLoc.getLine() : 1);
1652 Tok.setKind(tok::numeric_constant);
1653 } else if (II == Ident__FILE__ || II == Ident__BASE_FILE__ ||
1654 II == Ident__FILE_NAME__) {
1655 // C99 6.10.8: "__FILE__: The presumed name of the current source file (a
1656 // character string literal)". This can be affected by #line.
1657 PresumedLoc PLoc = SourceMgr.getPresumedLoc(Tok.getLocation());
1658
1659 // __BASE_FILE__ is a GNU extension that returns the top of the presumed
1660 // #include stack instead of the current file.
1661 if (II == Ident__BASE_FILE__ && PLoc.isValid()) {
1662 SourceLocation NextLoc = PLoc.getIncludeLoc();
1663 while (NextLoc.isValid()) {
1664 PLoc = SourceMgr.getPresumedLoc(NextLoc);
1665 if (PLoc.isInvalid())
1666 break;
1667
1668 NextLoc = PLoc.getIncludeLoc();
1669 }
1670 }
1671
1672 // Escape this filename. Turn '\' -> '\\' '"' -> '\"'
1674 if (PLoc.isValid()) {
1675 // __FILE_NAME__ is a Clang-specific extension that expands to the
1676 // the last part of __FILE__.
1677 if (II == Ident__FILE_NAME__) {
1679 } else {
1680 FN += PLoc.getFilename();
1682 }
1683 Lexer::Stringify(FN);
1684 OS << '"' << FN << '"';
1685 }
1686 Tok.setKind(tok::string_literal);
1687 } else if (II == Ident__DATE__) {
1688 Diag(Tok.getLocation(), diag::warn_pp_date_time);
1689 if (!DATELoc.isValid())
1690 ComputeDATE_TIME(DATELoc, TIMELoc, *this);
1691 Tok.setKind(tok::string_literal);
1692 Tok.setLength(strlen("\"Mmm dd yyyy\""));
1693 Tok.setLocation(SourceMgr.createExpansionLoc(DATELoc, Tok.getLocation(),
1694 Tok.getLocation(),
1695 Tok.getLength()));
1696 return;
1697 } else if (II == Ident__TIME__) {
1698 Diag(Tok.getLocation(), diag::warn_pp_date_time);
1699 if (!TIMELoc.isValid())
1700 ComputeDATE_TIME(DATELoc, TIMELoc, *this);
1701 Tok.setKind(tok::string_literal);
1702 Tok.setLength(strlen("\"hh:mm:ss\""));
1703 Tok.setLocation(SourceMgr.createExpansionLoc(TIMELoc, Tok.getLocation(),
1704 Tok.getLocation(),
1705 Tok.getLength()));
1706 return;
1707 } else if (II == Ident__INCLUDE_LEVEL__) {
1708 // Compute the presumed include depth of this token. This can be affected
1709 // by GNU line markers.
1710 unsigned Depth = 0;
1711
1712 PresumedLoc PLoc = SourceMgr.getPresumedLoc(Tok.getLocation());
1713 if (PLoc.isValid()) {
1714 PLoc = SourceMgr.getPresumedLoc(PLoc.getIncludeLoc());
1715 for (; PLoc.isValid(); ++Depth)
1716 PLoc = SourceMgr.getPresumedLoc(PLoc.getIncludeLoc());
1717 }
1718
1719 // __INCLUDE_LEVEL__ expands to a simple numeric value.
1720 OS << Depth;
1721 Tok.setKind(tok::numeric_constant);
1722 } else if (II == Ident__TIMESTAMP__) {
1723 Diag(Tok.getLocation(), diag::warn_pp_date_time);
1724 // MSVC, ICC, GCC, VisualAge C++ extension. The generated string should be
1725 // of the form "Ddd Mmm dd hh::mm::ss yyyy", which is returned by asctime.
1726 std::string Result;
1727 std::stringstream TmpStream;
1728 TmpStream.imbue(std::locale("C"));
1729 if (getPreprocessorOpts().SourceDateEpoch) {
1730 time_t TT = *getPreprocessorOpts().SourceDateEpoch;
1731 std::tm *TM = std::gmtime(&TT);
1732 TmpStream << std::put_time(TM, "%a %b %e %T %Y");
1733 } else {
1734 // Get the file that we are lexing out of. If we're currently lexing from
1735 // a macro, dig into the include stack.
1736 const FileEntry *CurFile = nullptr;
1737 if (PreprocessorLexer *TheLexer = getCurrentFileLexer())
1738 CurFile = SourceMgr.getFileEntryForID(TheLexer->getFileID());
1739 if (CurFile) {
1740 time_t TT = CurFile->getModificationTime();
1741 struct tm *TM = localtime(&TT);
1742 TmpStream << std::put_time(TM, "%a %b %e %T %Y");
1743 }
1744 }
1745 Result = TmpStream.str();
1746 if (Result.empty())
1747 Result = "??? ??? ?? ??:??:?? ????";
1748 OS << '"' << Result << '"';
1749 Tok.setKind(tok::string_literal);
1750 } else if (II == Ident__FLT_EVAL_METHOD__) {
1751 // __FLT_EVAL_METHOD__ is set to the default value.
1752 OS << getTUFPEvalMethod();
1753 // __FLT_EVAL_METHOD__ expands to a simple numeric value.
1754 Tok.setKind(tok::numeric_constant);
1755 if (getLastFPEvalPragmaLocation().isValid()) {
1756 // The program is ill-formed. The value of __FLT_EVAL_METHOD__ is altered
1757 // by the pragma.
1758 Diag(Tok, diag::err_illegal_use_of_flt_eval_macro);
1759 Diag(getLastFPEvalPragmaLocation(), diag::note_pragma_entered_here);
1760 }
1761 } else if (II == Ident__COUNTER__) {
1762 // __COUNTER__ expands to a simple numeric value.
1763 OS << CounterValue++;
1764 Tok.setKind(tok::numeric_constant);
1765 } else if (II == Ident__has_feature) {
1766 EvaluateFeatureLikeBuiltinMacro(OS, Tok, II, *this, false,
1767 [this](Token &Tok, bool &HasLexedNextToken) -> int {
1769 diag::err_feature_check_malformed);
1770 return II && HasFeature(*this, II->getName());
1771 });
1772 } else if (II == Ident__has_extension) {
1773 EvaluateFeatureLikeBuiltinMacro(OS, Tok, II, *this, false,
1774 [this](Token &Tok, bool &HasLexedNextToken) -> int {
1776 diag::err_feature_check_malformed);
1777 return II && HasExtension(*this, II->getName());
1778 });
1779 } else if (II == Ident__has_builtin) {
1780 EvaluateFeatureLikeBuiltinMacro(OS, Tok, II, *this, false,
1781 [this](Token &Tok, bool &HasLexedNextToken) -> int {
1783 diag::err_feature_check_malformed);
1784 if (!II)
1785 return false;
1786 else if (II->getBuiltinID() != 0) {
1787 switch (II->getBuiltinID()) {
1788 case Builtin::BI__builtin_cpu_is:
1789 return getTargetInfo().supportsCpuIs();
1790 case Builtin::BI__builtin_cpu_init:
1791 return getTargetInfo().supportsCpuInit();
1792 case Builtin::BI__builtin_cpu_supports:
1794 case Builtin::BI__builtin_operator_new:
1795 case Builtin::BI__builtin_operator_delete:
1796 // denotes date of behavior change to support calling arbitrary
1797 // usual allocation and deallocation functions. Required by libc++
1798 return 201802;
1799 default:
1801 getBuiltinInfo().getRequiredFeatures(II->getBuiltinID()),
1802 getTargetInfo().getTargetOpts().FeatureMap);
1803 }
1804 return true;
1805 } else if (II->getTokenID() != tok::identifier ||
1807 // Treat all keywords that introduce a custom syntax of the form
1808 //
1809 // '__some_keyword' '(' [...] ')'
1810 //
1811 // as being "builtin functions", even if the syntax isn't a valid
1812 // function call (for example, because the builtin takes a type
1813 // argument).
1814 if (II->getName().starts_with("__builtin_") ||
1815 II->getName().starts_with("__is_") ||
1816 II->getName().starts_with("__has_"))
1817 return true;
1818 return llvm::StringSwitch<bool>(II->getName())
1819 .Case("__array_rank", true)
1820 .Case("__array_extent", true)
1821#define TRANSFORM_TYPE_TRAIT_DEF(_, Trait) .Case("__" #Trait, true)
1822#include "clang/Basic/TransformTypeTraits.def"
1823 .Default(false);
1824 } else {
1825 return llvm::StringSwitch<bool>(II->getName())
1826 // Report builtin templates as being builtins.
1827 .Case("__make_integer_seq", getLangOpts().CPlusPlus)
1828 .Case("__type_pack_element", getLangOpts().CPlusPlus)
1829 // Likewise for some builtin preprocessor macros.
1830 // FIXME: This is inconsistent; we usually suggest detecting
1831 // builtin macros via #ifdef. Don't add more cases here.
1832 .Case("__is_target_arch", true)
1833 .Case("__is_target_vendor", true)
1834 .Case("__is_target_os", true)
1835 .Case("__is_target_environment", true)
1836 .Case("__is_target_variant_os", true)
1837 .Case("__is_target_variant_environment", true)
1838 .Default(false);
1839 }
1840 });
1841 } else if (II == Ident__has_constexpr_builtin) {
1843 OS, Tok, II, *this, false,
1844 [this](Token &Tok, bool &HasLexedNextToken) -> int {
1846 Tok, *this, diag::err_feature_check_malformed);
1847 if (!II)
1848 return false;
1849 unsigned BuiltinOp = II->getBuiltinID();
1850 return BuiltinOp != 0 &&
1851 this->getBuiltinInfo().isConstantEvaluated(BuiltinOp);
1852 });
1853 } else if (II == Ident__is_identifier) {
1854 EvaluateFeatureLikeBuiltinMacro(OS, Tok, II, *this, false,
1855 [](Token &Tok, bool &HasLexedNextToken) -> int {
1856 return Tok.is(tok::identifier);
1857 });
1858 } else if (II == Ident__has_attribute) {
1859 EvaluateFeatureLikeBuiltinMacro(OS, Tok, II, *this, true,
1860 [this](Token &Tok, bool &HasLexedNextToken) -> int {
1862 diag::err_feature_check_malformed);
1864 II, getTargetInfo(), getLangOpts())
1865 : 0;
1866 });
1867 } else if (II == Ident__has_declspec) {
1868 EvaluateFeatureLikeBuiltinMacro(OS, Tok, II, *this, true,
1869 [this](Token &Tok, bool &HasLexedNextToken) -> int {
1871 diag::err_feature_check_malformed);
1872 if (II) {
1873 const LangOptions &LangOpts = getLangOpts();
1874 return LangOpts.DeclSpecKeyword &&
1876 II, getTargetInfo(), LangOpts);
1877 }
1878
1879 return false;
1880 });
1881 } else if (II == Ident__has_cpp_attribute ||
1882 II == Ident__has_c_attribute) {
1883 bool IsCXX = II == Ident__has_cpp_attribute;
1884 EvaluateFeatureLikeBuiltinMacro(OS, Tok, II, *this, true,
1885 [&](Token &Tok, bool &HasLexedNextToken) -> int {
1886 IdentifierInfo *ScopeII = nullptr;
1888 Tok, *this, diag::err_feature_check_malformed);
1889 if (!II)
1890 return false;
1891
1892 // It is possible to receive a scope token. Read the "::", if it is
1893 // available, and the subsequent identifier.
1894 LexUnexpandedToken(Tok);
1895 if (Tok.isNot(tok::coloncolon))
1896 HasLexedNextToken = true;
1897 else {
1898 ScopeII = II;
1899 // Lex an expanded token for the attribute name.
1900 Lex(Tok);
1901 II = ExpectFeatureIdentifierInfo(Tok, *this,
1902 diag::err_feature_check_malformed);
1903 }
1904
1908 return II ? hasAttribute(Syntax, ScopeII, II, getTargetInfo(),
1909 getLangOpts())
1910 : 0;
1911 });
1912 } else if (II == Ident__has_include ||
1913 II == Ident__has_include_next) {
1914 // The argument to these two builtins should be a parenthesized
1915 // file name string literal using angle brackets (<>) or
1916 // double-quotes ("").
1917 bool Value;
1918 if (II == Ident__has_include)
1919 Value = EvaluateHasInclude(Tok, II);
1920 else
1921 Value = EvaluateHasIncludeNext(Tok, II);
1922
1923 if (Tok.isNot(tok::r_paren))
1924 return;
1925 OS << (int)Value;
1926 Tok.setKind(tok::numeric_constant);
1927 } else if (II == Ident__has_embed) {
1928 // The argument to these two builtins should be a parenthesized
1929 // file name string literal using angle brackets (<>) or
1930 // double-quotes (""), optionally followed by a series of
1931 // arguments similar to form like attributes.
1932 EmbedResult Value = EvaluateHasEmbed(Tok, II);
1934 return;
1935
1936 Tok.setKind(tok::numeric_constant);
1937 OS << static_cast<int>(Value);
1938 } else if (II == Ident__has_warning) {
1939 // The argument should be a parenthesized string literal.
1940 EvaluateFeatureLikeBuiltinMacro(OS, Tok, II, *this, false,
1941 [this](Token &Tok, bool &HasLexedNextToken) -> int {
1942 std::string WarningName;
1943 SourceLocation StrStartLoc = Tok.getLocation();
1944
1945 HasLexedNextToken = Tok.is(tok::string_literal);
1946 if (!FinishLexStringLiteral(Tok, WarningName, "'__has_warning'",
1947 /*AllowMacroExpansion=*/false))
1948 return false;
1949
1950 // FIXME: Should we accept "-R..." flags here, or should that be
1951 // handled by a separate __has_remark?
1952 if (WarningName.size() < 3 || WarningName[0] != '-' ||
1953 WarningName[1] != 'W') {
1954 Diag(StrStartLoc, diag::warn_has_warning_invalid_option);
1955 return false;
1956 }
1957
1958 // Finally, check if the warning flags maps to a diagnostic group.
1959 // We construct a SmallVector here to talk to getDiagnosticIDs().
1960 // Although we don't use the result, this isn't a hot path, and not
1961 // worth special casing.
1963 return !getDiagnostics().getDiagnosticIDs()->
1965 WarningName.substr(2), Diags);
1966 });
1967 } else if (II == Ident__building_module) {
1968 // The argument to this builtin should be an identifier. The
1969 // builtin evaluates to 1 when that identifier names the module we are
1970 // currently building.
1971 EvaluateFeatureLikeBuiltinMacro(OS, Tok, II, *this, false,
1972 [this](Token &Tok, bool &HasLexedNextToken) -> int {
1974 diag::err_expected_id_building_module);
1975 return getLangOpts().isCompilingModule() && II &&
1976 (II->getName() == getLangOpts().CurrentModule);
1977 });
1978 } else if (II == Ident__MODULE__) {
1979 // The current module as an identifier.
1980 OS << getLangOpts().CurrentModule;
1981 IdentifierInfo *ModuleII = getIdentifierInfo(getLangOpts().CurrentModule);
1982 Tok.setIdentifierInfo(ModuleII);
1983 Tok.setKind(ModuleII->getTokenID());
1984 } else if (II == Ident__identifier) {
1986
1987 // We're expecting '__identifier' '(' identifier ')'. Try to recover
1988 // if the parens are missing.
1989 LexNonComment(Tok);
1990 if (Tok.isNot(tok::l_paren)) {
1991 // No '(', use end of last token.
1992 Diag(getLocForEndOfToken(Loc), diag::err_pp_expected_after)
1993 << II << tok::l_paren;
1994 // If the next token isn't valid as our argument, we can't recover.
1995 if (!Tok.isAnnotation() && Tok.getIdentifierInfo())
1996 Tok.setKind(tok::identifier);
1997 return;
1998 }
1999
2000 SourceLocation LParenLoc = Tok.getLocation();
2001 LexNonComment(Tok);
2002
2003 if (!Tok.isAnnotation() && Tok.getIdentifierInfo())
2004 Tok.setKind(tok::identifier);
2005 else if (Tok.is(tok::string_literal) && !Tok.hasUDSuffix()) {
2006 StringLiteralParser Literal(Tok, *this,
2008 if (Literal.hadError)
2009 return;
2010
2012 Tok.setKind(tok::identifier);
2013 } else {
2014 Diag(Tok.getLocation(), diag::err_pp_identifier_arg_not_identifier)
2015 << Tok.getKind();
2016 // Don't walk past anything that's not a real token.
2017 if (Tok.isOneOf(tok::eof, tok::eod) || Tok.isAnnotation())
2018 return;
2019 }
2020
2021 // Discard the ')', preserving 'Tok' as our result.
2022 Token RParen;
2023 LexNonComment(RParen);
2024 if (RParen.isNot(tok::r_paren)) {
2025 Diag(getLocForEndOfToken(Tok.getLocation()), diag::err_pp_expected_after)
2026 << Tok.getKind() << tok::r_paren;
2027 Diag(LParenLoc, diag::note_matching) << tok::l_paren;
2028 }
2029 return;
2030 } else if (II == Ident__is_target_arch) {
2032 OS, Tok, II, *this, false,
2033 [this](Token &Tok, bool &HasLexedNextToken) -> int {
2035 Tok, *this, diag::err_feature_check_malformed);
2036 return II && isTargetArch(getTargetInfo(), II);
2037 });
2038 } else if (II == Ident__is_target_vendor) {
2040 OS, Tok, II, *this, false,
2041 [this](Token &Tok, bool &HasLexedNextToken) -> int {
2043 Tok, *this, diag::err_feature_check_malformed);
2044 return II && isTargetVendor(getTargetInfo(), II);
2045 });
2046 } else if (II == Ident__is_target_os) {
2048 OS, Tok, II, *this, false,
2049 [this](Token &Tok, bool &HasLexedNextToken) -> int {
2051 Tok, *this, diag::err_feature_check_malformed);
2052 return II && isTargetOS(getTargetInfo(), II);
2053 });
2054 } else if (II == Ident__is_target_environment) {
2056 OS, Tok, II, *this, false,
2057 [this](Token &Tok, bool &HasLexedNextToken) -> int {
2059 Tok, *this, diag::err_feature_check_malformed);
2060 return II && isTargetEnvironment(getTargetInfo(), II);
2061 });
2062 } else if (II == Ident__is_target_variant_os) {
2064 OS, Tok, II, *this, false,
2065 [this](Token &Tok, bool &HasLexedNextToken) -> int {
2067 Tok, *this, diag::err_feature_check_malformed);
2068 return II && isTargetVariantOS(getTargetInfo(), II);
2069 });
2070 } else if (II == Ident__is_target_variant_environment) {
2072 OS, Tok, II, *this, false,
2073 [this](Token &Tok, bool &HasLexedNextToken) -> int {
2075 Tok, *this, diag::err_feature_check_malformed);
2076 return II && isTargetVariantEnvironment(getTargetInfo(), II);
2077 });
2078 } else {
2079 llvm_unreachable("Unknown identifier!");
2080 }
2081 CreateString(OS.str(), Tok, Tok.getLocation(), Tok.getLocation());
2082 Tok.setFlagValue(Token::StartOfLine, IsAtStartOfLine);
2083 Tok.setFlagValue(Token::LeadingSpace, HasLeadingSpace);
2084}
2085
2087 // If the 'used' status changed, and the macro requires 'unused' warning,
2088 // remove its SourceLocation from the warn-for-unused-macro locations.
2089 if (MI->isWarnIfUnused() && !MI->isUsed())
2090 WarnUnusedMacroLocs.erase(MI->getDefinitionLoc());
2091 MI->setIsUsed(true);
2092}
2093
2095 const LangOptions &LangOpts,
2096 const TargetInfo &TI) {
2097 LangOpts.remapPathPrefix(Path);
2098 if (LangOpts.UseTargetPathSeparator) {
2099 if (TI.getTriple().isOSWindows())
2100 llvm::sys::path::remove_dots(Path, false,
2101 llvm::sys::path::Style::windows_backslash);
2102 else
2103 llvm::sys::path::remove_dots(Path, false, llvm::sys::path::Style::posix);
2104 }
2105}
2106
2108 const PresumedLoc &PLoc,
2109 const LangOptions &LangOpts,
2110 const TargetInfo &TI) {
2111 // Try to get the last path component, failing that return the original
2112 // presumed location.
2113 StringRef PLFileName = llvm::sys::path::filename(PLoc.getFilename());
2114 if (PLFileName.empty())
2115 PLFileName = PLoc.getFilename();
2116 FileName.append(PLFileName.begin(), PLFileName.end());
2117 processPathForFileMacro(FileName, LangOpts, TI);
2118}
Defines enum values for all the target-independent builtin functions.
IndirectLocalPath & Path
Expr * E
static bool getDiagnosticsInGroup(diag::Flavor Flavor, const WarningOption *Group, SmallVectorImpl< diag::kind > &Diags)
Return true if any diagnostics were found in this group, even if they were filtered out due to having...
Defines the clang::FileManager interface and associated types.
StringRef Filename
Definition: Format.cpp:2989
StringRef Identifier
Definition: Format.cpp:2997
const Environment & Env
Definition: HTMLLogger.cpp:148
llvm::DenseSet< const void * > Visited
Definition: HTMLLogger.cpp:146
Defines the clang::IdentifierInfo, clang::IdentifierTable, and clang::Selector interfaces.
Forward-declares and imports various common LLVM datatypes that clang wants to use unqualified.
Defines the clang::LangOptions interface.
static DiagnosticBuilder Diag(DiagnosticsEngine *Diags, const LangOptions &Features, FullSourceLoc TokLoc, const char *TokBegin, const char *TokRangeBegin, const char *TokRangeEnd, unsigned DiagID)
Produce a diagnostic highlighting some portion of a literal.
llvm::MachO::FileType FileType
Definition: MachO.h:46
Defines the clang::MacroInfo and clang::MacroDirective classes.
Defines types useful for describing an Objective-C runtime.
static bool HasExtension(const Preprocessor &PP, StringRef Extension)
HasExtension - Return true if we recognize and implement the feature specified by the identifier,...
static bool CheckMatchedBrackets(const SmallVectorImpl< Token > &Tokens)
CheckMatchedBrackets - Returns true if the braces and parentheses in the token vector are properly ne...
static bool EvaluateHasIncludeCommon(Token &Tok, IdentifierInfo *II, Preprocessor &PP, ConstSearchDirIterator LookupFrom, const FileEntry *LookupFromFile)
EvaluateHasIncludeCommon - Process a '__has_include("path")' or '__has_include_next("path")' expressi...
static IdentifierInfo * RegisterBuiltinMacro(Preprocessor &PP, const char *Name)
RegisterBuiltinMacro - Register the specified identifier in the identifier table and mark it as a bui...
static bool GenerateNewArgTokens(Preprocessor &PP, SmallVectorImpl< Token > &OldTokens, SmallVectorImpl< Token > &NewTokens, unsigned &NumArgs, SmallVectorImpl< SourceRange > &ParenHints, SmallVectorImpl< SourceRange > &InitLists)
GenerateNewArgTokens - Returns true if OldTokens can be converted to a new vector of tokens in NewTok...
static bool isTargetVariantOS(const TargetInfo &TI, const IdentifierInfo *II)
Implements the __is_target_variant_os builtin macro.
static bool isTrivialSingleTokenExpansion(const MacroInfo *MI, const IdentifierInfo *MacroIdent, Preprocessor &PP)
isTrivialSingleTokenExpansion - Return true if MI, which has a single token in its expansion,...
static bool isTargetArch(const TargetInfo &TI, const IdentifierInfo *II)
Implements the __is_target_arch builtin macro.
static void ComputeDATE_TIME(SourceLocation &DATELoc, SourceLocation &TIMELoc, Preprocessor &PP)
ComputeDATE_TIME - Compute the current time, enter it into the specified scratch buffer,...
static bool isTargetVariantEnvironment(const TargetInfo &TI, const IdentifierInfo *II)
Implements the __is_target_variant_environment builtin macro.
static bool isTargetEnvironment(const TargetInfo &TI, const IdentifierInfo *II)
Implements the __is_target_environment builtin macro.
static bool isTargetOS(const TargetInfo &TI, const IdentifierInfo *II)
Implements the __is_target_os builtin macro.
static bool isTargetVendor(const TargetInfo &TI, const IdentifierInfo *II)
Implements the __is_target_vendor builtin macro.
static void EvaluateFeatureLikeBuiltinMacro(llvm::raw_svector_ostream &OS, Token &Tok, IdentifierInfo *II, Preprocessor &PP, bool ExpandArgs, llvm::function_ref< int(Token &Tok, bool &HasLexedNextTok)> Op)
Process single-argument builtin feature-like macros that return integer values.
static bool HasFeature(const Preprocessor &PP, StringRef Feature)
HasFeature - Return true if we recognize and implement the feature specified by the identifier as a s...
static IdentifierInfo * ExpectFeatureIdentifierInfo(Token &Tok, Preprocessor &PP, signed DiagID)
Helper function to return the IdentifierInfo structure of a Token or generate a diagnostic if none av...
Defines the PreprocessorLexer interface.
Defines the clang::Preprocessor interface.
uint32_t Id
Definition: SemaARM.cpp:1143
SourceRange Range
Definition: SemaObjC.cpp:757
SourceLocation Loc
Definition: SemaObjC.cpp:758
Defines the clang::SourceLocation class and associated facilities.
__device__ int
Syntax
The style used to specify an attribute.
bool isConstantEvaluated(unsigned ID) const
Return true if this function can be constant evaluated by Clang frontend.
Definition: Builtins.h:279
SourceLocation getEnd() const
virtual void CodeCompleteMacroArgument(IdentifierInfo *Macro, MacroInfo *MacroInfo, unsigned ArgumentIndex)
Callback invoked when performing code completion inside a function-like macro argument.
A little helper class used to produce diagnostics.
Definition: Diagnostic.h:1271
diag::Severity getExtensionHandlingBehavior() const
Definition: Diagnostic.h:781
virtual void updateOutOfDateIdentifier(const IdentifierInfo &II)=0
Update an out-of-date identifier.
off_t getSize() const
Definition: FileEntry.h:340
Cached information about one file (either on disk or in the virtual file system).
Definition: FileEntry.h:300
time_t getModificationTime() const
Definition: FileEntry.h:328
static FixItHint CreateInsertion(SourceLocation InsertionLoc, StringRef Code, bool BeforePreviousInsertions=false)
Create a code modification hint that inserts the given code string at a specific location.
Definition: Diagnostic.h:97
SrcMgr::CharacteristicKind getFileDirFlavor(FileEntryRef File)
Return whether the specified file is a normal header, a system header, or a C++ friendly system heade...
Definition: HeaderSearch.h:551
One of these records is kept for each identifier that is lexed.
unsigned getBuiltinID() const
Return a value indicating whether this is a builtin function.
tok::TokenKind getTokenID() const
If this is a source-language token (e.g.
bool hadMacroDefinition() const
Returns true if this identifier was #defined to some value at any moment.
bool isFromAST() const
Return true if the identifier in its current state was loaded from an AST file.
bool hasRevertedTokenIDToIdentifier() const
True if revertTokenIDToIdentifier() was called.
const char * getNameStart() const
Return the beginning of the actual null-terminated string for this identifier.
void setHasMacroDefinition(bool Val)
bool isOutOfDate() const
Determine whether the information for this identifier is out of date with respect to the external sou...
void setChangedSinceDeserialization()
Note that this identifier has changed since it was loaded from an AST file.
StringRef getName() const
Return the actual identifier string.
Keeps track of the various options that can be enabled, which controls the dialect of C or C++ that i...
Definition: LangOptions.h:461
bool UseTargetPathSeparator
Indicates whether to use target's platform-specific file separator when FILE macro is used and when c...
Definition: LangOptions.h:567
void remapPathPrefix(SmallVectorImpl< char > &Path) const
Remap path prefix according to -fmacro-prefix-path option.
Definition: LangOptions.cpp:73
bool isCompilingModule() const
Are we compiling a module?
Definition: LangOptions.h:606
std::string CurrentModule
The name of the current module, of which the main source file is a part.
Definition: LangOptions.h:516
Lexer - This provides a simple interface that turns a text buffer into a stream of tokens.
Definition: Lexer.h:78
static std::string Stringify(StringRef Str, bool Charify=false)
Stringify - Convert the specified string into a C string by i) escaping '\' and " characters and ii) ...
Definition: Lexer.cpp:310
MacroArgs - An instance of this class captures information about the formal arguments specified to a ...
Definition: MacroArgs.h:30
static MacroArgs * create(const MacroInfo *MI, ArrayRef< Token > UnexpArgTokens, bool VarargsElided, Preprocessor &PP)
MacroArgs ctor function - Create a new MacroArgs object with the specified macro and argument info.
Definition: MacroArgs.cpp:24
void destroy(Preprocessor &PP)
destroy - Destroy and deallocate the memory for this object.
Definition: MacroArgs.cpp:78
A description of the current definition of a macro.
Definition: MacroInfo.h:590
MacroInfo * getMacroInfo() const
Get the MacroInfo that should be used for this definition.
Definition: MacroInfo.h:606
bool isAmbiguous() const
true if the definition is ambiguous, false otherwise.
Definition: MacroInfo.h:615
void forAllDefinitions(Fn F) const
Definition: MacroInfo.h:626
Encapsulates changes to the "macros namespace" (the location where the macro name became active,...
Definition: MacroInfo.h:313
const MacroDirective * getPrevious() const
Get previous definition of the macro with the same name.
Definition: MacroInfo.h:354
void setPrevious(MacroDirective *Prev)
Set previous definition of the macro with the same name.
Definition: MacroInfo.h:351
bool isDefined() const
Definition: MacroInfo.h:410
Encapsulates the data about a macro definition (e.g.
Definition: MacroInfo.h:39
bool isIdenticalTo(const MacroInfo &Other, Preprocessor &PP, bool Syntactically) const
Return true if the specified macro definition is equal to this macro in spelling, arguments,...
Definition: MacroInfo.cpp:94
bool isUsed() const
Return false if this macro is defined in the main file and has not yet been used.
Definition: MacroInfo.h:224
bool isFunctionLike() const
Definition: MacroInfo.h:201
ArrayRef< const IdentifierInfo * > params() const
Definition: MacroInfo.h:185
unsigned getNumTokens() const
Return the number of tokens that this macro expands to.
Definition: MacroInfo.h:235
void dump() const
Definition: MacroInfo.cpp:152
unsigned getNumParams() const
Definition: MacroInfo.h:184
const Token & getReplacementToken(unsigned Tok) const
Definition: MacroInfo.h:237
bool isBuiltinMacro() const
Return true if this macro requires processing before expansion.
Definition: MacroInfo.h:217
SourceLocation getDefinitionLoc() const
Return the location that the macro was defined at.
Definition: MacroInfo.h:125
bool isVariadic() const
Definition: MacroInfo.h:209
bool hasCommaPasting() const
Definition: MacroInfo.h:219
bool isObjectLike() const
Definition: MacroInfo.h:202
bool isWarnIfUnused() const
Return true if we should emit a warning if the macro is unused.
Definition: MacroInfo.h:232
bool isEnabled() const
Return true if this macro is enabled.
Definition: MacroInfo.h:281
void setIsUsed(bool Val)
Set the value of the IsUsed flag.
Definition: MacroInfo.h:154
void setIsBuiltinMacro(bool Val=true)
Set or clear the isBuiltinMacro flag.
Definition: MacroInfo.h:151
Represents a macro directive exported by a module.
Definition: MacroInfo.h:514
static ModuleMacro * create(Preprocessor &PP, Module *OwningModule, const IdentifierInfo *II, MacroInfo *Macro, ArrayRef< ModuleMacro * > Overrides)
Definition: MacroInfo.cpp:259
void Profile(llvm::FoldingSetNodeID &ID) const
Definition: MacroInfo.h:545
A header that is known to reside within a given module, whether it was included or excluded.
Definition: ModuleMap.h:159
Describes a module or submodule.
Definition: Module.h:105
void ExpandedMacro()
ExpandedMacro - When a macro is expanded with this lexer as the current buffer, this method is called...
This interface provides a way to observe the actions of the preprocessor as it does its thing.
Definition: PPCallbacks.h:36
MultipleIncludeOpt MIOpt
A state machine that detects the #ifndef-wrapping a file idiom for the multiple-include optimization.
OptionalFileEntryRef getFileEntry() const
getFileEntry - Return the FileEntry corresponding to this FileID.
std::optional< uint64_t > SourceDateEpoch
If set, the UNIX timestamp specified by SOURCE_DATE_EPOCH.
Engages in a tight little dance with the lexer to efficiently preprocess tokens.
Definition: Preprocessor.h:137
SourceLocation getLastFPEvalPragmaLocation() const
bool FinishLexStringLiteral(Token &Result, std::string &String, const char *DiagnosticTag, bool AllowMacroExpansion)
Complete the lexing of a string literal where the first token has already been lexed (see LexStringLi...
void dumpMacroInfo(const IdentifierInfo *II)
ModuleMacro * addModuleMacro(Module *Mod, IdentifierInfo *II, MacroInfo *Macro, ArrayRef< ModuleMacro * > Overrides, bool &IsNew)
Register an exported macro for a module and identifier.
void setLoadedMacroDirective(IdentifierInfo *II, MacroDirective *ED, MacroDirective *MD)
Set a MacroDirective that was loaded from a PCH file.
OptionalFileEntryRef LookupEmbedFile(StringRef Filename, bool isAngled, bool OpenFile, const FileEntry *LookupFromFile=nullptr)
Given a "Filename" or <Filename> reference, look up the indicated embed resource.
PPCallbacks * getPPCallbacks() const
const MacroInfo * getMacroInfo(const IdentifierInfo *II) const
void CreateString(StringRef Str, Token &Tok, SourceLocation ExpansionLocStart=SourceLocation(), SourceLocation ExpansionLocEnd=SourceLocation())
Plop the specified string into a scratch buffer and set the specified token's location and length to ...
void markMacroAsUsed(MacroInfo *MI)
A macro is used, update information about macros that need unused warnings.
MacroDirective * getLocalMacroDirectiveHistory(const IdentifierInfo *II) const
Given an identifier, return the latest non-imported macro directive for that identifier.
void Lex(Token &Result)
Lex the next token for this preprocessor.
bool isParsingIfOrElifDirective() const
True if we are currently preprocessing a if or #elif directive.
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.
SourceLocation AdvanceToTokenCharacter(SourceLocation TokStart, unsigned Char) const
Given a location that specifies the start of a token, return a new location that specifies a characte...
static void processPathToFileName(SmallVectorImpl< char > &FileName, const PresumedLoc &PLoc, const LangOptions &LangOpts, const TargetInfo &TI)
const TargetInfo & getTargetInfo() const
bool LexHeaderName(Token &Result, bool AllowMacroExpansion=true)
Lex a token, forming a header-name token if possible.
PreprocessorOptions & getPreprocessorOpts() const
Retrieve the preprocessor options used to initialize this preprocessor.
MacroInfo * AllocateMacroInfo(SourceLocation L)
Allocate a new MacroInfo object with the provided SourceLocation.
void LexUnexpandedToken(Token &Result)
Just like Lex, but disables macro expansion of identifier tokens.
ModuleMacro * getModuleMacro(Module *Mod, const IdentifierInfo *II)
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 ...
bool GetIncludeFilenameSpelling(SourceLocation Loc, StringRef &Buffer)
Turn the specified lexer token into a fully checked and spelled filename, e.g.
PreprocessorLexer * getCurrentFileLexer() const
Return the current file lexer being lexed from.
HeaderSearch & getHeaderSearchInfo() const
void emitMacroExpansionWarnings(const Token &Identifier, bool IsIfnDef=false) const
ExternalPreprocessorSource * getExternalSource() const
OptionalFileEntryRef LookupFile(SourceLocation FilenameLoc, StringRef Filename, bool isAngled, ConstSearchDirIterator FromDir, const FileEntry *FromFile, ConstSearchDirIterator *CurDir, SmallVectorImpl< char > *SearchPath, SmallVectorImpl< char > *RelativePath, ModuleMap::KnownHeader *SuggestedModule, bool *IsMapped, bool *IsFrameworkFound, bool SkipCache=false, bool OpenFile=true, bool CacheFailures=true)
Given a "foo" or <foo> reference, look up the indicated file.
Builtin::Context & getBuiltinInfo()
LangOptions::FPEvalMethodKind getTUFPEvalMethod() const
const LangOptions & getLangOpts() const
static void processPathForFileMacro(SmallVectorImpl< char > &Path, const LangOptions &LangOpts, const TargetInfo &TI)
DefMacroDirective * appendDefMacroDirective(IdentifierInfo *II, MacroInfo *MI, SourceLocation Loc)
DiagnosticsEngine & getDiagnostics() const
SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset=0)
Computes the source location just past the end of the token at this source location.
std::optional< LexEmbedParametersResult > LexEmbedParameters(Token &Current, bool ForHasEmbed)
Lex the parameters for an #embed directive, returns nullopt on error.
void EnterMacro(Token &Tok, SourceLocation ILEnd, MacroInfo *Macro, MacroArgs *Args)
Add a Macro to the top of the include stack and start lexing tokens from it instead of the current bu...
DiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID) const
Forwarding function for diagnostics.
void appendMacroDirective(IdentifierInfo *II, MacroDirective *MD)
Add a directive to the macro directive history for this identifier.
Represents an unpacked "presumed" location which can be presented to the user.
const char * getFilename() const
Return the presumed filename of this location.
bool isValid() const
unsigned getLine() const
Return the presumed line number of this location.
bool isInvalid() const
Return true if this object is invalid or uninitialized.
SourceLocation getIncludeLoc() const
Return the presumed include location of this location.
Encodes a location in the source.
bool isValid() const
Return true if this is a valid SourceLocation object.
PresumedLoc getPresumedLoc(SourceLocation Loc, bool UseLineDirectives=true) const
Returns the "presumed" location of a SourceLocation specifies.
CharSourceRange getExpansionRange(SourceLocation Loc) const
Given a SourceLocation object, return the range of tokens covered by the expansion in the ultimate fi...
bool isInSystemHeader(SourceLocation Loc) const
Returns if a SourceLocation is in a system header.
const FileEntry * getFileEntryForID(FileID FID) const
Returns the FileEntry record for the provided FileID.
SourceLocation createExpansionLoc(SourceLocation SpellingLoc, SourceLocation ExpansionLocStart, SourceLocation ExpansionLocEnd, unsigned Length, bool ExpansionIsTokenRange=true, int LoadedID=0, SourceLocation::UIntTy LoadedOffset=0)
Creates an expansion SLocEntry for a macro use.
A trivial tuple used to represent a source range.
StringLiteralParser - This decodes string escape characters and performs wide string analysis and Tra...
Exposes information about the current target.
Definition: TargetInfo.h:218
virtual bool supportsCpuSupports() const
Definition: TargetInfo.h:1513
virtual bool supportsCpuInit() const
Definition: TargetInfo.h:1515
const llvm::Triple & getTriple() const
Returns the target triple of the primary target.
Definition: TargetInfo.h:1256
const llvm::Triple * getDarwinTargetVariantTriple() const
Returns the darwin target variant triple, the variant of the deployment target for which the code is ...
Definition: TargetInfo.h:1816
virtual bool supportsCpuIs() const
Definition: TargetInfo.h:1514
TokenLexer - This implements a lexer that returns tokens from a macro body or token stream instead of...
Definition: TokenLexer.h:30
Token - This structure provides full information about a lexed token.
Definition: Token.h:36
IdentifierInfo * getIdentifierInfo() const
Definition: Token.h:187
unsigned getFlags() const
Return the internal represtation of the flags.
Definition: Token.h:262
void clearFlag(TokenFlags Flag)
Unset the specified flag.
Definition: Token.h:254
SourceLocation getLocation() const
Return a source location identifier for the specified offset in the current file.
Definition: Token.h:132
unsigned getLength() const
Definition: Token.h:135
void setLength(unsigned Len)
Definition: Token.h:141
void setKind(tok::TokenKind K)
Definition: Token.h:95
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:99
tok::TokenKind getKind() const
Definition: Token.h:94
bool isAtStartOfLine() const
isAtStartOfLine - Return true if this token is at the start of a line.
Definition: Token.h:276
@ DisableExpand
Definition: Token.h:79
@ IgnoredComma
Definition: Token.h:84
@ LeadingEmptyMacro
Definition: Token.h:81
@ LeadingSpace
Definition: Token.h:77
@ StartOfLine
Definition: Token.h:75
@ NeedsCleaning
Definition: Token.h:80
bool hasLeadingSpace() const
Return true if this token has whitespace before it.
Definition: Token.h:280
void setLocation(SourceLocation L)
Definition: Token.h:140
bool isOneOf(tok::TokenKind K1, tok::TokenKind K2) const
Definition: Token.h:101
bool isNot(tok::TokenKind K) const
Definition: Token.h:100
bool isAnnotation() const
Return true if this is any of tok::annot_* kind tokens.
Definition: Token.h:121
bool hasUDSuffix() const
Return true if this token is a string or character literal which has a ud-suffix.
Definition: Token.h:303
void startToken()
Reset all flags to cleared.
Definition: Token.h:177
void setIdentifierInfo(IdentifierInfo *II)
Definition: Token.h:196
void setFlagValue(TokenFlags Flag, bool Val)
Set a flag to either true or false.
Definition: Token.h:267
void setFlag(TokenFlags Flag)
Set the specified flag.
Definition: Token.h:244
Defines the clang::TargetInfo interface.
bool evaluateRequiredTargetFeatures(llvm::StringRef RequiredFatures, const llvm::StringMap< bool > &TargetFetureMap)
Returns true if the required target features of a builtin function are enabled.
CharacteristicKind
Indicates whether a file or directory holds normal user code, system code, or system code which is im...
Definition: SourceManager.h:81
uint32_t Literal
Literals are represented as positive integers.
Definition: CNFFormula.h:35
@ Error
Present this diagnostic as an error.
@ WarningOrError
A diagnostic that indicates a problem or potential problem.
The JSON file list parser is used to communicate input to InstallAPI.
@ CPlusPlus20
Definition: LangStandard.h:60
@ CPlusPlus
Definition: LangStandard.h:56
@ CPlusPlus11
Definition: LangStandard.h:57
@ Result
The result type of a method or function.
int hasAttribute(AttributeCommonInfo::Syntax Syntax, const IdentifierInfo *Scope, const IdentifierInfo *Attr, const TargetInfo &Target, const LangOptions &LangOpts)
Return the version number associated with the attribute if we recognize and implement the attribute s...
Definition: Attributes.cpp:31
@ Braces
New-expression has a C++11 list-initializer.