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