Path: blob/main/contrib/llvm-project/clang/lib/Lex/PPMacroExpansion.cpp
35233 views
//===--- PPMacroExpansion.cpp - Top level Macro Expansion -----------------===//1//2// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.3// See https://llvm.org/LICENSE.txt for license information.4// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception5//6//===----------------------------------------------------------------------===//7//8// This file implements the top level handling of macro expansion for the9// preprocessor.10//11//===----------------------------------------------------------------------===//1213#include "clang/Basic/AttributeCommonInfo.h"14#include "clang/Basic/Attributes.h"15#include "clang/Basic/Builtins.h"16#include "clang/Basic/FileManager.h"17#include "clang/Basic/IdentifierTable.h"18#include "clang/Basic/LLVM.h"19#include "clang/Basic/LangOptions.h"20#include "clang/Basic/ObjCRuntime.h"21#include "clang/Basic/SourceLocation.h"22#include "clang/Basic/TargetInfo.h"23#include "clang/Lex/CodeCompletionHandler.h"24#include "clang/Lex/DirectoryLookup.h"25#include "clang/Lex/ExternalPreprocessorSource.h"26#include "clang/Lex/HeaderSearch.h"27#include "clang/Lex/LexDiagnostic.h"28#include "clang/Lex/LiteralSupport.h"29#include "clang/Lex/MacroArgs.h"30#include "clang/Lex/MacroInfo.h"31#include "clang/Lex/Preprocessor.h"32#include "clang/Lex/PreprocessorLexer.h"33#include "clang/Lex/PreprocessorOptions.h"34#include "clang/Lex/Token.h"35#include "llvm/ADT/ArrayRef.h"36#include "llvm/ADT/DenseMap.h"37#include "llvm/ADT/DenseSet.h"38#include "llvm/ADT/FoldingSet.h"39#include "llvm/ADT/STLExtras.h"40#include "llvm/ADT/SmallString.h"41#include "llvm/ADT/SmallVector.h"42#include "llvm/ADT/StringRef.h"43#include "llvm/ADT/StringSwitch.h"44#include "llvm/Support/Casting.h"45#include "llvm/Support/ErrorHandling.h"46#include "llvm/Support/Format.h"47#include "llvm/Support/Path.h"48#include "llvm/Support/raw_ostream.h"49#include <algorithm>50#include <cassert>51#include <cstddef>52#include <cstring>53#include <ctime>54#include <optional>55#include <string>56#include <tuple>57#include <utility>5859using namespace clang;6061MacroDirective *62Preprocessor::getLocalMacroDirectiveHistory(const IdentifierInfo *II) const {63if (!II->hadMacroDefinition())64return nullptr;65auto Pos = CurSubmoduleState->Macros.find(II);66return Pos == CurSubmoduleState->Macros.end() ? nullptr67: Pos->second.getLatest();68}6970void Preprocessor::appendMacroDirective(IdentifierInfo *II, MacroDirective *MD){71assert(MD && "MacroDirective should be non-zero!");72assert(!MD->getPrevious() && "Already attached to a MacroDirective history.");7374MacroState &StoredMD = CurSubmoduleState->Macros[II];75auto *OldMD = StoredMD.getLatest();76MD->setPrevious(OldMD);77StoredMD.setLatest(MD);78StoredMD.overrideActiveModuleMacros(*this, II);7980if (needModuleMacros()) {81// Track that we created a new macro directive, so we know we should82// consider building a ModuleMacro for it when we get to the end of83// the module.84PendingModuleMacroNames.push_back(II);85}8687// Set up the identifier as having associated macro history.88II->setHasMacroDefinition(true);89if (!MD->isDefined() && !LeafModuleMacros.contains(II))90II->setHasMacroDefinition(false);91if (II->isFromAST())92II->setChangedSinceDeserialization();93}9495void Preprocessor::setLoadedMacroDirective(IdentifierInfo *II,96MacroDirective *ED,97MacroDirective *MD) {98// Normally, when a macro is defined, it goes through appendMacroDirective()99// above, which chains a macro to previous defines, undefs, etc.100// However, in a pch, the whole macro history up to the end of the pch is101// stored, so ASTReader goes through this function instead.102// However, built-in macros are already registered in the Preprocessor103// ctor, and ASTWriter stops writing the macro chain at built-in macros,104// so in that case the chain from the pch needs to be spliced to the existing105// built-in.106107assert(II && MD);108MacroState &StoredMD = CurSubmoduleState->Macros[II];109110if (auto *OldMD = StoredMD.getLatest()) {111// shouldIgnoreMacro() in ASTWriter also stops at macros from the112// predefines buffer in module builds. However, in module builds, modules113// are loaded completely before predefines are processed, so StoredMD114// will be nullptr for them when they're loaded. StoredMD should only be115// non-nullptr for builtins read from a pch file.116assert(OldMD->getMacroInfo()->isBuiltinMacro() &&117"only built-ins should have an entry here");118assert(!OldMD->getPrevious() && "builtin should only have a single entry");119ED->setPrevious(OldMD);120StoredMD.setLatest(MD);121} else {122StoredMD = MD;123}124125// Setup the identifier as having associated macro history.126II->setHasMacroDefinition(true);127if (!MD->isDefined() && !LeafModuleMacros.contains(II))128II->setHasMacroDefinition(false);129}130131ModuleMacro *Preprocessor::addModuleMacro(Module *Mod, IdentifierInfo *II,132MacroInfo *Macro,133ArrayRef<ModuleMacro *> Overrides,134bool &New) {135llvm::FoldingSetNodeID ID;136ModuleMacro::Profile(ID, Mod, II);137138void *InsertPos;139if (auto *MM = ModuleMacros.FindNodeOrInsertPos(ID, InsertPos)) {140New = false;141return MM;142}143144auto *MM = ModuleMacro::create(*this, Mod, II, Macro, Overrides);145ModuleMacros.InsertNode(MM, InsertPos);146147// Each overridden macro is now overridden by one more macro.148bool HidAny = false;149for (auto *O : Overrides) {150HidAny |= (O->NumOverriddenBy == 0);151++O->NumOverriddenBy;152}153154// If we were the first overrider for any macro, it's no longer a leaf.155auto &LeafMacros = LeafModuleMacros[II];156if (HidAny) {157llvm::erase_if(LeafMacros,158[](ModuleMacro *MM) { return MM->NumOverriddenBy != 0; });159}160161// The new macro is always a leaf macro.162LeafMacros.push_back(MM);163// The identifier now has defined macros (that may or may not be visible).164II->setHasMacroDefinition(true);165166New = true;167return MM;168}169170ModuleMacro *Preprocessor::getModuleMacro(Module *Mod,171const IdentifierInfo *II) {172llvm::FoldingSetNodeID ID;173ModuleMacro::Profile(ID, Mod, II);174175void *InsertPos;176return ModuleMacros.FindNodeOrInsertPos(ID, InsertPos);177}178179void Preprocessor::updateModuleMacroInfo(const IdentifierInfo *II,180ModuleMacroInfo &Info) {181assert(Info.ActiveModuleMacrosGeneration !=182CurSubmoduleState->VisibleModules.getGeneration() &&183"don't need to update this macro name info");184Info.ActiveModuleMacrosGeneration =185CurSubmoduleState->VisibleModules.getGeneration();186187auto Leaf = LeafModuleMacros.find(II);188if (Leaf == LeafModuleMacros.end()) {189// No imported macros at all: nothing to do.190return;191}192193Info.ActiveModuleMacros.clear();194195// Every macro that's locally overridden is overridden by a visible macro.196llvm::DenseMap<ModuleMacro *, int> NumHiddenOverrides;197for (auto *O : Info.OverriddenMacros)198NumHiddenOverrides[O] = -1;199200// Collect all macros that are not overridden by a visible macro.201llvm::SmallVector<ModuleMacro *, 16> Worklist;202for (auto *LeafMM : Leaf->second) {203assert(LeafMM->getNumOverridingMacros() == 0 && "leaf macro overridden");204if (NumHiddenOverrides.lookup(LeafMM) == 0)205Worklist.push_back(LeafMM);206}207while (!Worklist.empty()) {208auto *MM = Worklist.pop_back_val();209if (CurSubmoduleState->VisibleModules.isVisible(MM->getOwningModule())) {210// We only care about collecting definitions; undefinitions only act211// to override other definitions.212if (MM->getMacroInfo())213Info.ActiveModuleMacros.push_back(MM);214} else {215for (auto *O : MM->overrides())216if ((unsigned)++NumHiddenOverrides[O] == O->getNumOverridingMacros())217Worklist.push_back(O);218}219}220// Our reverse postorder walk found the macros in reverse order.221std::reverse(Info.ActiveModuleMacros.begin(), Info.ActiveModuleMacros.end());222223// Determine whether the macro name is ambiguous.224MacroInfo *MI = nullptr;225bool IsSystemMacro = true;226bool IsAmbiguous = false;227if (auto *MD = Info.MD) {228while (isa_and_nonnull<VisibilityMacroDirective>(MD))229MD = MD->getPrevious();230if (auto *DMD = dyn_cast_or_null<DefMacroDirective>(MD)) {231MI = DMD->getInfo();232IsSystemMacro &= SourceMgr.isInSystemHeader(DMD->getLocation());233}234}235for (auto *Active : Info.ActiveModuleMacros) {236auto *NewMI = Active->getMacroInfo();237238// Before marking the macro as ambiguous, check if this is a case where239// both macros are in system headers. If so, we trust that the system240// did not get it wrong. This also handles cases where Clang's own241// headers have a different spelling of certain system macros:242// #define LONG_MAX __LONG_MAX__ (clang's limits.h)243// #define LONG_MAX 0x7fffffffffffffffL (system's limits.h)244//245// FIXME: Remove the defined-in-system-headers check. clang's limits.h246// overrides the system limits.h's macros, so there's no conflict here.247if (MI && NewMI != MI &&248!MI->isIdenticalTo(*NewMI, *this, /*Syntactically=*/true))249IsAmbiguous = true;250IsSystemMacro &= Active->getOwningModule()->IsSystem ||251SourceMgr.isInSystemHeader(NewMI->getDefinitionLoc());252MI = NewMI;253}254Info.IsAmbiguous = IsAmbiguous && !IsSystemMacro;255}256257void Preprocessor::dumpMacroInfo(const IdentifierInfo *II) {258ArrayRef<ModuleMacro*> Leaf;259auto LeafIt = LeafModuleMacros.find(II);260if (LeafIt != LeafModuleMacros.end())261Leaf = LeafIt->second;262const MacroState *State = nullptr;263auto Pos = CurSubmoduleState->Macros.find(II);264if (Pos != CurSubmoduleState->Macros.end())265State = &Pos->second;266267llvm::errs() << "MacroState " << State << " " << II->getNameStart();268if (State && State->isAmbiguous(*this, II))269llvm::errs() << " ambiguous";270if (State && !State->getOverriddenMacros().empty()) {271llvm::errs() << " overrides";272for (auto *O : State->getOverriddenMacros())273llvm::errs() << " " << O->getOwningModule()->getFullModuleName();274}275llvm::errs() << "\n";276277// Dump local macro directives.278for (auto *MD = State ? State->getLatest() : nullptr; MD;279MD = MD->getPrevious()) {280llvm::errs() << " ";281MD->dump();282}283284// Dump module macros.285llvm::DenseSet<ModuleMacro*> Active;286for (auto *MM :287State ? State->getActiveModuleMacros(*this, II) : std::nullopt)288Active.insert(MM);289llvm::DenseSet<ModuleMacro*> Visited;290llvm::SmallVector<ModuleMacro *, 16> Worklist(Leaf.begin(), Leaf.end());291while (!Worklist.empty()) {292auto *MM = Worklist.pop_back_val();293llvm::errs() << " ModuleMacro " << MM << " "294<< MM->getOwningModule()->getFullModuleName();295if (!MM->getMacroInfo())296llvm::errs() << " undef";297298if (Active.count(MM))299llvm::errs() << " active";300else if (!CurSubmoduleState->VisibleModules.isVisible(301MM->getOwningModule()))302llvm::errs() << " hidden";303else if (MM->getMacroInfo())304llvm::errs() << " overridden";305306if (!MM->overrides().empty()) {307llvm::errs() << " overrides";308for (auto *O : MM->overrides()) {309llvm::errs() << " " << O->getOwningModule()->getFullModuleName();310if (Visited.insert(O).second)311Worklist.push_back(O);312}313}314llvm::errs() << "\n";315if (auto *MI = MM->getMacroInfo()) {316llvm::errs() << " ";317MI->dump();318llvm::errs() << "\n";319}320}321}322323/// RegisterBuiltinMacro - Register the specified identifier in the identifier324/// table and mark it as a builtin macro to be expanded.325static IdentifierInfo *RegisterBuiltinMacro(Preprocessor &PP, const char *Name){326// Get the identifier.327IdentifierInfo *Id = PP.getIdentifierInfo(Name);328329// Mark it as being a macro that is builtin.330MacroInfo *MI = PP.AllocateMacroInfo(SourceLocation());331MI->setIsBuiltinMacro();332PP.appendDefMacroDirective(Id, MI);333return Id;334}335336/// RegisterBuiltinMacros - Register builtin macros, such as __LINE__ with the337/// identifier table.338void Preprocessor::RegisterBuiltinMacros() {339Ident__LINE__ = RegisterBuiltinMacro(*this, "__LINE__");340Ident__FILE__ = RegisterBuiltinMacro(*this, "__FILE__");341Ident__DATE__ = RegisterBuiltinMacro(*this, "__DATE__");342Ident__TIME__ = RegisterBuiltinMacro(*this, "__TIME__");343Ident__COUNTER__ = RegisterBuiltinMacro(*this, "__COUNTER__");344Ident_Pragma = RegisterBuiltinMacro(*this, "_Pragma");345Ident__FLT_EVAL_METHOD__ = RegisterBuiltinMacro(*this, "__FLT_EVAL_METHOD__");346347// C++ Standing Document Extensions.348if (getLangOpts().CPlusPlus)349Ident__has_cpp_attribute =350RegisterBuiltinMacro(*this, "__has_cpp_attribute");351else352Ident__has_cpp_attribute = nullptr;353354// GCC Extensions.355Ident__BASE_FILE__ = RegisterBuiltinMacro(*this, "__BASE_FILE__");356Ident__INCLUDE_LEVEL__ = RegisterBuiltinMacro(*this, "__INCLUDE_LEVEL__");357Ident__TIMESTAMP__ = RegisterBuiltinMacro(*this, "__TIMESTAMP__");358359// Microsoft Extensions.360if (getLangOpts().MicrosoftExt) {361Ident__identifier = RegisterBuiltinMacro(*this, "__identifier");362Ident__pragma = RegisterBuiltinMacro(*this, "__pragma");363} else {364Ident__identifier = nullptr;365Ident__pragma = nullptr;366}367368// Clang Extensions.369Ident__FILE_NAME__ = RegisterBuiltinMacro(*this, "__FILE_NAME__");370Ident__has_feature = RegisterBuiltinMacro(*this, "__has_feature");371Ident__has_extension = RegisterBuiltinMacro(*this, "__has_extension");372Ident__has_builtin = RegisterBuiltinMacro(*this, "__has_builtin");373Ident__has_constexpr_builtin =374RegisterBuiltinMacro(*this, "__has_constexpr_builtin");375Ident__has_attribute = RegisterBuiltinMacro(*this, "__has_attribute");376if (!getLangOpts().CPlusPlus)377Ident__has_c_attribute = RegisterBuiltinMacro(*this, "__has_c_attribute");378else379Ident__has_c_attribute = nullptr;380381Ident__has_declspec = RegisterBuiltinMacro(*this, "__has_declspec_attribute");382Ident__has_embed = RegisterBuiltinMacro(*this, "__has_embed");383Ident__has_include = RegisterBuiltinMacro(*this, "__has_include");384Ident__has_include_next = RegisterBuiltinMacro(*this, "__has_include_next");385Ident__has_warning = RegisterBuiltinMacro(*this, "__has_warning");386Ident__is_identifier = RegisterBuiltinMacro(*this, "__is_identifier");387Ident__is_target_arch = RegisterBuiltinMacro(*this, "__is_target_arch");388Ident__is_target_vendor = RegisterBuiltinMacro(*this, "__is_target_vendor");389Ident__is_target_os = RegisterBuiltinMacro(*this, "__is_target_os");390Ident__is_target_environment =391RegisterBuiltinMacro(*this, "__is_target_environment");392Ident__is_target_variant_os =393RegisterBuiltinMacro(*this, "__is_target_variant_os");394Ident__is_target_variant_environment =395RegisterBuiltinMacro(*this, "__is_target_variant_environment");396397// Modules.398Ident__building_module = RegisterBuiltinMacro(*this, "__building_module");399if (!getLangOpts().CurrentModule.empty())400Ident__MODULE__ = RegisterBuiltinMacro(*this, "__MODULE__");401else402Ident__MODULE__ = nullptr;403}404405/// isTrivialSingleTokenExpansion - Return true if MI, which has a single token406/// in its expansion, currently expands to that token literally.407static bool isTrivialSingleTokenExpansion(const MacroInfo *MI,408const IdentifierInfo *MacroIdent,409Preprocessor &PP) {410IdentifierInfo *II = MI->getReplacementToken(0).getIdentifierInfo();411412// If the token isn't an identifier, it's always literally expanded.413if (!II) return true;414415// If the information about this identifier is out of date, update it from416// the external source.417if (II->isOutOfDate())418PP.getExternalSource()->updateOutOfDateIdentifier(*II);419420// If the identifier is a macro, and if that macro is enabled, it may be421// expanded so it's not a trivial expansion.422if (auto *ExpansionMI = PP.getMacroInfo(II))423if (ExpansionMI->isEnabled() &&424// Fast expanding "#define X X" is ok, because X would be disabled.425II != MacroIdent)426return false;427428// If this is an object-like macro invocation, it is safe to trivially expand429// it.430if (MI->isObjectLike()) return true;431432// If this is a function-like macro invocation, it's safe to trivially expand433// as long as the identifier is not a macro argument.434return !llvm::is_contained(MI->params(), II);435}436437/// isNextPPTokenLParen - Determine whether the next preprocessor token to be438/// lexed is a '('. If so, consume the token and return true, if not, this439/// method should have no observable side-effect on the lexed tokens.440bool Preprocessor::isNextPPTokenLParen() {441// Do some quick tests for rejection cases.442unsigned Val;443if (CurLexer)444Val = CurLexer->isNextPPTokenLParen();445else446Val = CurTokenLexer->isNextTokenLParen();447448if (Val == 2) {449// We have run off the end. If it's a source file we don't450// examine enclosing ones (C99 5.1.1.2p4). Otherwise walk up the451// macro stack.452if (CurPPLexer)453return false;454for (const IncludeStackInfo &Entry : llvm::reverse(IncludeMacroStack)) {455if (Entry.TheLexer)456Val = Entry.TheLexer->isNextPPTokenLParen();457else458Val = Entry.TheTokenLexer->isNextTokenLParen();459460if (Val != 2)461break;462463// Ran off the end of a source file?464if (Entry.ThePPLexer)465return false;466}467}468469// Okay, if we know that the token is a '(', lex it and return. Otherwise we470// have found something that isn't a '(' or we found the end of the471// translation unit. In either case, return false.472return Val == 1;473}474475/// HandleMacroExpandedIdentifier - If an identifier token is read that is to be476/// expanded as a macro, handle it and return the next token as 'Identifier'.477bool Preprocessor::HandleMacroExpandedIdentifier(Token &Identifier,478const MacroDefinition &M) {479emitMacroExpansionWarnings(Identifier);480481MacroInfo *MI = M.getMacroInfo();482483// If this is a macro expansion in the "#if !defined(x)" line for the file,484// then the macro could expand to different things in other contexts, we need485// to disable the optimization in this case.486if (CurPPLexer) CurPPLexer->MIOpt.ExpandedMacro();487488// If this is a builtin macro, like __LINE__ or _Pragma, handle it specially.489if (MI->isBuiltinMacro()) {490if (Callbacks)491Callbacks->MacroExpands(Identifier, M, Identifier.getLocation(),492/*Args=*/nullptr);493ExpandBuiltinMacro(Identifier);494return true;495}496497/// Args - If this is a function-like macro expansion, this contains,498/// for each macro argument, the list of tokens that were provided to the499/// invocation.500MacroArgs *Args = nullptr;501502// Remember where the end of the expansion occurred. For an object-like503// macro, this is the identifier. For a function-like macro, this is the ')'.504SourceLocation ExpansionEnd = Identifier.getLocation();505506// If this is a function-like macro, read the arguments.507if (MI->isFunctionLike()) {508// Remember that we are now parsing the arguments to a macro invocation.509// Preprocessor directives used inside macro arguments are not portable, and510// this enables the warning.511InMacroArgs = true;512ArgMacro = &Identifier;513514Args = ReadMacroCallArgumentList(Identifier, MI, ExpansionEnd);515516// Finished parsing args.517InMacroArgs = false;518ArgMacro = nullptr;519520// If there was an error parsing the arguments, bail out.521if (!Args) return true;522523++NumFnMacroExpanded;524} else {525++NumMacroExpanded;526}527528// Notice that this macro has been used.529markMacroAsUsed(MI);530531// Remember where the token is expanded.532SourceLocation ExpandLoc = Identifier.getLocation();533SourceRange ExpansionRange(ExpandLoc, ExpansionEnd);534535if (Callbacks) {536if (InMacroArgs) {537// We can have macro expansion inside a conditional directive while538// reading the function macro arguments. To ensure, in that case, that539// MacroExpands callbacks still happen in source order, queue this540// callback to have it happen after the function macro callback.541DelayedMacroExpandsCallbacks.push_back(542MacroExpandsInfo(Identifier, M, ExpansionRange));543} else {544Callbacks->MacroExpands(Identifier, M, ExpansionRange, Args);545if (!DelayedMacroExpandsCallbacks.empty()) {546for (const MacroExpandsInfo &Info : DelayedMacroExpandsCallbacks) {547// FIXME: We lose macro args info with delayed callback.548Callbacks->MacroExpands(Info.Tok, Info.MD, Info.Range,549/*Args=*/nullptr);550}551DelayedMacroExpandsCallbacks.clear();552}553}554}555556// If the macro definition is ambiguous, complain.557if (M.isAmbiguous()) {558Diag(Identifier, diag::warn_pp_ambiguous_macro)559<< Identifier.getIdentifierInfo();560Diag(MI->getDefinitionLoc(), diag::note_pp_ambiguous_macro_chosen)561<< Identifier.getIdentifierInfo();562M.forAllDefinitions([&](const MacroInfo *OtherMI) {563if (OtherMI != MI)564Diag(OtherMI->getDefinitionLoc(), diag::note_pp_ambiguous_macro_other)565<< Identifier.getIdentifierInfo();566});567}568569// If we started lexing a macro, enter the macro expansion body.570571// If this macro expands to no tokens, don't bother to push it onto the572// expansion stack, only to take it right back off.573if (MI->getNumTokens() == 0) {574// No need for arg info.575if (Args) Args->destroy(*this);576577// Propagate whitespace info as if we had pushed, then popped,578// a macro context.579Identifier.setFlag(Token::LeadingEmptyMacro);580PropagateLineStartLeadingSpaceInfo(Identifier);581++NumFastMacroExpanded;582return false;583} else if (MI->getNumTokens() == 1 &&584isTrivialSingleTokenExpansion(MI, Identifier.getIdentifierInfo(),585*this)) {586// Otherwise, if this macro expands into a single trivially-expanded587// token: expand it now. This handles common cases like588// "#define VAL 42".589590// No need for arg info.591if (Args) Args->destroy(*this);592593// Propagate the isAtStartOfLine/hasLeadingSpace markers of the macro594// identifier to the expanded token.595bool isAtStartOfLine = Identifier.isAtStartOfLine();596bool hasLeadingSpace = Identifier.hasLeadingSpace();597598// Replace the result token.599Identifier = MI->getReplacementToken(0);600601// Restore the StartOfLine/LeadingSpace markers.602Identifier.setFlagValue(Token::StartOfLine , isAtStartOfLine);603Identifier.setFlagValue(Token::LeadingSpace, hasLeadingSpace);604605// Update the tokens location to include both its expansion and physical606// locations.607SourceLocation Loc =608SourceMgr.createExpansionLoc(Identifier.getLocation(), ExpandLoc,609ExpansionEnd,Identifier.getLength());610Identifier.setLocation(Loc);611612// If this is a disabled macro or #define X X, we must mark the result as613// unexpandable.614if (IdentifierInfo *NewII = Identifier.getIdentifierInfo()) {615if (MacroInfo *NewMI = getMacroInfo(NewII))616if (!NewMI->isEnabled() || NewMI == MI) {617Identifier.setFlag(Token::DisableExpand);618// Don't warn for "#define X X" like "#define bool bool" from619// stdbool.h.620if (NewMI != MI || MI->isFunctionLike())621Diag(Identifier, diag::pp_disabled_macro_expansion);622}623}624625// Since this is not an identifier token, it can't be macro expanded, so626// we're done.627++NumFastMacroExpanded;628return true;629}630631// Start expanding the macro.632EnterMacro(Identifier, ExpansionEnd, MI, Args);633return false;634}635636enum Bracket {637Brace,638Paren639};640641/// CheckMatchedBrackets - Returns true if the braces and parentheses in the642/// token vector are properly nested.643static bool CheckMatchedBrackets(const SmallVectorImpl<Token> &Tokens) {644SmallVector<Bracket, 8> Brackets;645for (SmallVectorImpl<Token>::const_iterator I = Tokens.begin(),646E = Tokens.end();647I != E; ++I) {648if (I->is(tok::l_paren)) {649Brackets.push_back(Paren);650} else if (I->is(tok::r_paren)) {651if (Brackets.empty() || Brackets.back() == Brace)652return false;653Brackets.pop_back();654} else if (I->is(tok::l_brace)) {655Brackets.push_back(Brace);656} else if (I->is(tok::r_brace)) {657if (Brackets.empty() || Brackets.back() == Paren)658return false;659Brackets.pop_back();660}661}662return Brackets.empty();663}664665/// GenerateNewArgTokens - Returns true if OldTokens can be converted to a new666/// vector of tokens in NewTokens. The new number of arguments will be placed667/// in NumArgs and the ranges which need to surrounded in parentheses will be668/// in ParenHints.669/// Returns false if the token stream cannot be changed. If this is because670/// of an initializer list starting a macro argument, the range of those671/// initializer lists will be place in InitLists.672static bool GenerateNewArgTokens(Preprocessor &PP,673SmallVectorImpl<Token> &OldTokens,674SmallVectorImpl<Token> &NewTokens,675unsigned &NumArgs,676SmallVectorImpl<SourceRange> &ParenHints,677SmallVectorImpl<SourceRange> &InitLists) {678if (!CheckMatchedBrackets(OldTokens))679return false;680681// Once it is known that the brackets are matched, only a simple count of the682// braces is needed.683unsigned Braces = 0;684685// First token of a new macro argument.686SmallVectorImpl<Token>::iterator ArgStartIterator = OldTokens.begin();687688// First closing brace in a new macro argument. Used to generate689// SourceRanges for InitLists.690SmallVectorImpl<Token>::iterator ClosingBrace = OldTokens.end();691NumArgs = 0;692Token TempToken;693// Set to true when a macro separator token is found inside a braced list.694// If true, the fixed argument spans multiple old arguments and ParenHints695// will be updated.696bool FoundSeparatorToken = false;697for (SmallVectorImpl<Token>::iterator I = OldTokens.begin(),698E = OldTokens.end();699I != E; ++I) {700if (I->is(tok::l_brace)) {701++Braces;702} else if (I->is(tok::r_brace)) {703--Braces;704if (Braces == 0 && ClosingBrace == E && FoundSeparatorToken)705ClosingBrace = I;706} else if (I->is(tok::eof)) {707// EOF token is used to separate macro arguments708if (Braces != 0) {709// Assume comma separator is actually braced list separator and change710// it back to a comma.711FoundSeparatorToken = true;712I->setKind(tok::comma);713I->setLength(1);714} else { // Braces == 0715// Separator token still separates arguments.716++NumArgs;717718// If the argument starts with a brace, it can't be fixed with719// parentheses. A different diagnostic will be given.720if (FoundSeparatorToken && ArgStartIterator->is(tok::l_brace)) {721InitLists.push_back(722SourceRange(ArgStartIterator->getLocation(),723PP.getLocForEndOfToken(ClosingBrace->getLocation())));724ClosingBrace = E;725}726727// Add left paren728if (FoundSeparatorToken) {729TempToken.startToken();730TempToken.setKind(tok::l_paren);731TempToken.setLocation(ArgStartIterator->getLocation());732TempToken.setLength(0);733NewTokens.push_back(TempToken);734}735736// Copy over argument tokens737NewTokens.insert(NewTokens.end(), ArgStartIterator, I);738739// Add right paren and store the paren locations in ParenHints740if (FoundSeparatorToken) {741SourceLocation Loc = PP.getLocForEndOfToken((I - 1)->getLocation());742TempToken.startToken();743TempToken.setKind(tok::r_paren);744TempToken.setLocation(Loc);745TempToken.setLength(0);746NewTokens.push_back(TempToken);747ParenHints.push_back(SourceRange(ArgStartIterator->getLocation(),748Loc));749}750751// Copy separator token752NewTokens.push_back(*I);753754// Reset values755ArgStartIterator = I + 1;756FoundSeparatorToken = false;757}758}759}760761return !ParenHints.empty() && InitLists.empty();762}763764/// ReadFunctionLikeMacroArgs - After reading "MACRO" and knowing that the next765/// token is the '(' of the macro, this method is invoked to read all of the766/// actual arguments specified for the macro invocation. This returns null on767/// error.768MacroArgs *Preprocessor::ReadMacroCallArgumentList(Token &MacroName,769MacroInfo *MI,770SourceLocation &MacroEnd) {771// The number of fixed arguments to parse.772unsigned NumFixedArgsLeft = MI->getNumParams();773bool isVariadic = MI->isVariadic();774775// Outer loop, while there are more arguments, keep reading them.776Token Tok;777778// Read arguments as unexpanded tokens. This avoids issues, e.g., where779// an argument value in a macro could expand to ',' or '(' or ')'.780LexUnexpandedToken(Tok);781assert(Tok.is(tok::l_paren) && "Error computing l-paren-ness?");782783// ArgTokens - Build up a list of tokens that make up each argument. Each784// argument is separated by an EOF token. Use a SmallVector so we can avoid785// heap allocations in the common case.786SmallVector<Token, 64> ArgTokens;787bool ContainsCodeCompletionTok = false;788bool FoundElidedComma = false;789790SourceLocation TooManyArgsLoc;791792unsigned NumActuals = 0;793while (Tok.isNot(tok::r_paren)) {794if (ContainsCodeCompletionTok && Tok.isOneOf(tok::eof, tok::eod))795break;796797assert(Tok.isOneOf(tok::l_paren, tok::comma) &&798"only expect argument separators here");799800size_t ArgTokenStart = ArgTokens.size();801SourceLocation ArgStartLoc = Tok.getLocation();802803// C99 6.10.3p11: Keep track of the number of l_parens we have seen. Note804// that we already consumed the first one.805unsigned NumParens = 0;806807while (true) {808// Read arguments as unexpanded tokens. This avoids issues, e.g., where809// an argument value in a macro could expand to ',' or '(' or ')'.810LexUnexpandedToken(Tok);811812if (Tok.isOneOf(tok::eof, tok::eod)) { // "#if f(<eof>" & "#if f(\n"813if (!ContainsCodeCompletionTok) {814Diag(MacroName, diag::err_unterm_macro_invoc);815Diag(MI->getDefinitionLoc(), diag::note_macro_here)816<< MacroName.getIdentifierInfo();817// Do not lose the EOF/EOD. Return it to the client.818MacroName = Tok;819return nullptr;820}821// Do not lose the EOF/EOD.822auto Toks = std::make_unique<Token[]>(1);823Toks[0] = Tok;824EnterTokenStream(std::move(Toks), 1, true, /*IsReinject*/ false);825break;826} else if (Tok.is(tok::r_paren)) {827// If we found the ) token, the macro arg list is done.828if (NumParens-- == 0) {829MacroEnd = Tok.getLocation();830if (!ArgTokens.empty() &&831ArgTokens.back().commaAfterElided()) {832FoundElidedComma = true;833}834break;835}836} else if (Tok.is(tok::l_paren)) {837++NumParens;838} else if (Tok.is(tok::comma)) {839// In Microsoft-compatibility mode, single commas from nested macro840// expansions should not be considered as argument separators. We test841// for this with the IgnoredComma token flag.842if (Tok.getFlags() & Token::IgnoredComma) {843// However, in MSVC's preprocessor, subsequent expansions do treat844// these commas as argument separators. This leads to a common845// workaround used in macros that need to work in both MSVC and846// compliant preprocessors. Therefore, the IgnoredComma flag can only847// apply once to any given token.848Tok.clearFlag(Token::IgnoredComma);849} else if (NumParens == 0) {850// Comma ends this argument if there are more fixed arguments851// expected. However, if this is a variadic macro, and this is part of852// the variadic part, then the comma is just an argument token.853if (!isVariadic)854break;855if (NumFixedArgsLeft > 1)856break;857}858} else if (Tok.is(tok::comment) && !KeepMacroComments) {859// If this is a comment token in the argument list and we're just in860// -C mode (not -CC mode), discard the comment.861continue;862} else if (!Tok.isAnnotation() && Tok.getIdentifierInfo() != nullptr) {863// Reading macro arguments can cause macros that we are currently864// expanding from to be popped off the expansion stack. Doing so causes865// them to be reenabled for expansion. Here we record whether any866// identifiers we lex as macro arguments correspond to disabled macros.867// If so, we mark the token as noexpand. This is a subtle aspect of868// C99 6.10.3.4p2.869if (MacroInfo *MI = getMacroInfo(Tok.getIdentifierInfo()))870if (!MI->isEnabled())871Tok.setFlag(Token::DisableExpand);872} else if (Tok.is(tok::code_completion)) {873ContainsCodeCompletionTok = true;874if (CodeComplete)875CodeComplete->CodeCompleteMacroArgument(MacroName.getIdentifierInfo(),876MI, NumActuals);877// Don't mark that we reached the code-completion point because the878// parser is going to handle the token and there will be another879// code-completion callback.880}881882ArgTokens.push_back(Tok);883}884885// If this was an empty argument list foo(), don't add this as an empty886// argument.887if (ArgTokens.empty() && Tok.getKind() == tok::r_paren)888break;889890// If this is not a variadic macro, and too many args were specified, emit891// an error.892if (!isVariadic && NumFixedArgsLeft == 0 && TooManyArgsLoc.isInvalid()) {893if (ArgTokens.size() != ArgTokenStart)894TooManyArgsLoc = ArgTokens[ArgTokenStart].getLocation();895else896TooManyArgsLoc = ArgStartLoc;897}898899// Empty arguments are standard in C99 and C++0x, and are supported as an900// extension in other modes.901if (ArgTokens.size() == ArgTokenStart && !getLangOpts().C99)902Diag(Tok, getLangOpts().CPlusPlus11903? diag::warn_cxx98_compat_empty_fnmacro_arg904: diag::ext_empty_fnmacro_arg);905906// Add a marker EOF token to the end of the token list for this argument.907Token EOFTok;908EOFTok.startToken();909EOFTok.setKind(tok::eof);910EOFTok.setLocation(Tok.getLocation());911EOFTok.setLength(0);912ArgTokens.push_back(EOFTok);913++NumActuals;914if (!ContainsCodeCompletionTok && NumFixedArgsLeft != 0)915--NumFixedArgsLeft;916}917918// Okay, we either found the r_paren. Check to see if we parsed too few919// arguments.920unsigned MinArgsExpected = MI->getNumParams();921922// If this is not a variadic macro, and too many args were specified, emit923// an error.924if (!isVariadic && NumActuals > MinArgsExpected &&925!ContainsCodeCompletionTok) {926// Emit the diagnostic at the macro name in case there is a missing ).927// Emitting it at the , could be far away from the macro name.928Diag(TooManyArgsLoc, diag::err_too_many_args_in_macro_invoc);929Diag(MI->getDefinitionLoc(), diag::note_macro_here)930<< MacroName.getIdentifierInfo();931932// Commas from braced initializer lists will be treated as argument933// separators inside macros. Attempt to correct for this with parentheses.934// TODO: See if this can be generalized to angle brackets for templates935// inside macro arguments.936937SmallVector<Token, 4> FixedArgTokens;938unsigned FixedNumArgs = 0;939SmallVector<SourceRange, 4> ParenHints, InitLists;940if (!GenerateNewArgTokens(*this, ArgTokens, FixedArgTokens, FixedNumArgs,941ParenHints, InitLists)) {942if (!InitLists.empty()) {943DiagnosticBuilder DB =944Diag(MacroName,945diag::note_init_list_at_beginning_of_macro_argument);946for (SourceRange Range : InitLists)947DB << Range;948}949return nullptr;950}951if (FixedNumArgs != MinArgsExpected)952return nullptr;953954DiagnosticBuilder DB = Diag(MacroName, diag::note_suggest_parens_for_macro);955for (SourceRange ParenLocation : ParenHints) {956DB << FixItHint::CreateInsertion(ParenLocation.getBegin(), "(");957DB << FixItHint::CreateInsertion(ParenLocation.getEnd(), ")");958}959ArgTokens.swap(FixedArgTokens);960NumActuals = FixedNumArgs;961}962963// See MacroArgs instance var for description of this.964bool isVarargsElided = false;965966if (ContainsCodeCompletionTok) {967// Recover from not-fully-formed macro invocation during code-completion.968Token EOFTok;969EOFTok.startToken();970EOFTok.setKind(tok::eof);971EOFTok.setLocation(Tok.getLocation());972EOFTok.setLength(0);973for (; NumActuals < MinArgsExpected; ++NumActuals)974ArgTokens.push_back(EOFTok);975}976977if (NumActuals < MinArgsExpected) {978// There are several cases where too few arguments is ok, handle them now.979if (NumActuals == 0 && MinArgsExpected == 1) {980// #define A(X) or #define A(...) ---> A()981982// If there is exactly one argument, and that argument is missing,983// then we have an empty "()" argument empty list. This is fine, even if984// the macro expects one argument (the argument is just empty).985isVarargsElided = MI->isVariadic();986} else if ((FoundElidedComma || MI->isVariadic()) &&987(NumActuals+1 == MinArgsExpected || // A(x, ...) -> A(X)988(NumActuals == 0 && MinArgsExpected == 2))) {// A(x,...) -> A()989// Varargs where the named vararg parameter is missing: OK as extension.990// #define A(x, ...)991// A("blah")992//993// If the macro contains the comma pasting extension, the diagnostic994// is suppressed; we know we'll get another diagnostic later.995if (!MI->hasCommaPasting()) {996// C++20 [cpp.replace]p15, C23 6.10.5p12997//998// C++20 and C23 allow this construct, but standards before that999// do not (we allow it as an extension).1000unsigned ID;1001if (getLangOpts().CPlusPlus20)1002ID = diag::warn_cxx17_compat_missing_varargs_arg;1003else if (getLangOpts().CPlusPlus)1004ID = diag::ext_cxx_missing_varargs_arg;1005else if (getLangOpts().C23)1006ID = diag::warn_c17_compat_missing_varargs_arg;1007else1008ID = diag::ext_c_missing_varargs_arg;1009Diag(Tok, ID);1010Diag(MI->getDefinitionLoc(), diag::note_macro_here)1011<< MacroName.getIdentifierInfo();1012}10131014// Remember this occurred, allowing us to elide the comma when used for1015// cases like:1016// #define A(x, foo...) blah(a, ## foo)1017// #define B(x, ...) blah(a, ## __VA_ARGS__)1018// #define C(...) blah(a, ## __VA_ARGS__)1019// A(x) B(x) C()1020isVarargsElided = true;1021} else if (!ContainsCodeCompletionTok) {1022// Otherwise, emit the error.1023Diag(Tok, diag::err_too_few_args_in_macro_invoc);1024Diag(MI->getDefinitionLoc(), diag::note_macro_here)1025<< MacroName.getIdentifierInfo();1026return nullptr;1027}10281029// Add a marker EOF token to the end of the token list for this argument.1030SourceLocation EndLoc = Tok.getLocation();1031Tok.startToken();1032Tok.setKind(tok::eof);1033Tok.setLocation(EndLoc);1034Tok.setLength(0);1035ArgTokens.push_back(Tok);10361037// If we expect two arguments, add both as empty.1038if (NumActuals == 0 && MinArgsExpected == 2)1039ArgTokens.push_back(Tok);10401041} else if (NumActuals > MinArgsExpected && !MI->isVariadic() &&1042!ContainsCodeCompletionTok) {1043// Emit the diagnostic at the macro name in case there is a missing ).1044// Emitting it at the , could be far away from the macro name.1045Diag(MacroName, diag::err_too_many_args_in_macro_invoc);1046Diag(MI->getDefinitionLoc(), diag::note_macro_here)1047<< MacroName.getIdentifierInfo();1048return nullptr;1049}10501051return MacroArgs::create(MI, ArgTokens, isVarargsElided, *this);1052}10531054/// Keeps macro expanded tokens for TokenLexers.1055//1056/// Works like a stack; a TokenLexer adds the macro expanded tokens that is1057/// going to lex in the cache and when it finishes the tokens are removed1058/// from the end of the cache.1059Token *Preprocessor::cacheMacroExpandedTokens(TokenLexer *tokLexer,1060ArrayRef<Token> tokens) {1061assert(tokLexer);1062if (tokens.empty())1063return nullptr;10641065size_t newIndex = MacroExpandedTokens.size();1066bool cacheNeedsToGrow = tokens.size() >1067MacroExpandedTokens.capacity()-MacroExpandedTokens.size();1068MacroExpandedTokens.append(tokens.begin(), tokens.end());10691070if (cacheNeedsToGrow) {1071// Go through all the TokenLexers whose 'Tokens' pointer points in the1072// buffer and update the pointers to the (potential) new buffer array.1073for (const auto &Lexer : MacroExpandingLexersStack) {1074TokenLexer *prevLexer;1075size_t tokIndex;1076std::tie(prevLexer, tokIndex) = Lexer;1077prevLexer->Tokens = MacroExpandedTokens.data() + tokIndex;1078}1079}10801081MacroExpandingLexersStack.push_back(std::make_pair(tokLexer, newIndex));1082return MacroExpandedTokens.data() + newIndex;1083}10841085void Preprocessor::removeCachedMacroExpandedTokensOfLastLexer() {1086assert(!MacroExpandingLexersStack.empty());1087size_t tokIndex = MacroExpandingLexersStack.back().second;1088assert(tokIndex < MacroExpandedTokens.size());1089// Pop the cached macro expanded tokens from the end.1090MacroExpandedTokens.resize(tokIndex);1091MacroExpandingLexersStack.pop_back();1092}10931094/// ComputeDATE_TIME - Compute the current time, enter it into the specified1095/// scratch buffer, then return DATELoc/TIMELoc locations with the position of1096/// the identifier tokens inserted.1097static void ComputeDATE_TIME(SourceLocation &DATELoc, SourceLocation &TIMELoc,1098Preprocessor &PP) {1099time_t TT;1100std::tm *TM;1101if (PP.getPreprocessorOpts().SourceDateEpoch) {1102TT = *PP.getPreprocessorOpts().SourceDateEpoch;1103TM = std::gmtime(&TT);1104} else {1105TT = std::time(nullptr);1106TM = std::localtime(&TT);1107}11081109static const char * const Months[] = {1110"Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"1111};11121113{1114SmallString<32> TmpBuffer;1115llvm::raw_svector_ostream TmpStream(TmpBuffer);1116if (TM)1117TmpStream << llvm::format("\"%s %2d %4d\"", Months[TM->tm_mon],1118TM->tm_mday, TM->tm_year + 1900);1119else1120TmpStream << "??? ?? ????";1121Token TmpTok;1122TmpTok.startToken();1123PP.CreateString(TmpStream.str(), TmpTok);1124DATELoc = TmpTok.getLocation();1125}11261127{1128SmallString<32> TmpBuffer;1129llvm::raw_svector_ostream TmpStream(TmpBuffer);1130if (TM)1131TmpStream << llvm::format("\"%02d:%02d:%02d\"", TM->tm_hour, TM->tm_min,1132TM->tm_sec);1133else1134TmpStream << "??:??:??";1135Token TmpTok;1136TmpTok.startToken();1137PP.CreateString(TmpStream.str(), TmpTok);1138TIMELoc = TmpTok.getLocation();1139}1140}11411142/// HasFeature - Return true if we recognize and implement the feature1143/// specified by the identifier as a standard language feature.1144static bool HasFeature(const Preprocessor &PP, StringRef Feature) {1145const LangOptions &LangOpts = PP.getLangOpts();11461147// Normalize the feature name, __foo__ becomes foo.1148if (Feature.starts_with("__") && Feature.ends_with("__") &&1149Feature.size() >= 4)1150Feature = Feature.substr(2, Feature.size() - 4);11511152#define FEATURE(Name, Predicate) .Case(#Name, Predicate)1153return llvm::StringSwitch<bool>(Feature)1154#include "clang/Basic/Features.def"1155.Default(false);1156#undef FEATURE1157}11581159/// HasExtension - Return true if we recognize and implement the feature1160/// specified by the identifier, either as an extension or a standard language1161/// feature.1162static bool HasExtension(const Preprocessor &PP, StringRef Extension) {1163if (HasFeature(PP, Extension))1164return true;11651166// If the use of an extension results in an error diagnostic, extensions are1167// effectively unavailable, so just return false here.1168if (PP.getDiagnostics().getExtensionHandlingBehavior() >=1169diag::Severity::Error)1170return false;11711172const LangOptions &LangOpts = PP.getLangOpts();11731174// Normalize the extension name, __foo__ becomes foo.1175if (Extension.starts_with("__") && Extension.ends_with("__") &&1176Extension.size() >= 4)1177Extension = Extension.substr(2, Extension.size() - 4);11781179// Because we inherit the feature list from HasFeature, this string switch1180// must be less restrictive than HasFeature's.1181#define EXTENSION(Name, Predicate) .Case(#Name, Predicate)1182return llvm::StringSwitch<bool>(Extension)1183#include "clang/Basic/Features.def"1184.Default(false);1185#undef EXTENSION1186}11871188/// EvaluateHasIncludeCommon - Process a '__has_include("path")'1189/// or '__has_include_next("path")' expression.1190/// Returns true if successful.1191static bool EvaluateHasIncludeCommon(Token &Tok, IdentifierInfo *II,1192Preprocessor &PP,1193ConstSearchDirIterator LookupFrom,1194const FileEntry *LookupFromFile) {1195// Save the location of the current token. If a '(' is later found, use1196// that location. If not, use the end of this location instead.1197SourceLocation LParenLoc = Tok.getLocation();11981199// These expressions are only allowed within a preprocessor directive.1200if (!PP.isParsingIfOrElifDirective()) {1201PP.Diag(LParenLoc, diag::err_pp_directive_required) << II;1202// Return a valid identifier token.1203assert(Tok.is(tok::identifier));1204Tok.setIdentifierInfo(II);1205return false;1206}12071208// Get '('. If we don't have a '(', try to form a header-name token.1209do {1210if (PP.LexHeaderName(Tok))1211return false;1212} while (Tok.getKind() == tok::comment);12131214// Ensure we have a '('.1215if (Tok.isNot(tok::l_paren)) {1216// No '(', use end of last token.1217LParenLoc = PP.getLocForEndOfToken(LParenLoc);1218PP.Diag(LParenLoc, diag::err_pp_expected_after) << II << tok::l_paren;1219// If the next token looks like a filename or the start of one,1220// assume it is and process it as such.1221if (Tok.isNot(tok::header_name))1222return false;1223} else {1224// Save '(' location for possible missing ')' message.1225LParenLoc = Tok.getLocation();1226if (PP.LexHeaderName(Tok))1227return false;1228}12291230if (Tok.isNot(tok::header_name)) {1231PP.Diag(Tok.getLocation(), diag::err_pp_expects_filename);1232return false;1233}12341235// Reserve a buffer to get the spelling.1236SmallString<128> FilenameBuffer;1237bool Invalid = false;1238StringRef Filename = PP.getSpelling(Tok, FilenameBuffer, &Invalid);1239if (Invalid)1240return false;12411242SourceLocation FilenameLoc = Tok.getLocation();12431244// Get ')'.1245PP.LexNonComment(Tok);12461247// Ensure we have a trailing ).1248if (Tok.isNot(tok::r_paren)) {1249PP.Diag(PP.getLocForEndOfToken(FilenameLoc), diag::err_pp_expected_after)1250<< II << tok::r_paren;1251PP.Diag(LParenLoc, diag::note_matching) << tok::l_paren;1252return false;1253}12541255bool isAngled = PP.GetIncludeFilenameSpelling(Tok.getLocation(), Filename);1256// If GetIncludeFilenameSpelling set the start ptr to null, there was an1257// error.1258if (Filename.empty())1259return false;12601261// Passing this to LookupFile forces header search to check whether the found1262// file belongs to a module. Skipping that check could incorrectly mark1263// modular header as textual, causing issues down the line.1264ModuleMap::KnownHeader KH;12651266// Search include directories.1267OptionalFileEntryRef File =1268PP.LookupFile(FilenameLoc, Filename, isAngled, LookupFrom, LookupFromFile,1269nullptr, nullptr, nullptr, &KH, nullptr, nullptr);12701271if (PPCallbacks *Callbacks = PP.getPPCallbacks()) {1272SrcMgr::CharacteristicKind FileType = SrcMgr::C_User;1273if (File)1274FileType = PP.getHeaderSearchInfo().getFileDirFlavor(*File);1275Callbacks->HasInclude(FilenameLoc, Filename, isAngled, File, FileType);1276}12771278// Get the result value. A result of true means the file exists.1279return File.has_value();1280}12811282/// EvaluateHasEmbed - Process a '__has_embed("foo" params...)' expression.1283/// Returns a filled optional with the value if successful; otherwise, empty.1284EmbedResult Preprocessor::EvaluateHasEmbed(Token &Tok, IdentifierInfo *II) {1285// These expressions are only allowed within a preprocessor directive.1286if (!this->isParsingIfOrElifDirective()) {1287Diag(Tok, diag::err_pp_directive_required) << II;1288// Return a valid identifier token.1289assert(Tok.is(tok::identifier));1290Tok.setIdentifierInfo(II);1291return EmbedResult::Invalid;1292}12931294// Ensure we have a '('.1295LexUnexpandedToken(Tok);1296if (Tok.isNot(tok::l_paren)) {1297Diag(Tok, diag::err_pp_expected_after) << II << tok::l_paren;1298// If the next token looks like a filename or the start of one,1299// assume it is and process it as such.1300return EmbedResult::Invalid;1301}13021303// Save '(' location for possible missing ')' message and then lex the header1304// name token for the embed resource.1305SourceLocation LParenLoc = Tok.getLocation();1306if (this->LexHeaderName(Tok))1307return EmbedResult::Invalid;13081309if (Tok.isNot(tok::header_name)) {1310Diag(Tok.getLocation(), diag::err_pp_expects_filename);1311return EmbedResult::Invalid;1312}13131314SourceLocation FilenameLoc = Tok.getLocation();1315Token FilenameTok = Tok;13161317std::optional<LexEmbedParametersResult> Params =1318this->LexEmbedParameters(Tok, /*ForHasEmbed=*/true);1319assert((Params || Tok.is(tok::eod)) &&1320"expected success or to be at the end of the directive");13211322if (!Params)1323return EmbedResult::Invalid;13241325if (Params->UnrecognizedParams > 0)1326return EmbedResult::NotFound;13271328if (!Tok.is(tok::r_paren)) {1329Diag(this->getLocForEndOfToken(FilenameLoc), diag::err_pp_expected_after)1330<< II << tok::r_paren;1331Diag(LParenLoc, diag::note_matching) << tok::l_paren;1332if (Tok.isNot(tok::eod))1333DiscardUntilEndOfDirective();1334return EmbedResult::Invalid;1335}13361337SmallString<128> FilenameBuffer;1338StringRef Filename = this->getSpelling(FilenameTok, FilenameBuffer);1339bool isAngled =1340this->GetIncludeFilenameSpelling(FilenameTok.getLocation(), Filename);1341// If GetIncludeFilenameSpelling set the start ptr to null, there was an1342// error.1343assert(!Filename.empty());1344const FileEntry *LookupFromFile =1345this->getCurrentFileLexer() ? *this->getCurrentFileLexer()->getFileEntry()1346: static_cast<FileEntry *>(nullptr);1347OptionalFileEntryRef MaybeFileEntry =1348this->LookupEmbedFile(Filename, isAngled, false, LookupFromFile);1349if (Callbacks) {1350Callbacks->HasEmbed(LParenLoc, Filename, isAngled, MaybeFileEntry);1351}1352if (!MaybeFileEntry)1353return EmbedResult::NotFound;13541355size_t FileSize = MaybeFileEntry->getSize();1356// First, "offset" into the file (this reduces the amount of data we can read1357// from the file).1358if (Params->MaybeOffsetParam) {1359if (Params->MaybeOffsetParam->Offset > FileSize)1360FileSize = 0;1361else1362FileSize -= Params->MaybeOffsetParam->Offset;1363}13641365// Second, limit the data from the file (this also reduces the amount of data1366// we can read from the file).1367if (Params->MaybeLimitParam) {1368if (Params->MaybeLimitParam->Limit > FileSize)1369FileSize = 0;1370else1371FileSize = Params->MaybeLimitParam->Limit;1372}13731374// If we have no data left to read, the file is empty, otherwise we have the1375// expected resource.1376if (FileSize == 0)1377return EmbedResult::Empty;1378return EmbedResult::Found;1379}13801381bool Preprocessor::EvaluateHasInclude(Token &Tok, IdentifierInfo *II) {1382return EvaluateHasIncludeCommon(Tok, II, *this, nullptr, nullptr);1383}13841385bool Preprocessor::EvaluateHasIncludeNext(Token &Tok, IdentifierInfo *II) {1386ConstSearchDirIterator Lookup = nullptr;1387const FileEntry *LookupFromFile;1388std::tie(Lookup, LookupFromFile) = getIncludeNextStart(Tok);13891390return EvaluateHasIncludeCommon(Tok, II, *this, Lookup, LookupFromFile);1391}13921393/// Process single-argument builtin feature-like macros that return1394/// integer values.1395static void EvaluateFeatureLikeBuiltinMacro(llvm::raw_svector_ostream& OS,1396Token &Tok, IdentifierInfo *II,1397Preprocessor &PP, bool ExpandArgs,1398llvm::function_ref<1399int(Token &Tok,1400bool &HasLexedNextTok)> Op) {1401// Parse the initial '('.1402PP.LexUnexpandedToken(Tok);1403if (Tok.isNot(tok::l_paren)) {1404PP.Diag(Tok.getLocation(), diag::err_pp_expected_after) << II1405<< tok::l_paren;14061407// Provide a dummy '0' value on output stream to elide further errors.1408if (!Tok.isOneOf(tok::eof, tok::eod)) {1409OS << 0;1410Tok.setKind(tok::numeric_constant);1411}1412return;1413}14141415unsigned ParenDepth = 1;1416SourceLocation LParenLoc = Tok.getLocation();1417std::optional<int> Result;14181419Token ResultTok;1420bool SuppressDiagnostic = false;1421while (true) {1422// Parse next token.1423if (ExpandArgs)1424PP.Lex(Tok);1425else1426PP.LexUnexpandedToken(Tok);14271428already_lexed:1429switch (Tok.getKind()) {1430case tok::eof:1431case tok::eod:1432// Don't provide even a dummy value if the eod or eof marker is1433// reached. Simply provide a diagnostic.1434PP.Diag(Tok.getLocation(), diag::err_unterm_macro_invoc);1435return;14361437case tok::comma:1438if (!SuppressDiagnostic) {1439PP.Diag(Tok.getLocation(), diag::err_too_many_args_in_macro_invoc);1440SuppressDiagnostic = true;1441}1442continue;14431444case tok::l_paren:1445++ParenDepth;1446if (Result)1447break;1448if (!SuppressDiagnostic) {1449PP.Diag(Tok.getLocation(), diag::err_pp_nested_paren) << II;1450SuppressDiagnostic = true;1451}1452continue;14531454case tok::r_paren:1455if (--ParenDepth > 0)1456continue;14571458// The last ')' has been reached; return the value if one found or1459// a diagnostic and a dummy value.1460if (Result) {1461OS << *Result;1462// For strict conformance to __has_cpp_attribute rules, use 'L'1463// suffix for dated literals.1464if (*Result > 1)1465OS << 'L';1466} else {1467OS << 0;1468if (!SuppressDiagnostic)1469PP.Diag(Tok.getLocation(), diag::err_too_few_args_in_macro_invoc);1470}1471Tok.setKind(tok::numeric_constant);1472return;14731474default: {1475// Parse the macro argument, if one not found so far.1476if (Result)1477break;14781479bool HasLexedNextToken = false;1480Result = Op(Tok, HasLexedNextToken);1481ResultTok = Tok;1482if (HasLexedNextToken)1483goto already_lexed;1484continue;1485}1486}14871488// Diagnose missing ')'.1489if (!SuppressDiagnostic) {1490if (auto Diag = PP.Diag(Tok.getLocation(), diag::err_pp_expected_after)) {1491if (IdentifierInfo *LastII = ResultTok.getIdentifierInfo())1492Diag << LastII;1493else1494Diag << ResultTok.getKind();1495Diag << tok::r_paren << ResultTok.getLocation();1496}1497PP.Diag(LParenLoc, diag::note_matching) << tok::l_paren;1498SuppressDiagnostic = true;1499}1500}1501}15021503/// Helper function to return the IdentifierInfo structure of a Token1504/// or generate a diagnostic if none available.1505static IdentifierInfo *ExpectFeatureIdentifierInfo(Token &Tok,1506Preprocessor &PP,1507signed DiagID) {1508IdentifierInfo *II;1509if (!Tok.isAnnotation() && (II = Tok.getIdentifierInfo()))1510return II;15111512PP.Diag(Tok.getLocation(), DiagID);1513return nullptr;1514}15151516/// Implements the __is_target_arch builtin macro.1517static bool isTargetArch(const TargetInfo &TI, const IdentifierInfo *II) {1518std::string ArchName = II->getName().lower() + "--";1519llvm::Triple Arch(ArchName);1520const llvm::Triple &TT = TI.getTriple();1521if (TT.isThumb()) {1522// arm matches thumb or thumbv7. armv7 matches thumbv7.1523if ((Arch.getSubArch() == llvm::Triple::NoSubArch ||1524Arch.getSubArch() == TT.getSubArch()) &&1525((TT.getArch() == llvm::Triple::thumb &&1526Arch.getArch() == llvm::Triple::arm) ||1527(TT.getArch() == llvm::Triple::thumbeb &&1528Arch.getArch() == llvm::Triple::armeb)))1529return true;1530}1531// Check the parsed arch when it has no sub arch to allow Clang to1532// match thumb to thumbv7 but to prohibit matching thumbv6 to thumbv7.1533return (Arch.getSubArch() == llvm::Triple::NoSubArch ||1534Arch.getSubArch() == TT.getSubArch()) &&1535Arch.getArch() == TT.getArch();1536}15371538/// Implements the __is_target_vendor builtin macro.1539static bool isTargetVendor(const TargetInfo &TI, const IdentifierInfo *II) {1540StringRef VendorName = TI.getTriple().getVendorName();1541if (VendorName.empty())1542VendorName = "unknown";1543return VendorName.equals_insensitive(II->getName());1544}15451546/// Implements the __is_target_os builtin macro.1547static bool isTargetOS(const TargetInfo &TI, const IdentifierInfo *II) {1548std::string OSName =1549(llvm::Twine("unknown-unknown-") + II->getName().lower()).str();1550llvm::Triple OS(OSName);1551if (OS.getOS() == llvm::Triple::Darwin) {1552// Darwin matches macos, ios, etc.1553return TI.getTriple().isOSDarwin();1554}1555return TI.getTriple().getOS() == OS.getOS();1556}15571558/// Implements the __is_target_environment builtin macro.1559static bool isTargetEnvironment(const TargetInfo &TI,1560const IdentifierInfo *II) {1561std::string EnvName = (llvm::Twine("---") + II->getName().lower()).str();1562llvm::Triple Env(EnvName);1563// The unknown environment is matched only if1564// '__is_target_environment(unknown)' is used.1565if (Env.getEnvironment() == llvm::Triple::UnknownEnvironment &&1566EnvName != "---unknown")1567return false;1568return TI.getTriple().getEnvironment() == Env.getEnvironment();1569}15701571/// Implements the __is_target_variant_os builtin macro.1572static bool isTargetVariantOS(const TargetInfo &TI, const IdentifierInfo *II) {1573if (TI.getTriple().isOSDarwin()) {1574const llvm::Triple *VariantTriple = TI.getDarwinTargetVariantTriple();1575if (!VariantTriple)1576return false;15771578std::string OSName =1579(llvm::Twine("unknown-unknown-") + II->getName().lower()).str();1580llvm::Triple OS(OSName);1581if (OS.getOS() == llvm::Triple::Darwin) {1582// Darwin matches macos, ios, etc.1583return VariantTriple->isOSDarwin();1584}1585return VariantTriple->getOS() == OS.getOS();1586}1587return false;1588}15891590/// Implements the __is_target_variant_environment builtin macro.1591static bool isTargetVariantEnvironment(const TargetInfo &TI,1592const IdentifierInfo *II) {1593if (TI.getTriple().isOSDarwin()) {1594const llvm::Triple *VariantTriple = TI.getDarwinTargetVariantTriple();1595if (!VariantTriple)1596return false;1597std::string EnvName = (llvm::Twine("---") + II->getName().lower()).str();1598llvm::Triple Env(EnvName);1599return VariantTriple->getEnvironment() == Env.getEnvironment();1600}1601return false;1602}16031604static bool IsBuiltinTrait(Token &Tok) {16051606#define TYPE_TRAIT_1(Spelling, Name, Key) \1607case tok::kw_##Spelling: \1608return true;1609#define TYPE_TRAIT_2(Spelling, Name, Key) \1610case tok::kw_##Spelling: \1611return true;1612#define TYPE_TRAIT_N(Spelling, Name, Key) \1613case tok::kw_##Spelling: \1614return true;1615#define ARRAY_TYPE_TRAIT(Spelling, Name, Key) \1616case tok::kw_##Spelling: \1617return true;1618#define EXPRESSION_TRAIT(Spelling, Name, Key) \1619case tok::kw_##Spelling: \1620return true;1621#define TRANSFORM_TYPE_TRAIT_DEF(K, Spelling) \1622case tok::kw___##Spelling: \1623return true;16241625switch (Tok.getKind()) {1626default:1627return false;1628#include "clang/Basic/TokenKinds.def"1629}1630}16311632/// ExpandBuiltinMacro - If an identifier token is read that is to be expanded1633/// as a builtin macro, handle it and return the next token as 'Tok'.1634void Preprocessor::ExpandBuiltinMacro(Token &Tok) {1635// Figure out which token this is.1636IdentifierInfo *II = Tok.getIdentifierInfo();1637assert(II && "Can't be a macro without id info!");16381639// If this is an _Pragma or Microsoft __pragma directive, expand it,1640// invoke the pragma handler, then lex the token after it.1641if (II == Ident_Pragma)1642return Handle_Pragma(Tok);1643else if (II == Ident__pragma) // in non-MS mode this is null1644return HandleMicrosoft__pragma(Tok);16451646++NumBuiltinMacroExpanded;16471648SmallString<128> TmpBuffer;1649llvm::raw_svector_ostream OS(TmpBuffer);16501651// Set up the return result.1652Tok.setIdentifierInfo(nullptr);1653Tok.clearFlag(Token::NeedsCleaning);1654bool IsAtStartOfLine = Tok.isAtStartOfLine();1655bool HasLeadingSpace = Tok.hasLeadingSpace();16561657if (II == Ident__LINE__) {1658// C99 6.10.8: "__LINE__: The presumed line number (within the current1659// source file) of the current source line (an integer constant)". This can1660// be affected by #line.1661SourceLocation Loc = Tok.getLocation();16621663// Advance to the location of the first _, this might not be the first byte1664// of the token if it starts with an escaped newline.1665Loc = AdvanceToTokenCharacter(Loc, 0);16661667// One wrinkle here is that GCC expands __LINE__ to location of the *end* of1668// a macro expansion. This doesn't matter for object-like macros, but1669// can matter for a function-like macro that expands to contain __LINE__.1670// Skip down through expansion points until we find a file loc for the1671// end of the expansion history.1672Loc = SourceMgr.getExpansionRange(Loc).getEnd();1673PresumedLoc PLoc = SourceMgr.getPresumedLoc(Loc);16741675// __LINE__ expands to a simple numeric value.1676OS << (PLoc.isValid()? PLoc.getLine() : 1);1677Tok.setKind(tok::numeric_constant);1678} else if (II == Ident__FILE__ || II == Ident__BASE_FILE__ ||1679II == Ident__FILE_NAME__) {1680// C99 6.10.8: "__FILE__: The presumed name of the current source file (a1681// character string literal)". This can be affected by #line.1682PresumedLoc PLoc = SourceMgr.getPresumedLoc(Tok.getLocation());16831684// __BASE_FILE__ is a GNU extension that returns the top of the presumed1685// #include stack instead of the current file.1686if (II == Ident__BASE_FILE__ && PLoc.isValid()) {1687SourceLocation NextLoc = PLoc.getIncludeLoc();1688while (NextLoc.isValid()) {1689PLoc = SourceMgr.getPresumedLoc(NextLoc);1690if (PLoc.isInvalid())1691break;16921693NextLoc = PLoc.getIncludeLoc();1694}1695}16961697// Escape this filename. Turn '\' -> '\\' '"' -> '\"'1698SmallString<256> FN;1699if (PLoc.isValid()) {1700// __FILE_NAME__ is a Clang-specific extension that expands to the1701// the last part of __FILE__.1702if (II == Ident__FILE_NAME__) {1703processPathToFileName(FN, PLoc, getLangOpts(), getTargetInfo());1704} else {1705FN += PLoc.getFilename();1706processPathForFileMacro(FN, getLangOpts(), getTargetInfo());1707}1708Lexer::Stringify(FN);1709OS << '"' << FN << '"';1710}1711Tok.setKind(tok::string_literal);1712} else if (II == Ident__DATE__) {1713Diag(Tok.getLocation(), diag::warn_pp_date_time);1714if (!DATELoc.isValid())1715ComputeDATE_TIME(DATELoc, TIMELoc, *this);1716Tok.setKind(tok::string_literal);1717Tok.setLength(strlen("\"Mmm dd yyyy\""));1718Tok.setLocation(SourceMgr.createExpansionLoc(DATELoc, Tok.getLocation(),1719Tok.getLocation(),1720Tok.getLength()));1721return;1722} else if (II == Ident__TIME__) {1723Diag(Tok.getLocation(), diag::warn_pp_date_time);1724if (!TIMELoc.isValid())1725ComputeDATE_TIME(DATELoc, TIMELoc, *this);1726Tok.setKind(tok::string_literal);1727Tok.setLength(strlen("\"hh:mm:ss\""));1728Tok.setLocation(SourceMgr.createExpansionLoc(TIMELoc, Tok.getLocation(),1729Tok.getLocation(),1730Tok.getLength()));1731return;1732} else if (II == Ident__INCLUDE_LEVEL__) {1733// Compute the presumed include depth of this token. This can be affected1734// by GNU line markers.1735unsigned Depth = 0;17361737PresumedLoc PLoc = SourceMgr.getPresumedLoc(Tok.getLocation());1738if (PLoc.isValid()) {1739PLoc = SourceMgr.getPresumedLoc(PLoc.getIncludeLoc());1740for (; PLoc.isValid(); ++Depth)1741PLoc = SourceMgr.getPresumedLoc(PLoc.getIncludeLoc());1742}17431744// __INCLUDE_LEVEL__ expands to a simple numeric value.1745OS << Depth;1746Tok.setKind(tok::numeric_constant);1747} else if (II == Ident__TIMESTAMP__) {1748Diag(Tok.getLocation(), diag::warn_pp_date_time);1749// MSVC, ICC, GCC, VisualAge C++ extension. The generated string should be1750// of the form "Ddd Mmm dd hh::mm::ss yyyy", which is returned by asctime.1751const char *Result;1752if (getPreprocessorOpts().SourceDateEpoch) {1753time_t TT = *getPreprocessorOpts().SourceDateEpoch;1754std::tm *TM = std::gmtime(&TT);1755Result = asctime(TM);1756} else {1757// Get the file that we are lexing out of. If we're currently lexing from1758// a macro, dig into the include stack.1759const FileEntry *CurFile = nullptr;1760if (PreprocessorLexer *TheLexer = getCurrentFileLexer())1761CurFile = SourceMgr.getFileEntryForID(TheLexer->getFileID());1762if (CurFile) {1763time_t TT = CurFile->getModificationTime();1764struct tm *TM = localtime(&TT);1765Result = asctime(TM);1766} else {1767Result = "??? ??? ?? ??:??:?? ????\n";1768}1769}1770// Surround the string with " and strip the trailing newline.1771OS << '"' << StringRef(Result).drop_back() << '"';1772Tok.setKind(tok::string_literal);1773} else if (II == Ident__FLT_EVAL_METHOD__) {1774// __FLT_EVAL_METHOD__ is set to the default value.1775OS << getTUFPEvalMethod();1776// __FLT_EVAL_METHOD__ expands to a simple numeric value.1777Tok.setKind(tok::numeric_constant);1778if (getLastFPEvalPragmaLocation().isValid()) {1779// The program is ill-formed. The value of __FLT_EVAL_METHOD__ is altered1780// by the pragma.1781Diag(Tok, diag::err_illegal_use_of_flt_eval_macro);1782Diag(getLastFPEvalPragmaLocation(), diag::note_pragma_entered_here);1783}1784} else if (II == Ident__COUNTER__) {1785// __COUNTER__ expands to a simple numeric value.1786OS << CounterValue++;1787Tok.setKind(tok::numeric_constant);1788} else if (II == Ident__has_feature) {1789EvaluateFeatureLikeBuiltinMacro(OS, Tok, II, *this, false,1790[this](Token &Tok, bool &HasLexedNextToken) -> int {1791IdentifierInfo *II = ExpectFeatureIdentifierInfo(Tok, *this,1792diag::err_feature_check_malformed);1793return II && HasFeature(*this, II->getName());1794});1795} else if (II == Ident__has_extension) {1796EvaluateFeatureLikeBuiltinMacro(OS, Tok, II, *this, false,1797[this](Token &Tok, bool &HasLexedNextToken) -> int {1798IdentifierInfo *II = ExpectFeatureIdentifierInfo(Tok, *this,1799diag::err_feature_check_malformed);1800return II && HasExtension(*this, II->getName());1801});1802} else if (II == Ident__has_builtin) {1803EvaluateFeatureLikeBuiltinMacro(OS, Tok, II, *this, false,1804[this](Token &Tok, bool &HasLexedNextToken) -> int {1805IdentifierInfo *II = ExpectFeatureIdentifierInfo(Tok, *this,1806diag::err_feature_check_malformed);1807if (!II)1808return false;1809else if (II->getBuiltinID() != 0) {1810switch (II->getBuiltinID()) {1811case Builtin::BI__builtin_cpu_is:1812return getTargetInfo().supportsCpuIs();1813case Builtin::BI__builtin_cpu_init:1814return getTargetInfo().supportsCpuInit();1815case Builtin::BI__builtin_cpu_supports:1816return getTargetInfo().supportsCpuSupports();1817case Builtin::BI__builtin_operator_new:1818case Builtin::BI__builtin_operator_delete:1819// denotes date of behavior change to support calling arbitrary1820// usual allocation and deallocation functions. Required by libc++1821return 201802;1822default:1823return Builtin::evaluateRequiredTargetFeatures(1824getBuiltinInfo().getRequiredFeatures(II->getBuiltinID()),1825getTargetInfo().getTargetOpts().FeatureMap);1826}1827return true;1828} else if (IsBuiltinTrait(Tok)) {1829return true;1830} else if (II->getTokenID() != tok::identifier &&1831II->getName().starts_with("__builtin_")) {1832return true;1833} else {1834return llvm::StringSwitch<bool>(II->getName())1835// Report builtin templates as being builtins.1836.Case("__make_integer_seq", getLangOpts().CPlusPlus)1837.Case("__type_pack_element", getLangOpts().CPlusPlus)1838// Likewise for some builtin preprocessor macros.1839// FIXME: This is inconsistent; we usually suggest detecting1840// builtin macros via #ifdef. Don't add more cases here.1841.Case("__is_target_arch", true)1842.Case("__is_target_vendor", true)1843.Case("__is_target_os", true)1844.Case("__is_target_environment", true)1845.Case("__is_target_variant_os", true)1846.Case("__is_target_variant_environment", true)1847.Default(false);1848}1849});1850} else if (II == Ident__has_constexpr_builtin) {1851EvaluateFeatureLikeBuiltinMacro(1852OS, Tok, II, *this, false,1853[this](Token &Tok, bool &HasLexedNextToken) -> int {1854IdentifierInfo *II = ExpectFeatureIdentifierInfo(1855Tok, *this, diag::err_feature_check_malformed);1856if (!II)1857return false;1858unsigned BuiltinOp = II->getBuiltinID();1859return BuiltinOp != 0 &&1860this->getBuiltinInfo().isConstantEvaluated(BuiltinOp);1861});1862} else if (II == Ident__is_identifier) {1863EvaluateFeatureLikeBuiltinMacro(OS, Tok, II, *this, false,1864[](Token &Tok, bool &HasLexedNextToken) -> int {1865return Tok.is(tok::identifier);1866});1867} else if (II == Ident__has_attribute) {1868EvaluateFeatureLikeBuiltinMacro(OS, Tok, II, *this, true,1869[this](Token &Tok, bool &HasLexedNextToken) -> int {1870IdentifierInfo *II = ExpectFeatureIdentifierInfo(Tok, *this,1871diag::err_feature_check_malformed);1872return II ? hasAttribute(AttributeCommonInfo::Syntax::AS_GNU, nullptr,1873II, getTargetInfo(), getLangOpts())1874: 0;1875});1876} else if (II == Ident__has_declspec) {1877EvaluateFeatureLikeBuiltinMacro(OS, Tok, II, *this, true,1878[this](Token &Tok, bool &HasLexedNextToken) -> int {1879IdentifierInfo *II = ExpectFeatureIdentifierInfo(Tok, *this,1880diag::err_feature_check_malformed);1881if (II) {1882const LangOptions &LangOpts = getLangOpts();1883return LangOpts.DeclSpecKeyword &&1884hasAttribute(AttributeCommonInfo::Syntax::AS_Declspec, nullptr,1885II, getTargetInfo(), LangOpts);1886}18871888return false;1889});1890} else if (II == Ident__has_cpp_attribute ||1891II == Ident__has_c_attribute) {1892bool IsCXX = II == Ident__has_cpp_attribute;1893EvaluateFeatureLikeBuiltinMacro(OS, Tok, II, *this, true,1894[&](Token &Tok, bool &HasLexedNextToken) -> int {1895IdentifierInfo *ScopeII = nullptr;1896IdentifierInfo *II = ExpectFeatureIdentifierInfo(1897Tok, *this, diag::err_feature_check_malformed);1898if (!II)1899return false;19001901// It is possible to receive a scope token. Read the "::", if it is1902// available, and the subsequent identifier.1903LexUnexpandedToken(Tok);1904if (Tok.isNot(tok::coloncolon))1905HasLexedNextToken = true;1906else {1907ScopeII = II;1908// Lex an expanded token for the attribute name.1909Lex(Tok);1910II = ExpectFeatureIdentifierInfo(Tok, *this,1911diag::err_feature_check_malformed);1912}19131914AttributeCommonInfo::Syntax Syntax =1915IsCXX ? AttributeCommonInfo::Syntax::AS_CXX111916: AttributeCommonInfo::Syntax::AS_C23;1917return II ? hasAttribute(Syntax, ScopeII, II, getTargetInfo(),1918getLangOpts())1919: 0;1920});1921} else if (II == Ident__has_include ||1922II == Ident__has_include_next) {1923// The argument to these two builtins should be a parenthesized1924// file name string literal using angle brackets (<>) or1925// double-quotes ("").1926bool Value;1927if (II == Ident__has_include)1928Value = EvaluateHasInclude(Tok, II);1929else1930Value = EvaluateHasIncludeNext(Tok, II);19311932if (Tok.isNot(tok::r_paren))1933return;1934OS << (int)Value;1935Tok.setKind(tok::numeric_constant);1936} else if (II == Ident__has_embed) {1937// The argument to these two builtins should be a parenthesized1938// file name string literal using angle brackets (<>) or1939// double-quotes (""), optionally followed by a series of1940// arguments similar to form like attributes.1941EmbedResult Value = EvaluateHasEmbed(Tok, II);1942if (Value == EmbedResult::Invalid)1943return;19441945Tok.setKind(tok::numeric_constant);1946OS << static_cast<int>(Value);1947} else if (II == Ident__has_warning) {1948// The argument should be a parenthesized string literal.1949EvaluateFeatureLikeBuiltinMacro(OS, Tok, II, *this, false,1950[this](Token &Tok, bool &HasLexedNextToken) -> int {1951std::string WarningName;1952SourceLocation StrStartLoc = Tok.getLocation();19531954HasLexedNextToken = Tok.is(tok::string_literal);1955if (!FinishLexStringLiteral(Tok, WarningName, "'__has_warning'",1956/*AllowMacroExpansion=*/false))1957return false;19581959// FIXME: Should we accept "-R..." flags here, or should that be1960// handled by a separate __has_remark?1961if (WarningName.size() < 3 || WarningName[0] != '-' ||1962WarningName[1] != 'W') {1963Diag(StrStartLoc, diag::warn_has_warning_invalid_option);1964return false;1965}19661967// Finally, check if the warning flags maps to a diagnostic group.1968// We construct a SmallVector here to talk to getDiagnosticIDs().1969// Although we don't use the result, this isn't a hot path, and not1970// worth special casing.1971SmallVector<diag::kind, 10> Diags;1972return !getDiagnostics().getDiagnosticIDs()->1973getDiagnosticsInGroup(diag::Flavor::WarningOrError,1974WarningName.substr(2), Diags);1975});1976} else if (II == Ident__building_module) {1977// The argument to this builtin should be an identifier. The1978// builtin evaluates to 1 when that identifier names the module we are1979// currently building.1980EvaluateFeatureLikeBuiltinMacro(OS, Tok, II, *this, false,1981[this](Token &Tok, bool &HasLexedNextToken) -> int {1982IdentifierInfo *II = ExpectFeatureIdentifierInfo(Tok, *this,1983diag::err_expected_id_building_module);1984return getLangOpts().isCompilingModule() && II &&1985(II->getName() == getLangOpts().CurrentModule);1986});1987} else if (II == Ident__MODULE__) {1988// The current module as an identifier.1989OS << getLangOpts().CurrentModule;1990IdentifierInfo *ModuleII = getIdentifierInfo(getLangOpts().CurrentModule);1991Tok.setIdentifierInfo(ModuleII);1992Tok.setKind(ModuleII->getTokenID());1993} else if (II == Ident__identifier) {1994SourceLocation Loc = Tok.getLocation();19951996// We're expecting '__identifier' '(' identifier ')'. Try to recover1997// if the parens are missing.1998LexNonComment(Tok);1999if (Tok.isNot(tok::l_paren)) {2000// No '(', use end of last token.2001Diag(getLocForEndOfToken(Loc), diag::err_pp_expected_after)2002<< II << tok::l_paren;2003// If the next token isn't valid as our argument, we can't recover.2004if (!Tok.isAnnotation() && Tok.getIdentifierInfo())2005Tok.setKind(tok::identifier);2006return;2007}20082009SourceLocation LParenLoc = Tok.getLocation();2010LexNonComment(Tok);20112012if (!Tok.isAnnotation() && Tok.getIdentifierInfo())2013Tok.setKind(tok::identifier);2014else if (Tok.is(tok::string_literal) && !Tok.hasUDSuffix()) {2015StringLiteralParser Literal(Tok, *this,2016StringLiteralEvalMethod::Unevaluated);2017if (Literal.hadError)2018return;20192020Tok.setIdentifierInfo(getIdentifierInfo(Literal.GetString()));2021Tok.setKind(tok::identifier);2022} else {2023Diag(Tok.getLocation(), diag::err_pp_identifier_arg_not_identifier)2024<< Tok.getKind();2025// Don't walk past anything that's not a real token.2026if (Tok.isOneOf(tok::eof, tok::eod) || Tok.isAnnotation())2027return;2028}20292030// Discard the ')', preserving 'Tok' as our result.2031Token RParen;2032LexNonComment(RParen);2033if (RParen.isNot(tok::r_paren)) {2034Diag(getLocForEndOfToken(Tok.getLocation()), diag::err_pp_expected_after)2035<< Tok.getKind() << tok::r_paren;2036Diag(LParenLoc, diag::note_matching) << tok::l_paren;2037}2038return;2039} else if (II == Ident__is_target_arch) {2040EvaluateFeatureLikeBuiltinMacro(2041OS, Tok, II, *this, false,2042[this](Token &Tok, bool &HasLexedNextToken) -> int {2043IdentifierInfo *II = ExpectFeatureIdentifierInfo(2044Tok, *this, diag::err_feature_check_malformed);2045return II && isTargetArch(getTargetInfo(), II);2046});2047} else if (II == Ident__is_target_vendor) {2048EvaluateFeatureLikeBuiltinMacro(2049OS, Tok, II, *this, false,2050[this](Token &Tok, bool &HasLexedNextToken) -> int {2051IdentifierInfo *II = ExpectFeatureIdentifierInfo(2052Tok, *this, diag::err_feature_check_malformed);2053return II && isTargetVendor(getTargetInfo(), II);2054});2055} else if (II == Ident__is_target_os) {2056EvaluateFeatureLikeBuiltinMacro(2057OS, Tok, II, *this, false,2058[this](Token &Tok, bool &HasLexedNextToken) -> int {2059IdentifierInfo *II = ExpectFeatureIdentifierInfo(2060Tok, *this, diag::err_feature_check_malformed);2061return II && isTargetOS(getTargetInfo(), II);2062});2063} else if (II == Ident__is_target_environment) {2064EvaluateFeatureLikeBuiltinMacro(2065OS, Tok, II, *this, false,2066[this](Token &Tok, bool &HasLexedNextToken) -> int {2067IdentifierInfo *II = ExpectFeatureIdentifierInfo(2068Tok, *this, diag::err_feature_check_malformed);2069return II && isTargetEnvironment(getTargetInfo(), II);2070});2071} else if (II == Ident__is_target_variant_os) {2072EvaluateFeatureLikeBuiltinMacro(2073OS, Tok, II, *this, false,2074[this](Token &Tok, bool &HasLexedNextToken) -> int {2075IdentifierInfo *II = ExpectFeatureIdentifierInfo(2076Tok, *this, diag::err_feature_check_malformed);2077return II && isTargetVariantOS(getTargetInfo(), II);2078});2079} else if (II == Ident__is_target_variant_environment) {2080EvaluateFeatureLikeBuiltinMacro(2081OS, Tok, II, *this, false,2082[this](Token &Tok, bool &HasLexedNextToken) -> int {2083IdentifierInfo *II = ExpectFeatureIdentifierInfo(2084Tok, *this, diag::err_feature_check_malformed);2085return II && isTargetVariantEnvironment(getTargetInfo(), II);2086});2087} else {2088llvm_unreachable("Unknown identifier!");2089}2090CreateString(OS.str(), Tok, Tok.getLocation(), Tok.getLocation());2091Tok.setFlagValue(Token::StartOfLine, IsAtStartOfLine);2092Tok.setFlagValue(Token::LeadingSpace, HasLeadingSpace);2093}20942095void Preprocessor::markMacroAsUsed(MacroInfo *MI) {2096// If the 'used' status changed, and the macro requires 'unused' warning,2097// remove its SourceLocation from the warn-for-unused-macro locations.2098if (MI->isWarnIfUnused() && !MI->isUsed())2099WarnUnusedMacroLocs.erase(MI->getDefinitionLoc());2100MI->setIsUsed(true);2101}21022103void Preprocessor::processPathForFileMacro(SmallVectorImpl<char> &Path,2104const LangOptions &LangOpts,2105const TargetInfo &TI) {2106LangOpts.remapPathPrefix(Path);2107if (LangOpts.UseTargetPathSeparator) {2108if (TI.getTriple().isOSWindows())2109llvm::sys::path::remove_dots(Path, false,2110llvm::sys::path::Style::windows_backslash);2111else2112llvm::sys::path::remove_dots(Path, false, llvm::sys::path::Style::posix);2113}2114}21152116void Preprocessor::processPathToFileName(SmallVectorImpl<char> &FileName,2117const PresumedLoc &PLoc,2118const LangOptions &LangOpts,2119const TargetInfo &TI) {2120// Try to get the last path component, failing that return the original2121// presumed location.2122StringRef PLFileName = llvm::sys::path::filename(PLoc.getFilename());2123if (PLFileName.empty())2124PLFileName = PLoc.getFilename();2125FileName.append(PLFileName.begin(), PLFileName.end());2126processPathForFileMacro(FileName, LangOpts, TI);2127}212821292130