PPMacroExpansion.cpp 76 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976
  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. #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>
  58. using namespace clang;
  59. MacroDirective *
  60. Preprocessor::getLocalMacroDirectiveHistory(const IdentifierInfo *II) const {
  61. if (!II->hadMacroDefinition())
  62. return nullptr;
  63. auto Pos = CurSubmoduleState->Macros.find(II);
  64. return Pos == CurSubmoduleState->Macros.end() ? nullptr
  65. : Pos->second.getLatest();
  66. }
  67. void Preprocessor::appendMacroDirective(IdentifierInfo *II, MacroDirective *MD){
  68. assert(MD && "MacroDirective should be non-zero!");
  69. assert(!MD->getPrevious() && "Already attached to a MacroDirective history.");
  70. MacroState &StoredMD = CurSubmoduleState->Macros[II];
  71. auto *OldMD = StoredMD.getLatest();
  72. MD->setPrevious(OldMD);
  73. StoredMD.setLatest(MD);
  74. StoredMD.overrideActiveModuleMacros(*this, II);
  75. if (needModuleMacros()) {
  76. // Track that we created a new macro directive, so we know we should
  77. // consider building a ModuleMacro for it when we get to the end of
  78. // the module.
  79. PendingModuleMacroNames.push_back(II);
  80. }
  81. // Set up the identifier as having associated macro history.
  82. II->setHasMacroDefinition(true);
  83. if (!MD->isDefined() && LeafModuleMacros.find(II) == LeafModuleMacros.end())
  84. II->setHasMacroDefinition(false);
  85. if (II->isFromAST())
  86. II->setChangedSinceDeserialization();
  87. }
  88. void Preprocessor::setLoadedMacroDirective(IdentifierInfo *II,
  89. MacroDirective *ED,
  90. MacroDirective *MD) {
  91. // Normally, when a macro is defined, it goes through appendMacroDirective()
  92. // above, which chains a macro to previous defines, undefs, etc.
  93. // However, in a pch, the whole macro history up to the end of the pch is
  94. // stored, so ASTReader goes through this function instead.
  95. // However, built-in macros are already registered in the Preprocessor
  96. // ctor, and ASTWriter stops writing the macro chain at built-in macros,
  97. // so in that case the chain from the pch needs to be spliced to the existing
  98. // built-in.
  99. assert(II && MD);
  100. MacroState &StoredMD = CurSubmoduleState->Macros[II];
  101. if (auto *OldMD = StoredMD.getLatest()) {
  102. // shouldIgnoreMacro() in ASTWriter also stops at macros from the
  103. // predefines buffer in module builds. However, in module builds, modules
  104. // are loaded completely before predefines are processed, so StoredMD
  105. // will be nullptr for them when they're loaded. StoredMD should only be
  106. // non-nullptr for builtins read from a pch file.
  107. assert(OldMD->getMacroInfo()->isBuiltinMacro() &&
  108. "only built-ins should have an entry here");
  109. assert(!OldMD->getPrevious() && "builtin should only have a single entry");
  110. ED->setPrevious(OldMD);
  111. StoredMD.setLatest(MD);
  112. } else {
  113. StoredMD = MD;
  114. }
  115. // Setup the identifier as having associated macro history.
  116. II->setHasMacroDefinition(true);
  117. if (!MD->isDefined() && LeafModuleMacros.find(II) == LeafModuleMacros.end())
  118. II->setHasMacroDefinition(false);
  119. }
  120. ModuleMacro *Preprocessor::addModuleMacro(Module *Mod, IdentifierInfo *II,
  121. MacroInfo *Macro,
  122. ArrayRef<ModuleMacro *> Overrides,
  123. bool &New) {
  124. llvm::FoldingSetNodeID ID;
  125. ModuleMacro::Profile(ID, Mod, II);
  126. void *InsertPos;
  127. if (auto *MM = ModuleMacros.FindNodeOrInsertPos(ID, InsertPos)) {
  128. New = false;
  129. return MM;
  130. }
  131. auto *MM = ModuleMacro::create(*this, Mod, II, Macro, Overrides);
  132. ModuleMacros.InsertNode(MM, InsertPos);
  133. // Each overridden macro is now overridden by one more macro.
  134. bool HidAny = false;
  135. for (auto *O : Overrides) {
  136. HidAny |= (O->NumOverriddenBy == 0);
  137. ++O->NumOverriddenBy;
  138. }
  139. // If we were the first overrider for any macro, it's no longer a leaf.
  140. auto &LeafMacros = LeafModuleMacros[II];
  141. if (HidAny) {
  142. llvm::erase_if(LeafMacros,
  143. [](ModuleMacro *MM) { return MM->NumOverriddenBy != 0; });
  144. }
  145. // The new macro is always a leaf macro.
  146. LeafMacros.push_back(MM);
  147. // The identifier now has defined macros (that may or may not be visible).
  148. II->setHasMacroDefinition(true);
  149. New = true;
  150. return MM;
  151. }
  152. ModuleMacro *Preprocessor::getModuleMacro(Module *Mod,
  153. const IdentifierInfo *II) {
  154. llvm::FoldingSetNodeID ID;
  155. ModuleMacro::Profile(ID, Mod, II);
  156. void *InsertPos;
  157. return ModuleMacros.FindNodeOrInsertPos(ID, InsertPos);
  158. }
  159. void Preprocessor::updateModuleMacroInfo(const IdentifierInfo *II,
  160. ModuleMacroInfo &Info) {
  161. assert(Info.ActiveModuleMacrosGeneration !=
  162. CurSubmoduleState->VisibleModules.getGeneration() &&
  163. "don't need to update this macro name info");
  164. Info.ActiveModuleMacrosGeneration =
  165. CurSubmoduleState->VisibleModules.getGeneration();
  166. auto Leaf = LeafModuleMacros.find(II);
  167. if (Leaf == LeafModuleMacros.end()) {
  168. // No imported macros at all: nothing to do.
  169. return;
  170. }
  171. Info.ActiveModuleMacros.clear();
  172. // Every macro that's locally overridden is overridden by a visible macro.
  173. llvm::DenseMap<ModuleMacro *, int> NumHiddenOverrides;
  174. for (auto *O : Info.OverriddenMacros)
  175. NumHiddenOverrides[O] = -1;
  176. // Collect all macros that are not overridden by a visible macro.
  177. llvm::SmallVector<ModuleMacro *, 16> Worklist;
  178. for (auto *LeafMM : Leaf->second) {
  179. assert(LeafMM->getNumOverridingMacros() == 0 && "leaf macro overridden");
  180. if (NumHiddenOverrides.lookup(LeafMM) == 0)
  181. Worklist.push_back(LeafMM);
  182. }
  183. while (!Worklist.empty()) {
  184. auto *MM = Worklist.pop_back_val();
  185. if (CurSubmoduleState->VisibleModules.isVisible(MM->getOwningModule())) {
  186. // We only care about collecting definitions; undefinitions only act
  187. // to override other definitions.
  188. if (MM->getMacroInfo())
  189. Info.ActiveModuleMacros.push_back(MM);
  190. } else {
  191. for (auto *O : MM->overrides())
  192. if ((unsigned)++NumHiddenOverrides[O] == O->getNumOverridingMacros())
  193. Worklist.push_back(O);
  194. }
  195. }
  196. // Our reverse postorder walk found the macros in reverse order.
  197. std::reverse(Info.ActiveModuleMacros.begin(), Info.ActiveModuleMacros.end());
  198. // Determine whether the macro name is ambiguous.
  199. MacroInfo *MI = nullptr;
  200. bool IsSystemMacro = true;
  201. bool IsAmbiguous = false;
  202. if (auto *MD = Info.MD) {
  203. while (MD && isa<VisibilityMacroDirective>(MD))
  204. MD = MD->getPrevious();
  205. if (auto *DMD = dyn_cast_or_null<DefMacroDirective>(MD)) {
  206. MI = DMD->getInfo();
  207. IsSystemMacro &= SourceMgr.isInSystemHeader(DMD->getLocation());
  208. }
  209. }
  210. for (auto *Active : Info.ActiveModuleMacros) {
  211. auto *NewMI = Active->getMacroInfo();
  212. // Before marking the macro as ambiguous, check if this is a case where
  213. // both macros are in system headers. If so, we trust that the system
  214. // did not get it wrong. This also handles cases where Clang's own
  215. // headers have a different spelling of certain system macros:
  216. // #define LONG_MAX __LONG_MAX__ (clang's limits.h)
  217. // #define LONG_MAX 0x7fffffffffffffffL (system's limits.h)
  218. //
  219. // FIXME: Remove the defined-in-system-headers check. clang's limits.h
  220. // overrides the system limits.h's macros, so there's no conflict here.
  221. if (MI && NewMI != MI &&
  222. !MI->isIdenticalTo(*NewMI, *this, /*Syntactically=*/true))
  223. IsAmbiguous = true;
  224. IsSystemMacro &= Active->getOwningModule()->IsSystem ||
  225. SourceMgr.isInSystemHeader(NewMI->getDefinitionLoc());
  226. MI = NewMI;
  227. }
  228. Info.IsAmbiguous = IsAmbiguous && !IsSystemMacro;
  229. }
  230. void Preprocessor::dumpMacroInfo(const IdentifierInfo *II) {
  231. ArrayRef<ModuleMacro*> Leaf;
  232. auto LeafIt = LeafModuleMacros.find(II);
  233. if (LeafIt != LeafModuleMacros.end())
  234. Leaf = LeafIt->second;
  235. const MacroState *State = nullptr;
  236. auto Pos = CurSubmoduleState->Macros.find(II);
  237. if (Pos != CurSubmoduleState->Macros.end())
  238. State = &Pos->second;
  239. llvm::errs() << "MacroState " << State << " " << II->getNameStart();
  240. if (State && State->isAmbiguous(*this, II))
  241. llvm::errs() << " ambiguous";
  242. if (State && !State->getOverriddenMacros().empty()) {
  243. llvm::errs() << " overrides";
  244. for (auto *O : State->getOverriddenMacros())
  245. llvm::errs() << " " << O->getOwningModule()->getFullModuleName();
  246. }
  247. llvm::errs() << "\n";
  248. // Dump local macro directives.
  249. for (auto *MD = State ? State->getLatest() : nullptr; MD;
  250. MD = MD->getPrevious()) {
  251. llvm::errs() << " ";
  252. MD->dump();
  253. }
  254. // Dump module macros.
  255. llvm::DenseSet<ModuleMacro*> Active;
  256. for (auto *MM :
  257. State ? State->getActiveModuleMacros(*this, II) : std::nullopt)
  258. Active.insert(MM);
  259. llvm::DenseSet<ModuleMacro*> Visited;
  260. llvm::SmallVector<ModuleMacro *, 16> Worklist(Leaf.begin(), Leaf.end());
  261. while (!Worklist.empty()) {
  262. auto *MM = Worklist.pop_back_val();
  263. llvm::errs() << " ModuleMacro " << MM << " "
  264. << MM->getOwningModule()->getFullModuleName();
  265. if (!MM->getMacroInfo())
  266. llvm::errs() << " undef";
  267. if (Active.count(MM))
  268. llvm::errs() << " active";
  269. else if (!CurSubmoduleState->VisibleModules.isVisible(
  270. MM->getOwningModule()))
  271. llvm::errs() << " hidden";
  272. else if (MM->getMacroInfo())
  273. llvm::errs() << " overridden";
  274. if (!MM->overrides().empty()) {
  275. llvm::errs() << " overrides";
  276. for (auto *O : MM->overrides()) {
  277. llvm::errs() << " " << O->getOwningModule()->getFullModuleName();
  278. if (Visited.insert(O).second)
  279. Worklist.push_back(O);
  280. }
  281. }
  282. llvm::errs() << "\n";
  283. if (auto *MI = MM->getMacroInfo()) {
  284. llvm::errs() << " ";
  285. MI->dump();
  286. llvm::errs() << "\n";
  287. }
  288. }
  289. }
  290. /// RegisterBuiltinMacro - Register the specified identifier in the identifier
  291. /// table and mark it as a builtin macro to be expanded.
  292. static IdentifierInfo *RegisterBuiltinMacro(Preprocessor &PP, const char *Name){
  293. // Get the identifier.
  294. IdentifierInfo *Id = PP.getIdentifierInfo(Name);
  295. // Mark it as being a macro that is builtin.
  296. MacroInfo *MI = PP.AllocateMacroInfo(SourceLocation());
  297. MI->setIsBuiltinMacro();
  298. PP.appendDefMacroDirective(Id, MI);
  299. return Id;
  300. }
  301. /// RegisterBuiltinMacros - Register builtin macros, such as __LINE__ with the
  302. /// identifier table.
  303. void Preprocessor::RegisterBuiltinMacros() {
  304. Ident__LINE__ = RegisterBuiltinMacro(*this, "__LINE__");
  305. Ident__FILE__ = RegisterBuiltinMacro(*this, "__FILE__");
  306. Ident__DATE__ = RegisterBuiltinMacro(*this, "__DATE__");
  307. Ident__TIME__ = RegisterBuiltinMacro(*this, "__TIME__");
  308. Ident__COUNTER__ = RegisterBuiltinMacro(*this, "__COUNTER__");
  309. Ident_Pragma = RegisterBuiltinMacro(*this, "_Pragma");
  310. Ident__FLT_EVAL_METHOD__ = RegisterBuiltinMacro(*this, "__FLT_EVAL_METHOD__");
  311. // C++ Standing Document Extensions.
  312. if (getLangOpts().CPlusPlus)
  313. Ident__has_cpp_attribute =
  314. RegisterBuiltinMacro(*this, "__has_cpp_attribute");
  315. else
  316. Ident__has_cpp_attribute = nullptr;
  317. // GCC Extensions.
  318. Ident__BASE_FILE__ = RegisterBuiltinMacro(*this, "__BASE_FILE__");
  319. Ident__INCLUDE_LEVEL__ = RegisterBuiltinMacro(*this, "__INCLUDE_LEVEL__");
  320. Ident__TIMESTAMP__ = RegisterBuiltinMacro(*this, "__TIMESTAMP__");
  321. // Microsoft Extensions.
  322. if (getLangOpts().MicrosoftExt) {
  323. Ident__identifier = RegisterBuiltinMacro(*this, "__identifier");
  324. Ident__pragma = RegisterBuiltinMacro(*this, "__pragma");
  325. } else {
  326. Ident__identifier = nullptr;
  327. Ident__pragma = nullptr;
  328. }
  329. // Clang Extensions.
  330. Ident__FILE_NAME__ = RegisterBuiltinMacro(*this, "__FILE_NAME__");
  331. Ident__has_feature = RegisterBuiltinMacro(*this, "__has_feature");
  332. Ident__has_extension = RegisterBuiltinMacro(*this, "__has_extension");
  333. Ident__has_builtin = RegisterBuiltinMacro(*this, "__has_builtin");
  334. Ident__has_constexpr_builtin =
  335. RegisterBuiltinMacro(*this, "__has_constexpr_builtin");
  336. Ident__has_attribute = RegisterBuiltinMacro(*this, "__has_attribute");
  337. if (!getLangOpts().CPlusPlus)
  338. Ident__has_c_attribute = RegisterBuiltinMacro(*this, "__has_c_attribute");
  339. else
  340. Ident__has_c_attribute = nullptr;
  341. Ident__has_declspec = RegisterBuiltinMacro(*this, "__has_declspec_attribute");
  342. Ident__has_include = RegisterBuiltinMacro(*this, "__has_include");
  343. Ident__has_include_next = RegisterBuiltinMacro(*this, "__has_include_next");
  344. Ident__has_warning = RegisterBuiltinMacro(*this, "__has_warning");
  345. Ident__is_identifier = RegisterBuiltinMacro(*this, "__is_identifier");
  346. Ident__is_target_arch = RegisterBuiltinMacro(*this, "__is_target_arch");
  347. Ident__is_target_vendor = RegisterBuiltinMacro(*this, "__is_target_vendor");
  348. Ident__is_target_os = RegisterBuiltinMacro(*this, "__is_target_os");
  349. Ident__is_target_environment =
  350. RegisterBuiltinMacro(*this, "__is_target_environment");
  351. Ident__is_target_variant_os =
  352. RegisterBuiltinMacro(*this, "__is_target_variant_os");
  353. Ident__is_target_variant_environment =
  354. RegisterBuiltinMacro(*this, "__is_target_variant_environment");
  355. // Modules.
  356. Ident__building_module = RegisterBuiltinMacro(*this, "__building_module");
  357. if (!getLangOpts().CurrentModule.empty())
  358. Ident__MODULE__ = RegisterBuiltinMacro(*this, "__MODULE__");
  359. else
  360. Ident__MODULE__ = nullptr;
  361. }
  362. /// isTrivialSingleTokenExpansion - Return true if MI, which has a single token
  363. /// in its expansion, currently expands to that token literally.
  364. static bool isTrivialSingleTokenExpansion(const MacroInfo *MI,
  365. const IdentifierInfo *MacroIdent,
  366. Preprocessor &PP) {
  367. IdentifierInfo *II = MI->getReplacementToken(0).getIdentifierInfo();
  368. // If the token isn't an identifier, it's always literally expanded.
  369. if (!II) return true;
  370. // If the information about this identifier is out of date, update it from
  371. // the external source.
  372. if (II->isOutOfDate())
  373. PP.getExternalSource()->updateOutOfDateIdentifier(*II);
  374. // If the identifier is a macro, and if that macro is enabled, it may be
  375. // expanded so it's not a trivial expansion.
  376. if (auto *ExpansionMI = PP.getMacroInfo(II))
  377. if (ExpansionMI->isEnabled() &&
  378. // Fast expanding "#define X X" is ok, because X would be disabled.
  379. II != MacroIdent)
  380. return false;
  381. // If this is an object-like macro invocation, it is safe to trivially expand
  382. // it.
  383. if (MI->isObjectLike()) return true;
  384. // If this is a function-like macro invocation, it's safe to trivially expand
  385. // as long as the identifier is not a macro argument.
  386. return !llvm::is_contained(MI->params(), II);
  387. }
  388. /// isNextPPTokenLParen - Determine whether the next preprocessor token to be
  389. /// lexed is a '('. If so, consume the token and return true, if not, this
  390. /// method should have no observable side-effect on the lexed tokens.
  391. bool Preprocessor::isNextPPTokenLParen() {
  392. // Do some quick tests for rejection cases.
  393. unsigned Val;
  394. if (CurLexer)
  395. Val = CurLexer->isNextPPTokenLParen();
  396. else
  397. Val = CurTokenLexer->isNextTokenLParen();
  398. if (Val == 2) {
  399. // We have run off the end. If it's a source file we don't
  400. // examine enclosing ones (C99 5.1.1.2p4). Otherwise walk up the
  401. // macro stack.
  402. if (CurPPLexer)
  403. return false;
  404. for (const IncludeStackInfo &Entry : llvm::reverse(IncludeMacroStack)) {
  405. if (Entry.TheLexer)
  406. Val = Entry.TheLexer->isNextPPTokenLParen();
  407. else
  408. Val = Entry.TheTokenLexer->isNextTokenLParen();
  409. if (Val != 2)
  410. break;
  411. // Ran off the end of a source file?
  412. if (Entry.ThePPLexer)
  413. return false;
  414. }
  415. }
  416. // Okay, if we know that the token is a '(', lex it and return. Otherwise we
  417. // have found something that isn't a '(' or we found the end of the
  418. // translation unit. In either case, return false.
  419. return Val == 1;
  420. }
  421. /// HandleMacroExpandedIdentifier - If an identifier token is read that is to be
  422. /// expanded as a macro, handle it and return the next token as 'Identifier'.
  423. bool Preprocessor::HandleMacroExpandedIdentifier(Token &Identifier,
  424. const MacroDefinition &M) {
  425. emitMacroExpansionWarnings(Identifier);
  426. MacroInfo *MI = M.getMacroInfo();
  427. // If this is a macro expansion in the "#if !defined(x)" line for the file,
  428. // then the macro could expand to different things in other contexts, we need
  429. // to disable the optimization in this case.
  430. if (CurPPLexer) CurPPLexer->MIOpt.ExpandedMacro();
  431. // If this is a builtin macro, like __LINE__ or _Pragma, handle it specially.
  432. if (MI->isBuiltinMacro()) {
  433. if (Callbacks)
  434. Callbacks->MacroExpands(Identifier, M, Identifier.getLocation(),
  435. /*Args=*/nullptr);
  436. ExpandBuiltinMacro(Identifier);
  437. return true;
  438. }
  439. /// Args - If this is a function-like macro expansion, this contains,
  440. /// for each macro argument, the list of tokens that were provided to the
  441. /// invocation.
  442. MacroArgs *Args = nullptr;
  443. // Remember where the end of the expansion occurred. For an object-like
  444. // macro, this is the identifier. For a function-like macro, this is the ')'.
  445. SourceLocation ExpansionEnd = Identifier.getLocation();
  446. // If this is a function-like macro, read the arguments.
  447. if (MI->isFunctionLike()) {
  448. // Remember that we are now parsing the arguments to a macro invocation.
  449. // Preprocessor directives used inside macro arguments are not portable, and
  450. // this enables the warning.
  451. InMacroArgs = true;
  452. ArgMacro = &Identifier;
  453. Args = ReadMacroCallArgumentList(Identifier, MI, ExpansionEnd);
  454. // Finished parsing args.
  455. InMacroArgs = false;
  456. ArgMacro = nullptr;
  457. // If there was an error parsing the arguments, bail out.
  458. if (!Args) return true;
  459. ++NumFnMacroExpanded;
  460. } else {
  461. ++NumMacroExpanded;
  462. }
  463. // Notice that this macro has been used.
  464. markMacroAsUsed(MI);
  465. // Remember where the token is expanded.
  466. SourceLocation ExpandLoc = Identifier.getLocation();
  467. SourceRange ExpansionRange(ExpandLoc, ExpansionEnd);
  468. if (Callbacks) {
  469. if (InMacroArgs) {
  470. // We can have macro expansion inside a conditional directive while
  471. // reading the function macro arguments. To ensure, in that case, that
  472. // MacroExpands callbacks still happen in source order, queue this
  473. // callback to have it happen after the function macro callback.
  474. DelayedMacroExpandsCallbacks.push_back(
  475. MacroExpandsInfo(Identifier, M, ExpansionRange));
  476. } else {
  477. Callbacks->MacroExpands(Identifier, M, ExpansionRange, Args);
  478. if (!DelayedMacroExpandsCallbacks.empty()) {
  479. for (const MacroExpandsInfo &Info : DelayedMacroExpandsCallbacks) {
  480. // FIXME: We lose macro args info with delayed callback.
  481. Callbacks->MacroExpands(Info.Tok, Info.MD, Info.Range,
  482. /*Args=*/nullptr);
  483. }
  484. DelayedMacroExpandsCallbacks.clear();
  485. }
  486. }
  487. }
  488. // If the macro definition is ambiguous, complain.
  489. if (M.isAmbiguous()) {
  490. Diag(Identifier, diag::warn_pp_ambiguous_macro)
  491. << Identifier.getIdentifierInfo();
  492. Diag(MI->getDefinitionLoc(), diag::note_pp_ambiguous_macro_chosen)
  493. << Identifier.getIdentifierInfo();
  494. M.forAllDefinitions([&](const MacroInfo *OtherMI) {
  495. if (OtherMI != MI)
  496. Diag(OtherMI->getDefinitionLoc(), diag::note_pp_ambiguous_macro_other)
  497. << Identifier.getIdentifierInfo();
  498. });
  499. }
  500. // If we started lexing a macro, enter the macro expansion body.
  501. // If this macro expands to no tokens, don't bother to push it onto the
  502. // expansion stack, only to take it right back off.
  503. if (MI->getNumTokens() == 0) {
  504. // No need for arg info.
  505. if (Args) Args->destroy(*this);
  506. // Propagate whitespace info as if we had pushed, then popped,
  507. // a macro context.
  508. Identifier.setFlag(Token::LeadingEmptyMacro);
  509. PropagateLineStartLeadingSpaceInfo(Identifier);
  510. ++NumFastMacroExpanded;
  511. return false;
  512. } else if (MI->getNumTokens() == 1 &&
  513. isTrivialSingleTokenExpansion(MI, Identifier.getIdentifierInfo(),
  514. *this)) {
  515. // Otherwise, if this macro expands into a single trivially-expanded
  516. // token: expand it now. This handles common cases like
  517. // "#define VAL 42".
  518. // No need for arg info.
  519. if (Args) Args->destroy(*this);
  520. // Propagate the isAtStartOfLine/hasLeadingSpace markers of the macro
  521. // identifier to the expanded token.
  522. bool isAtStartOfLine = Identifier.isAtStartOfLine();
  523. bool hasLeadingSpace = Identifier.hasLeadingSpace();
  524. // Replace the result token.
  525. Identifier = MI->getReplacementToken(0);
  526. // Restore the StartOfLine/LeadingSpace markers.
  527. Identifier.setFlagValue(Token::StartOfLine , isAtStartOfLine);
  528. Identifier.setFlagValue(Token::LeadingSpace, hasLeadingSpace);
  529. // Update the tokens location to include both its expansion and physical
  530. // locations.
  531. SourceLocation Loc =
  532. SourceMgr.createExpansionLoc(Identifier.getLocation(), ExpandLoc,
  533. ExpansionEnd,Identifier.getLength());
  534. Identifier.setLocation(Loc);
  535. // If this is a disabled macro or #define X X, we must mark the result as
  536. // unexpandable.
  537. if (IdentifierInfo *NewII = Identifier.getIdentifierInfo()) {
  538. if (MacroInfo *NewMI = getMacroInfo(NewII))
  539. if (!NewMI->isEnabled() || NewMI == MI) {
  540. Identifier.setFlag(Token::DisableExpand);
  541. // Don't warn for "#define X X" like "#define bool bool" from
  542. // stdbool.h.
  543. if (NewMI != MI || MI->isFunctionLike())
  544. Diag(Identifier, diag::pp_disabled_macro_expansion);
  545. }
  546. }
  547. // Since this is not an identifier token, it can't be macro expanded, so
  548. // we're done.
  549. ++NumFastMacroExpanded;
  550. return true;
  551. }
  552. // Start expanding the macro.
  553. EnterMacro(Identifier, ExpansionEnd, MI, Args);
  554. return false;
  555. }
  556. enum Bracket {
  557. Brace,
  558. Paren
  559. };
  560. /// CheckMatchedBrackets - Returns true if the braces and parentheses in the
  561. /// token vector are properly nested.
  562. static bool CheckMatchedBrackets(const SmallVectorImpl<Token> &Tokens) {
  563. SmallVector<Bracket, 8> Brackets;
  564. for (SmallVectorImpl<Token>::const_iterator I = Tokens.begin(),
  565. E = Tokens.end();
  566. I != E; ++I) {
  567. if (I->is(tok::l_paren)) {
  568. Brackets.push_back(Paren);
  569. } else if (I->is(tok::r_paren)) {
  570. if (Brackets.empty() || Brackets.back() == Brace)
  571. return false;
  572. Brackets.pop_back();
  573. } else if (I->is(tok::l_brace)) {
  574. Brackets.push_back(Brace);
  575. } else if (I->is(tok::r_brace)) {
  576. if (Brackets.empty() || Brackets.back() == Paren)
  577. return false;
  578. Brackets.pop_back();
  579. }
  580. }
  581. return Brackets.empty();
  582. }
  583. /// GenerateNewArgTokens - Returns true if OldTokens can be converted to a new
  584. /// vector of tokens in NewTokens. The new number of arguments will be placed
  585. /// in NumArgs and the ranges which need to surrounded in parentheses will be
  586. /// in ParenHints.
  587. /// Returns false if the token stream cannot be changed. If this is because
  588. /// of an initializer list starting a macro argument, the range of those
  589. /// initializer lists will be place in InitLists.
  590. static bool GenerateNewArgTokens(Preprocessor &PP,
  591. SmallVectorImpl<Token> &OldTokens,
  592. SmallVectorImpl<Token> &NewTokens,
  593. unsigned &NumArgs,
  594. SmallVectorImpl<SourceRange> &ParenHints,
  595. SmallVectorImpl<SourceRange> &InitLists) {
  596. if (!CheckMatchedBrackets(OldTokens))
  597. return false;
  598. // Once it is known that the brackets are matched, only a simple count of the
  599. // braces is needed.
  600. unsigned Braces = 0;
  601. // First token of a new macro argument.
  602. SmallVectorImpl<Token>::iterator ArgStartIterator = OldTokens.begin();
  603. // First closing brace in a new macro argument. Used to generate
  604. // SourceRanges for InitLists.
  605. SmallVectorImpl<Token>::iterator ClosingBrace = OldTokens.end();
  606. NumArgs = 0;
  607. Token TempToken;
  608. // Set to true when a macro separator token is found inside a braced list.
  609. // If true, the fixed argument spans multiple old arguments and ParenHints
  610. // will be updated.
  611. bool FoundSeparatorToken = false;
  612. for (SmallVectorImpl<Token>::iterator I = OldTokens.begin(),
  613. E = OldTokens.end();
  614. I != E; ++I) {
  615. if (I->is(tok::l_brace)) {
  616. ++Braces;
  617. } else if (I->is(tok::r_brace)) {
  618. --Braces;
  619. if (Braces == 0 && ClosingBrace == E && FoundSeparatorToken)
  620. ClosingBrace = I;
  621. } else if (I->is(tok::eof)) {
  622. // EOF token is used to separate macro arguments
  623. if (Braces != 0) {
  624. // Assume comma separator is actually braced list separator and change
  625. // it back to a comma.
  626. FoundSeparatorToken = true;
  627. I->setKind(tok::comma);
  628. I->setLength(1);
  629. } else { // Braces == 0
  630. // Separator token still separates arguments.
  631. ++NumArgs;
  632. // If the argument starts with a brace, it can't be fixed with
  633. // parentheses. A different diagnostic will be given.
  634. if (FoundSeparatorToken && ArgStartIterator->is(tok::l_brace)) {
  635. InitLists.push_back(
  636. SourceRange(ArgStartIterator->getLocation(),
  637. PP.getLocForEndOfToken(ClosingBrace->getLocation())));
  638. ClosingBrace = E;
  639. }
  640. // Add left paren
  641. if (FoundSeparatorToken) {
  642. TempToken.startToken();
  643. TempToken.setKind(tok::l_paren);
  644. TempToken.setLocation(ArgStartIterator->getLocation());
  645. TempToken.setLength(0);
  646. NewTokens.push_back(TempToken);
  647. }
  648. // Copy over argument tokens
  649. NewTokens.insert(NewTokens.end(), ArgStartIterator, I);
  650. // Add right paren and store the paren locations in ParenHints
  651. if (FoundSeparatorToken) {
  652. SourceLocation Loc = PP.getLocForEndOfToken((I - 1)->getLocation());
  653. TempToken.startToken();
  654. TempToken.setKind(tok::r_paren);
  655. TempToken.setLocation(Loc);
  656. TempToken.setLength(0);
  657. NewTokens.push_back(TempToken);
  658. ParenHints.push_back(SourceRange(ArgStartIterator->getLocation(),
  659. Loc));
  660. }
  661. // Copy separator token
  662. NewTokens.push_back(*I);
  663. // Reset values
  664. ArgStartIterator = I + 1;
  665. FoundSeparatorToken = false;
  666. }
  667. }
  668. }
  669. return !ParenHints.empty() && InitLists.empty();
  670. }
  671. /// ReadFunctionLikeMacroArgs - After reading "MACRO" and knowing that the next
  672. /// token is the '(' of the macro, this method is invoked to read all of the
  673. /// actual arguments specified for the macro invocation. This returns null on
  674. /// error.
  675. MacroArgs *Preprocessor::ReadMacroCallArgumentList(Token &MacroName,
  676. MacroInfo *MI,
  677. SourceLocation &MacroEnd) {
  678. // The number of fixed arguments to parse.
  679. unsigned NumFixedArgsLeft = MI->getNumParams();
  680. bool isVariadic = MI->isVariadic();
  681. // Outer loop, while there are more arguments, keep reading them.
  682. Token Tok;
  683. // Read arguments as unexpanded tokens. This avoids issues, e.g., where
  684. // an argument value in a macro could expand to ',' or '(' or ')'.
  685. LexUnexpandedToken(Tok);
  686. assert(Tok.is(tok::l_paren) && "Error computing l-paren-ness?");
  687. // ArgTokens - Build up a list of tokens that make up each argument. Each
  688. // argument is separated by an EOF token. Use a SmallVector so we can avoid
  689. // heap allocations in the common case.
  690. SmallVector<Token, 64> ArgTokens;
  691. bool ContainsCodeCompletionTok = false;
  692. bool FoundElidedComma = false;
  693. SourceLocation TooManyArgsLoc;
  694. unsigned NumActuals = 0;
  695. while (Tok.isNot(tok::r_paren)) {
  696. if (ContainsCodeCompletionTok && Tok.isOneOf(tok::eof, tok::eod))
  697. break;
  698. assert(Tok.isOneOf(tok::l_paren, tok::comma) &&
  699. "only expect argument separators here");
  700. size_t ArgTokenStart = ArgTokens.size();
  701. SourceLocation ArgStartLoc = Tok.getLocation();
  702. // C99 6.10.3p11: Keep track of the number of l_parens we have seen. Note
  703. // that we already consumed the first one.
  704. unsigned NumParens = 0;
  705. while (true) {
  706. // Read arguments as unexpanded tokens. This avoids issues, e.g., where
  707. // an argument value in a macro could expand to ',' or '(' or ')'.
  708. LexUnexpandedToken(Tok);
  709. if (Tok.isOneOf(tok::eof, tok::eod)) { // "#if f(<eof>" & "#if f(\n"
  710. if (!ContainsCodeCompletionTok) {
  711. Diag(MacroName, diag::err_unterm_macro_invoc);
  712. Diag(MI->getDefinitionLoc(), diag::note_macro_here)
  713. << MacroName.getIdentifierInfo();
  714. // Do not lose the EOF/EOD. Return it to the client.
  715. MacroName = Tok;
  716. return nullptr;
  717. }
  718. // Do not lose the EOF/EOD.
  719. auto Toks = std::make_unique<Token[]>(1);
  720. Toks[0] = Tok;
  721. EnterTokenStream(std::move(Toks), 1, true, /*IsReinject*/ false);
  722. break;
  723. } else if (Tok.is(tok::r_paren)) {
  724. // If we found the ) token, the macro arg list is done.
  725. if (NumParens-- == 0) {
  726. MacroEnd = Tok.getLocation();
  727. if (!ArgTokens.empty() &&
  728. ArgTokens.back().commaAfterElided()) {
  729. FoundElidedComma = true;
  730. }
  731. break;
  732. }
  733. } else if (Tok.is(tok::l_paren)) {
  734. ++NumParens;
  735. } else if (Tok.is(tok::comma)) {
  736. // In Microsoft-compatibility mode, single commas from nested macro
  737. // expansions should not be considered as argument separators. We test
  738. // for this with the IgnoredComma token flag.
  739. if (Tok.getFlags() & Token::IgnoredComma) {
  740. // However, in MSVC's preprocessor, subsequent expansions do treat
  741. // these commas as argument separators. This leads to a common
  742. // workaround used in macros that need to work in both MSVC and
  743. // compliant preprocessors. Therefore, the IgnoredComma flag can only
  744. // apply once to any given token.
  745. Tok.clearFlag(Token::IgnoredComma);
  746. } else if (NumParens == 0) {
  747. // Comma ends this argument if there are more fixed arguments
  748. // expected. However, if this is a variadic macro, and this is part of
  749. // the variadic part, then the comma is just an argument token.
  750. if (!isVariadic)
  751. break;
  752. if (NumFixedArgsLeft > 1)
  753. break;
  754. }
  755. } else if (Tok.is(tok::comment) && !KeepMacroComments) {
  756. // If this is a comment token in the argument list and we're just in
  757. // -C mode (not -CC mode), discard the comment.
  758. continue;
  759. } else if (!Tok.isAnnotation() && Tok.getIdentifierInfo() != nullptr) {
  760. // Reading macro arguments can cause macros that we are currently
  761. // expanding from to be popped off the expansion stack. Doing so causes
  762. // them to be reenabled for expansion. Here we record whether any
  763. // identifiers we lex as macro arguments correspond to disabled macros.
  764. // If so, we mark the token as noexpand. This is a subtle aspect of
  765. // C99 6.10.3.4p2.
  766. if (MacroInfo *MI = getMacroInfo(Tok.getIdentifierInfo()))
  767. if (!MI->isEnabled())
  768. Tok.setFlag(Token::DisableExpand);
  769. } else if (Tok.is(tok::code_completion)) {
  770. ContainsCodeCompletionTok = true;
  771. if (CodeComplete)
  772. CodeComplete->CodeCompleteMacroArgument(MacroName.getIdentifierInfo(),
  773. MI, NumActuals);
  774. // Don't mark that we reached the code-completion point because the
  775. // parser is going to handle the token and there will be another
  776. // code-completion callback.
  777. }
  778. ArgTokens.push_back(Tok);
  779. }
  780. // If this was an empty argument list foo(), don't add this as an empty
  781. // argument.
  782. if (ArgTokens.empty() && Tok.getKind() == tok::r_paren)
  783. break;
  784. // If this is not a variadic macro, and too many args were specified, emit
  785. // an error.
  786. if (!isVariadic && NumFixedArgsLeft == 0 && TooManyArgsLoc.isInvalid()) {
  787. if (ArgTokens.size() != ArgTokenStart)
  788. TooManyArgsLoc = ArgTokens[ArgTokenStart].getLocation();
  789. else
  790. TooManyArgsLoc = ArgStartLoc;
  791. }
  792. // Empty arguments are standard in C99 and C++0x, and are supported as an
  793. // extension in other modes.
  794. if (ArgTokens.size() == ArgTokenStart && !getLangOpts().C99)
  795. Diag(Tok, getLangOpts().CPlusPlus11
  796. ? diag::warn_cxx98_compat_empty_fnmacro_arg
  797. : diag::ext_empty_fnmacro_arg);
  798. // Add a marker EOF token to the end of the token list for this argument.
  799. Token EOFTok;
  800. EOFTok.startToken();
  801. EOFTok.setKind(tok::eof);
  802. EOFTok.setLocation(Tok.getLocation());
  803. EOFTok.setLength(0);
  804. ArgTokens.push_back(EOFTok);
  805. ++NumActuals;
  806. if (!ContainsCodeCompletionTok && NumFixedArgsLeft != 0)
  807. --NumFixedArgsLeft;
  808. }
  809. // Okay, we either found the r_paren. Check to see if we parsed too few
  810. // arguments.
  811. unsigned MinArgsExpected = MI->getNumParams();
  812. // If this is not a variadic macro, and too many args were specified, emit
  813. // an error.
  814. if (!isVariadic && NumActuals > MinArgsExpected &&
  815. !ContainsCodeCompletionTok) {
  816. // Emit the diagnostic at the macro name in case there is a missing ).
  817. // Emitting it at the , could be far away from the macro name.
  818. Diag(TooManyArgsLoc, diag::err_too_many_args_in_macro_invoc);
  819. Diag(MI->getDefinitionLoc(), diag::note_macro_here)
  820. << MacroName.getIdentifierInfo();
  821. // Commas from braced initializer lists will be treated as argument
  822. // separators inside macros. Attempt to correct for this with parentheses.
  823. // TODO: See if this can be generalized to angle brackets for templates
  824. // inside macro arguments.
  825. SmallVector<Token, 4> FixedArgTokens;
  826. unsigned FixedNumArgs = 0;
  827. SmallVector<SourceRange, 4> ParenHints, InitLists;
  828. if (!GenerateNewArgTokens(*this, ArgTokens, FixedArgTokens, FixedNumArgs,
  829. ParenHints, InitLists)) {
  830. if (!InitLists.empty()) {
  831. DiagnosticBuilder DB =
  832. Diag(MacroName,
  833. diag::note_init_list_at_beginning_of_macro_argument);
  834. for (SourceRange Range : InitLists)
  835. DB << Range;
  836. }
  837. return nullptr;
  838. }
  839. if (FixedNumArgs != MinArgsExpected)
  840. return nullptr;
  841. DiagnosticBuilder DB = Diag(MacroName, diag::note_suggest_parens_for_macro);
  842. for (SourceRange ParenLocation : ParenHints) {
  843. DB << FixItHint::CreateInsertion(ParenLocation.getBegin(), "(");
  844. DB << FixItHint::CreateInsertion(ParenLocation.getEnd(), ")");
  845. }
  846. ArgTokens.swap(FixedArgTokens);
  847. NumActuals = FixedNumArgs;
  848. }
  849. // See MacroArgs instance var for description of this.
  850. bool isVarargsElided = false;
  851. if (ContainsCodeCompletionTok) {
  852. // Recover from not-fully-formed macro invocation during code-completion.
  853. Token EOFTok;
  854. EOFTok.startToken();
  855. EOFTok.setKind(tok::eof);
  856. EOFTok.setLocation(Tok.getLocation());
  857. EOFTok.setLength(0);
  858. for (; NumActuals < MinArgsExpected; ++NumActuals)
  859. ArgTokens.push_back(EOFTok);
  860. }
  861. if (NumActuals < MinArgsExpected) {
  862. // There are several cases where too few arguments is ok, handle them now.
  863. if (NumActuals == 0 && MinArgsExpected == 1) {
  864. // #define A(X) or #define A(...) ---> A()
  865. // If there is exactly one argument, and that argument is missing,
  866. // then we have an empty "()" argument empty list. This is fine, even if
  867. // the macro expects one argument (the argument is just empty).
  868. isVarargsElided = MI->isVariadic();
  869. } else if ((FoundElidedComma || MI->isVariadic()) &&
  870. (NumActuals+1 == MinArgsExpected || // A(x, ...) -> A(X)
  871. (NumActuals == 0 && MinArgsExpected == 2))) {// A(x,...) -> A()
  872. // Varargs where the named vararg parameter is missing: OK as extension.
  873. // #define A(x, ...)
  874. // A("blah")
  875. //
  876. // If the macro contains the comma pasting extension, the diagnostic
  877. // is suppressed; we know we'll get another diagnostic later.
  878. if (!MI->hasCommaPasting()) {
  879. // C++20 allows this construct, but standards before C++20 and all C
  880. // standards do not allow the construct (we allow it as an extension).
  881. Diag(Tok, getLangOpts().CPlusPlus20
  882. ? diag::warn_cxx17_compat_missing_varargs_arg
  883. : diag::ext_missing_varargs_arg);
  884. Diag(MI->getDefinitionLoc(), diag::note_macro_here)
  885. << MacroName.getIdentifierInfo();
  886. }
  887. // Remember this occurred, allowing us to elide the comma when used for
  888. // cases like:
  889. // #define A(x, foo...) blah(a, ## foo)
  890. // #define B(x, ...) blah(a, ## __VA_ARGS__)
  891. // #define C(...) blah(a, ## __VA_ARGS__)
  892. // A(x) B(x) C()
  893. isVarargsElided = true;
  894. } else if (!ContainsCodeCompletionTok) {
  895. // Otherwise, emit the error.
  896. Diag(Tok, diag::err_too_few_args_in_macro_invoc);
  897. Diag(MI->getDefinitionLoc(), diag::note_macro_here)
  898. << MacroName.getIdentifierInfo();
  899. return nullptr;
  900. }
  901. // Add a marker EOF token to the end of the token list for this argument.
  902. SourceLocation EndLoc = Tok.getLocation();
  903. Tok.startToken();
  904. Tok.setKind(tok::eof);
  905. Tok.setLocation(EndLoc);
  906. Tok.setLength(0);
  907. ArgTokens.push_back(Tok);
  908. // If we expect two arguments, add both as empty.
  909. if (NumActuals == 0 && MinArgsExpected == 2)
  910. ArgTokens.push_back(Tok);
  911. } else if (NumActuals > MinArgsExpected && !MI->isVariadic() &&
  912. !ContainsCodeCompletionTok) {
  913. // Emit the diagnostic at the macro name in case there is a missing ).
  914. // Emitting it at the , could be far away from the macro name.
  915. Diag(MacroName, diag::err_too_many_args_in_macro_invoc);
  916. Diag(MI->getDefinitionLoc(), diag::note_macro_here)
  917. << MacroName.getIdentifierInfo();
  918. return nullptr;
  919. }
  920. return MacroArgs::create(MI, ArgTokens, isVarargsElided, *this);
  921. }
  922. /// Keeps macro expanded tokens for TokenLexers.
  923. //
  924. /// Works like a stack; a TokenLexer adds the macro expanded tokens that is
  925. /// going to lex in the cache and when it finishes the tokens are removed
  926. /// from the end of the cache.
  927. Token *Preprocessor::cacheMacroExpandedTokens(TokenLexer *tokLexer,
  928. ArrayRef<Token> tokens) {
  929. assert(tokLexer);
  930. if (tokens.empty())
  931. return nullptr;
  932. size_t newIndex = MacroExpandedTokens.size();
  933. bool cacheNeedsToGrow = tokens.size() >
  934. MacroExpandedTokens.capacity()-MacroExpandedTokens.size();
  935. MacroExpandedTokens.append(tokens.begin(), tokens.end());
  936. if (cacheNeedsToGrow) {
  937. // Go through all the TokenLexers whose 'Tokens' pointer points in the
  938. // buffer and update the pointers to the (potential) new buffer array.
  939. for (const auto &Lexer : MacroExpandingLexersStack) {
  940. TokenLexer *prevLexer;
  941. size_t tokIndex;
  942. std::tie(prevLexer, tokIndex) = Lexer;
  943. prevLexer->Tokens = MacroExpandedTokens.data() + tokIndex;
  944. }
  945. }
  946. MacroExpandingLexersStack.push_back(std::make_pair(tokLexer, newIndex));
  947. return MacroExpandedTokens.data() + newIndex;
  948. }
  949. void Preprocessor::removeCachedMacroExpandedTokensOfLastLexer() {
  950. assert(!MacroExpandingLexersStack.empty());
  951. size_t tokIndex = MacroExpandingLexersStack.back().second;
  952. assert(tokIndex < MacroExpandedTokens.size());
  953. // Pop the cached macro expanded tokens from the end.
  954. MacroExpandedTokens.resize(tokIndex);
  955. MacroExpandingLexersStack.pop_back();
  956. }
  957. /// ComputeDATE_TIME - Compute the current time, enter it into the specified
  958. /// scratch buffer, then return DATELoc/TIMELoc locations with the position of
  959. /// the identifier tokens inserted.
  960. static void ComputeDATE_TIME(SourceLocation &DATELoc, SourceLocation &TIMELoc,
  961. Preprocessor &PP) {
  962. time_t TT;
  963. std::tm *TM;
  964. if (PP.getPreprocessorOpts().SourceDateEpoch) {
  965. TT = *PP.getPreprocessorOpts().SourceDateEpoch;
  966. TM = std::gmtime(&TT);
  967. } else {
  968. TT = std::time(nullptr);
  969. TM = std::localtime(&TT);
  970. }
  971. static const char * const Months[] = {
  972. "Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"
  973. };
  974. {
  975. SmallString<32> TmpBuffer;
  976. llvm::raw_svector_ostream TmpStream(TmpBuffer);
  977. if (TM)
  978. TmpStream << llvm::format("\"%s %2d %4d\"", Months[TM->tm_mon],
  979. TM->tm_mday, TM->tm_year + 1900);
  980. else
  981. TmpStream << "??? ?? ????";
  982. Token TmpTok;
  983. TmpTok.startToken();
  984. PP.CreateString(TmpStream.str(), TmpTok);
  985. DATELoc = TmpTok.getLocation();
  986. }
  987. {
  988. SmallString<32> TmpBuffer;
  989. llvm::raw_svector_ostream TmpStream(TmpBuffer);
  990. if (TM)
  991. TmpStream << llvm::format("\"%02d:%02d:%02d\"", TM->tm_hour, TM->tm_min,
  992. TM->tm_sec);
  993. else
  994. TmpStream << "??:??:??";
  995. Token TmpTok;
  996. TmpTok.startToken();
  997. PP.CreateString(TmpStream.str(), TmpTok);
  998. TIMELoc = TmpTok.getLocation();
  999. }
  1000. }
  1001. /// HasFeature - Return true if we recognize and implement the feature
  1002. /// specified by the identifier as a standard language feature.
  1003. static bool HasFeature(const Preprocessor &PP, StringRef Feature) {
  1004. const LangOptions &LangOpts = PP.getLangOpts();
  1005. // Normalize the feature name, __foo__ becomes foo.
  1006. if (Feature.startswith("__") && Feature.endswith("__") && Feature.size() >= 4)
  1007. Feature = Feature.substr(2, Feature.size() - 4);
  1008. #define FEATURE(Name, Predicate) .Case(#Name, Predicate)
  1009. return llvm::StringSwitch<bool>(Feature)
  1010. #include "clang/Basic/Features.def"
  1011. .Default(false);
  1012. #undef FEATURE
  1013. }
  1014. /// HasExtension - Return true if we recognize and implement the feature
  1015. /// specified by the identifier, either as an extension or a standard language
  1016. /// feature.
  1017. static bool HasExtension(const Preprocessor &PP, StringRef Extension) {
  1018. if (HasFeature(PP, Extension))
  1019. return true;
  1020. // If the use of an extension results in an error diagnostic, extensions are
  1021. // effectively unavailable, so just return false here.
  1022. if (PP.getDiagnostics().getExtensionHandlingBehavior() >=
  1023. diag::Severity::Error)
  1024. return false;
  1025. const LangOptions &LangOpts = PP.getLangOpts();
  1026. // Normalize the extension name, __foo__ becomes foo.
  1027. if (Extension.startswith("__") && Extension.endswith("__") &&
  1028. Extension.size() >= 4)
  1029. Extension = Extension.substr(2, Extension.size() - 4);
  1030. // Because we inherit the feature list from HasFeature, this string switch
  1031. // must be less restrictive than HasFeature's.
  1032. #define EXTENSION(Name, Predicate) .Case(#Name, Predicate)
  1033. return llvm::StringSwitch<bool>(Extension)
  1034. #include "clang/Basic/Features.def"
  1035. .Default(false);
  1036. #undef EXTENSION
  1037. }
  1038. /// EvaluateHasIncludeCommon - Process a '__has_include("path")'
  1039. /// or '__has_include_next("path")' expression.
  1040. /// Returns true if successful.
  1041. static bool EvaluateHasIncludeCommon(Token &Tok, IdentifierInfo *II,
  1042. Preprocessor &PP,
  1043. ConstSearchDirIterator LookupFrom,
  1044. const FileEntry *LookupFromFile) {
  1045. // Save the location of the current token. If a '(' is later found, use
  1046. // that location. If not, use the end of this location instead.
  1047. SourceLocation LParenLoc = Tok.getLocation();
  1048. // These expressions are only allowed within a preprocessor directive.
  1049. if (!PP.isParsingIfOrElifDirective()) {
  1050. PP.Diag(LParenLoc, diag::err_pp_directive_required) << II;
  1051. // Return a valid identifier token.
  1052. assert(Tok.is(tok::identifier));
  1053. Tok.setIdentifierInfo(II);
  1054. return false;
  1055. }
  1056. // Get '('. If we don't have a '(', try to form a header-name token.
  1057. do {
  1058. if (PP.LexHeaderName(Tok))
  1059. return false;
  1060. } while (Tok.getKind() == tok::comment);
  1061. // Ensure we have a '('.
  1062. if (Tok.isNot(tok::l_paren)) {
  1063. // No '(', use end of last token.
  1064. LParenLoc = PP.getLocForEndOfToken(LParenLoc);
  1065. PP.Diag(LParenLoc, diag::err_pp_expected_after) << II << tok::l_paren;
  1066. // If the next token looks like a filename or the start of one,
  1067. // assume it is and process it as such.
  1068. if (Tok.isNot(tok::header_name))
  1069. return false;
  1070. } else {
  1071. // Save '(' location for possible missing ')' message.
  1072. LParenLoc = Tok.getLocation();
  1073. if (PP.LexHeaderName(Tok))
  1074. return false;
  1075. }
  1076. if (Tok.isNot(tok::header_name)) {
  1077. PP.Diag(Tok.getLocation(), diag::err_pp_expects_filename);
  1078. return false;
  1079. }
  1080. // Reserve a buffer to get the spelling.
  1081. SmallString<128> FilenameBuffer;
  1082. bool Invalid = false;
  1083. StringRef Filename = PP.getSpelling(Tok, FilenameBuffer, &Invalid);
  1084. if (Invalid)
  1085. return false;
  1086. SourceLocation FilenameLoc = Tok.getLocation();
  1087. // Get ')'.
  1088. PP.LexNonComment(Tok);
  1089. // Ensure we have a trailing ).
  1090. if (Tok.isNot(tok::r_paren)) {
  1091. PP.Diag(PP.getLocForEndOfToken(FilenameLoc), diag::err_pp_expected_after)
  1092. << II << tok::r_paren;
  1093. PP.Diag(LParenLoc, diag::note_matching) << tok::l_paren;
  1094. return false;
  1095. }
  1096. bool isAngled = PP.GetIncludeFilenameSpelling(Tok.getLocation(), Filename);
  1097. // If GetIncludeFilenameSpelling set the start ptr to null, there was an
  1098. // error.
  1099. if (Filename.empty())
  1100. return false;
  1101. // Search include directories.
  1102. OptionalFileEntryRef File =
  1103. PP.LookupFile(FilenameLoc, Filename, isAngled, LookupFrom, LookupFromFile,
  1104. nullptr, nullptr, nullptr, nullptr, nullptr, nullptr);
  1105. if (PPCallbacks *Callbacks = PP.getPPCallbacks()) {
  1106. SrcMgr::CharacteristicKind FileType = SrcMgr::C_User;
  1107. if (File)
  1108. FileType =
  1109. PP.getHeaderSearchInfo().getFileDirFlavor(&File->getFileEntry());
  1110. Callbacks->HasInclude(FilenameLoc, Filename, isAngled, File, FileType);
  1111. }
  1112. // Get the result value. A result of true means the file exists.
  1113. return File.has_value();
  1114. }
  1115. bool Preprocessor::EvaluateHasInclude(Token &Tok, IdentifierInfo *II) {
  1116. return EvaluateHasIncludeCommon(Tok, II, *this, nullptr, nullptr);
  1117. }
  1118. bool Preprocessor::EvaluateHasIncludeNext(Token &Tok, IdentifierInfo *II) {
  1119. ConstSearchDirIterator Lookup = nullptr;
  1120. const FileEntry *LookupFromFile;
  1121. std::tie(Lookup, LookupFromFile) = getIncludeNextStart(Tok);
  1122. return EvaluateHasIncludeCommon(Tok, II, *this, Lookup, LookupFromFile);
  1123. }
  1124. /// Process single-argument builtin feature-like macros that return
  1125. /// integer values.
  1126. static void EvaluateFeatureLikeBuiltinMacro(llvm::raw_svector_ostream& OS,
  1127. Token &Tok, IdentifierInfo *II,
  1128. Preprocessor &PP, bool ExpandArgs,
  1129. llvm::function_ref<
  1130. int(Token &Tok,
  1131. bool &HasLexedNextTok)> Op) {
  1132. // Parse the initial '('.
  1133. PP.LexUnexpandedToken(Tok);
  1134. if (Tok.isNot(tok::l_paren)) {
  1135. PP.Diag(Tok.getLocation(), diag::err_pp_expected_after) << II
  1136. << tok::l_paren;
  1137. // Provide a dummy '0' value on output stream to elide further errors.
  1138. if (!Tok.isOneOf(tok::eof, tok::eod)) {
  1139. OS << 0;
  1140. Tok.setKind(tok::numeric_constant);
  1141. }
  1142. return;
  1143. }
  1144. unsigned ParenDepth = 1;
  1145. SourceLocation LParenLoc = Tok.getLocation();
  1146. std::optional<int> Result;
  1147. Token ResultTok;
  1148. bool SuppressDiagnostic = false;
  1149. while (true) {
  1150. // Parse next token.
  1151. if (ExpandArgs)
  1152. PP.Lex(Tok);
  1153. else
  1154. PP.LexUnexpandedToken(Tok);
  1155. already_lexed:
  1156. switch (Tok.getKind()) {
  1157. case tok::eof:
  1158. case tok::eod:
  1159. // Don't provide even a dummy value if the eod or eof marker is
  1160. // reached. Simply provide a diagnostic.
  1161. PP.Diag(Tok.getLocation(), diag::err_unterm_macro_invoc);
  1162. return;
  1163. case tok::comma:
  1164. if (!SuppressDiagnostic) {
  1165. PP.Diag(Tok.getLocation(), diag::err_too_many_args_in_macro_invoc);
  1166. SuppressDiagnostic = true;
  1167. }
  1168. continue;
  1169. case tok::l_paren:
  1170. ++ParenDepth;
  1171. if (Result)
  1172. break;
  1173. if (!SuppressDiagnostic) {
  1174. PP.Diag(Tok.getLocation(), diag::err_pp_nested_paren) << II;
  1175. SuppressDiagnostic = true;
  1176. }
  1177. continue;
  1178. case tok::r_paren:
  1179. if (--ParenDepth > 0)
  1180. continue;
  1181. // The last ')' has been reached; return the value if one found or
  1182. // a diagnostic and a dummy value.
  1183. if (Result) {
  1184. OS << *Result;
  1185. // For strict conformance to __has_cpp_attribute rules, use 'L'
  1186. // suffix for dated literals.
  1187. if (*Result > 1)
  1188. OS << 'L';
  1189. } else {
  1190. OS << 0;
  1191. if (!SuppressDiagnostic)
  1192. PP.Diag(Tok.getLocation(), diag::err_too_few_args_in_macro_invoc);
  1193. }
  1194. Tok.setKind(tok::numeric_constant);
  1195. return;
  1196. default: {
  1197. // Parse the macro argument, if one not found so far.
  1198. if (Result)
  1199. break;
  1200. bool HasLexedNextToken = false;
  1201. Result = Op(Tok, HasLexedNextToken);
  1202. ResultTok = Tok;
  1203. if (HasLexedNextToken)
  1204. goto already_lexed;
  1205. continue;
  1206. }
  1207. }
  1208. // Diagnose missing ')'.
  1209. if (!SuppressDiagnostic) {
  1210. if (auto Diag = PP.Diag(Tok.getLocation(), diag::err_pp_expected_after)) {
  1211. if (IdentifierInfo *LastII = ResultTok.getIdentifierInfo())
  1212. Diag << LastII;
  1213. else
  1214. Diag << ResultTok.getKind();
  1215. Diag << tok::r_paren << ResultTok.getLocation();
  1216. }
  1217. PP.Diag(LParenLoc, diag::note_matching) << tok::l_paren;
  1218. SuppressDiagnostic = true;
  1219. }
  1220. }
  1221. }
  1222. /// Helper function to return the IdentifierInfo structure of a Token
  1223. /// or generate a diagnostic if none available.
  1224. static IdentifierInfo *ExpectFeatureIdentifierInfo(Token &Tok,
  1225. Preprocessor &PP,
  1226. signed DiagID) {
  1227. IdentifierInfo *II;
  1228. if (!Tok.isAnnotation() && (II = Tok.getIdentifierInfo()))
  1229. return II;
  1230. PP.Diag(Tok.getLocation(), DiagID);
  1231. return nullptr;
  1232. }
  1233. /// Implements the __is_target_arch builtin macro.
  1234. static bool isTargetArch(const TargetInfo &TI, const IdentifierInfo *II) {
  1235. std::string ArchName = II->getName().lower() + "--";
  1236. llvm::Triple Arch(ArchName);
  1237. const llvm::Triple &TT = TI.getTriple();
  1238. if (TT.isThumb()) {
  1239. // arm matches thumb or thumbv7. armv7 matches thumbv7.
  1240. if ((Arch.getSubArch() == llvm::Triple::NoSubArch ||
  1241. Arch.getSubArch() == TT.getSubArch()) &&
  1242. ((TT.getArch() == llvm::Triple::thumb &&
  1243. Arch.getArch() == llvm::Triple::arm) ||
  1244. (TT.getArch() == llvm::Triple::thumbeb &&
  1245. Arch.getArch() == llvm::Triple::armeb)))
  1246. return true;
  1247. }
  1248. // Check the parsed arch when it has no sub arch to allow Clang to
  1249. // match thumb to thumbv7 but to prohibit matching thumbv6 to thumbv7.
  1250. return (Arch.getSubArch() == llvm::Triple::NoSubArch ||
  1251. Arch.getSubArch() == TT.getSubArch()) &&
  1252. Arch.getArch() == TT.getArch();
  1253. }
  1254. /// Implements the __is_target_vendor builtin macro.
  1255. static bool isTargetVendor(const TargetInfo &TI, const IdentifierInfo *II) {
  1256. StringRef VendorName = TI.getTriple().getVendorName();
  1257. if (VendorName.empty())
  1258. VendorName = "unknown";
  1259. return VendorName.equals_insensitive(II->getName());
  1260. }
  1261. /// Implements the __is_target_os builtin macro.
  1262. static bool isTargetOS(const TargetInfo &TI, const IdentifierInfo *II) {
  1263. std::string OSName =
  1264. (llvm::Twine("unknown-unknown-") + II->getName().lower()).str();
  1265. llvm::Triple OS(OSName);
  1266. if (OS.getOS() == llvm::Triple::Darwin) {
  1267. // Darwin matches macos, ios, etc.
  1268. return TI.getTriple().isOSDarwin();
  1269. }
  1270. return TI.getTriple().getOS() == OS.getOS();
  1271. }
  1272. /// Implements the __is_target_environment builtin macro.
  1273. static bool isTargetEnvironment(const TargetInfo &TI,
  1274. const IdentifierInfo *II) {
  1275. std::string EnvName = (llvm::Twine("---") + II->getName().lower()).str();
  1276. llvm::Triple Env(EnvName);
  1277. // The unknown environment is matched only if
  1278. // '__is_target_environment(unknown)' is used.
  1279. if (Env.getEnvironment() == llvm::Triple::UnknownEnvironment &&
  1280. EnvName != "---unknown")
  1281. return false;
  1282. return TI.getTriple().getEnvironment() == Env.getEnvironment();
  1283. }
  1284. /// Implements the __is_target_variant_os builtin macro.
  1285. static bool isTargetVariantOS(const TargetInfo &TI, const IdentifierInfo *II) {
  1286. if (TI.getTriple().isOSDarwin()) {
  1287. const llvm::Triple *VariantTriple = TI.getDarwinTargetVariantTriple();
  1288. if (!VariantTriple)
  1289. return false;
  1290. std::string OSName =
  1291. (llvm::Twine("unknown-unknown-") + II->getName().lower()).str();
  1292. llvm::Triple OS(OSName);
  1293. if (OS.getOS() == llvm::Triple::Darwin) {
  1294. // Darwin matches macos, ios, etc.
  1295. return VariantTriple->isOSDarwin();
  1296. }
  1297. return VariantTriple->getOS() == OS.getOS();
  1298. }
  1299. return false;
  1300. }
  1301. /// Implements the __is_target_variant_environment builtin macro.
  1302. static bool isTargetVariantEnvironment(const TargetInfo &TI,
  1303. const IdentifierInfo *II) {
  1304. if (TI.getTriple().isOSDarwin()) {
  1305. const llvm::Triple *VariantTriple = TI.getDarwinTargetVariantTriple();
  1306. if (!VariantTriple)
  1307. return false;
  1308. std::string EnvName = (llvm::Twine("---") + II->getName().lower()).str();
  1309. llvm::Triple Env(EnvName);
  1310. return VariantTriple->getEnvironment() == Env.getEnvironment();
  1311. }
  1312. return false;
  1313. }
  1314. /// ExpandBuiltinMacro - If an identifier token is read that is to be expanded
  1315. /// as a builtin macro, handle it and return the next token as 'Tok'.
  1316. void Preprocessor::ExpandBuiltinMacro(Token &Tok) {
  1317. // Figure out which token this is.
  1318. IdentifierInfo *II = Tok.getIdentifierInfo();
  1319. assert(II && "Can't be a macro without id info!");
  1320. // If this is an _Pragma or Microsoft __pragma directive, expand it,
  1321. // invoke the pragma handler, then lex the token after it.
  1322. if (II == Ident_Pragma)
  1323. return Handle_Pragma(Tok);
  1324. else if (II == Ident__pragma) // in non-MS mode this is null
  1325. return HandleMicrosoft__pragma(Tok);
  1326. ++NumBuiltinMacroExpanded;
  1327. SmallString<128> TmpBuffer;
  1328. llvm::raw_svector_ostream OS(TmpBuffer);
  1329. // Set up the return result.
  1330. Tok.setIdentifierInfo(nullptr);
  1331. Tok.clearFlag(Token::NeedsCleaning);
  1332. bool IsAtStartOfLine = Tok.isAtStartOfLine();
  1333. bool HasLeadingSpace = Tok.hasLeadingSpace();
  1334. if (II == Ident__LINE__) {
  1335. // C99 6.10.8: "__LINE__: The presumed line number (within the current
  1336. // source file) of the current source line (an integer constant)". This can
  1337. // be affected by #line.
  1338. SourceLocation Loc = Tok.getLocation();
  1339. // Advance to the location of the first _, this might not be the first byte
  1340. // of the token if it starts with an escaped newline.
  1341. Loc = AdvanceToTokenCharacter(Loc, 0);
  1342. // One wrinkle here is that GCC expands __LINE__ to location of the *end* of
  1343. // a macro expansion. This doesn't matter for object-like macros, but
  1344. // can matter for a function-like macro that expands to contain __LINE__.
  1345. // Skip down through expansion points until we find a file loc for the
  1346. // end of the expansion history.
  1347. Loc = SourceMgr.getExpansionRange(Loc).getEnd();
  1348. PresumedLoc PLoc = SourceMgr.getPresumedLoc(Loc);
  1349. // __LINE__ expands to a simple numeric value.
  1350. OS << (PLoc.isValid()? PLoc.getLine() : 1);
  1351. Tok.setKind(tok::numeric_constant);
  1352. } else if (II == Ident__FILE__ || II == Ident__BASE_FILE__ ||
  1353. II == Ident__FILE_NAME__) {
  1354. // C99 6.10.8: "__FILE__: The presumed name of the current source file (a
  1355. // character string literal)". This can be affected by #line.
  1356. PresumedLoc PLoc = SourceMgr.getPresumedLoc(Tok.getLocation());
  1357. // __BASE_FILE__ is a GNU extension that returns the top of the presumed
  1358. // #include stack instead of the current file.
  1359. if (II == Ident__BASE_FILE__ && PLoc.isValid()) {
  1360. SourceLocation NextLoc = PLoc.getIncludeLoc();
  1361. while (NextLoc.isValid()) {
  1362. PLoc = SourceMgr.getPresumedLoc(NextLoc);
  1363. if (PLoc.isInvalid())
  1364. break;
  1365. NextLoc = PLoc.getIncludeLoc();
  1366. }
  1367. }
  1368. // Escape this filename. Turn '\' -> '\\' '"' -> '\"'
  1369. SmallString<256> FN;
  1370. if (PLoc.isValid()) {
  1371. // __FILE_NAME__ is a Clang-specific extension that expands to the
  1372. // the last part of __FILE__.
  1373. if (II == Ident__FILE_NAME__) {
  1374. // Try to get the last path component, failing that return the original
  1375. // presumed location.
  1376. StringRef PLFileName = llvm::sys::path::filename(PLoc.getFilename());
  1377. if (PLFileName != "")
  1378. FN += PLFileName;
  1379. else
  1380. FN += PLoc.getFilename();
  1381. } else {
  1382. FN += PLoc.getFilename();
  1383. }
  1384. processPathForFileMacro(FN, getLangOpts(), getTargetInfo());
  1385. Lexer::Stringify(FN);
  1386. OS << '"' << FN << '"';
  1387. }
  1388. Tok.setKind(tok::string_literal);
  1389. } else if (II == Ident__DATE__) {
  1390. Diag(Tok.getLocation(), diag::warn_pp_date_time);
  1391. if (!DATELoc.isValid())
  1392. ComputeDATE_TIME(DATELoc, TIMELoc, *this);
  1393. Tok.setKind(tok::string_literal);
  1394. Tok.setLength(strlen("\"Mmm dd yyyy\""));
  1395. Tok.setLocation(SourceMgr.createExpansionLoc(DATELoc, Tok.getLocation(),
  1396. Tok.getLocation(),
  1397. Tok.getLength()));
  1398. return;
  1399. } else if (II == Ident__TIME__) {
  1400. Diag(Tok.getLocation(), diag::warn_pp_date_time);
  1401. if (!TIMELoc.isValid())
  1402. ComputeDATE_TIME(DATELoc, TIMELoc, *this);
  1403. Tok.setKind(tok::string_literal);
  1404. Tok.setLength(strlen("\"hh:mm:ss\""));
  1405. Tok.setLocation(SourceMgr.createExpansionLoc(TIMELoc, Tok.getLocation(),
  1406. Tok.getLocation(),
  1407. Tok.getLength()));
  1408. return;
  1409. } else if (II == Ident__INCLUDE_LEVEL__) {
  1410. // Compute the presumed include depth of this token. This can be affected
  1411. // by GNU line markers.
  1412. unsigned Depth = 0;
  1413. PresumedLoc PLoc = SourceMgr.getPresumedLoc(Tok.getLocation());
  1414. if (PLoc.isValid()) {
  1415. PLoc = SourceMgr.getPresumedLoc(PLoc.getIncludeLoc());
  1416. for (; PLoc.isValid(); ++Depth)
  1417. PLoc = SourceMgr.getPresumedLoc(PLoc.getIncludeLoc());
  1418. }
  1419. // __INCLUDE_LEVEL__ expands to a simple numeric value.
  1420. OS << Depth;
  1421. Tok.setKind(tok::numeric_constant);
  1422. } else if (II == Ident__TIMESTAMP__) {
  1423. Diag(Tok.getLocation(), diag::warn_pp_date_time);
  1424. // MSVC, ICC, GCC, VisualAge C++ extension. The generated string should be
  1425. // of the form "Ddd Mmm dd hh::mm::ss yyyy", which is returned by asctime.
  1426. const char *Result;
  1427. if (getPreprocessorOpts().SourceDateEpoch) {
  1428. time_t TT = *getPreprocessorOpts().SourceDateEpoch;
  1429. std::tm *TM = std::gmtime(&TT);
  1430. Result = asctime(TM);
  1431. } else {
  1432. // Get the file that we are lexing out of. If we're currently lexing from
  1433. // a macro, dig into the include stack.
  1434. const FileEntry *CurFile = nullptr;
  1435. if (PreprocessorLexer *TheLexer = getCurrentFileLexer())
  1436. CurFile = SourceMgr.getFileEntryForID(TheLexer->getFileID());
  1437. if (CurFile) {
  1438. time_t TT = CurFile->getModificationTime();
  1439. struct tm *TM = localtime(&TT);
  1440. Result = asctime(TM);
  1441. } else {
  1442. Result = "??? ??? ?? ??:??:?? ????\n";
  1443. }
  1444. }
  1445. // Surround the string with " and strip the trailing newline.
  1446. OS << '"' << StringRef(Result).drop_back() << '"';
  1447. Tok.setKind(tok::string_literal);
  1448. } else if (II == Ident__FLT_EVAL_METHOD__) {
  1449. // __FLT_EVAL_METHOD__ is set to the default value.
  1450. OS << getTUFPEvalMethod();
  1451. // __FLT_EVAL_METHOD__ expands to a simple numeric value.
  1452. Tok.setKind(tok::numeric_constant);
  1453. if (getLastFPEvalPragmaLocation().isValid()) {
  1454. // The program is ill-formed. The value of __FLT_EVAL_METHOD__ is altered
  1455. // by the pragma.
  1456. Diag(Tok, diag::err_illegal_use_of_flt_eval_macro);
  1457. Diag(getLastFPEvalPragmaLocation(), diag::note_pragma_entered_here);
  1458. }
  1459. } else if (II == Ident__COUNTER__) {
  1460. // __COUNTER__ expands to a simple numeric value.
  1461. OS << CounterValue++;
  1462. Tok.setKind(tok::numeric_constant);
  1463. } else if (II == Ident__has_feature) {
  1464. EvaluateFeatureLikeBuiltinMacro(OS, Tok, II, *this, false,
  1465. [this](Token &Tok, bool &HasLexedNextToken) -> int {
  1466. IdentifierInfo *II = ExpectFeatureIdentifierInfo(Tok, *this,
  1467. diag::err_feature_check_malformed);
  1468. return II && HasFeature(*this, II->getName());
  1469. });
  1470. } else if (II == Ident__has_extension) {
  1471. EvaluateFeatureLikeBuiltinMacro(OS, Tok, II, *this, false,
  1472. [this](Token &Tok, bool &HasLexedNextToken) -> int {
  1473. IdentifierInfo *II = ExpectFeatureIdentifierInfo(Tok, *this,
  1474. diag::err_feature_check_malformed);
  1475. return II && HasExtension(*this, II->getName());
  1476. });
  1477. } else if (II == Ident__has_builtin) {
  1478. EvaluateFeatureLikeBuiltinMacro(OS, Tok, II, *this, false,
  1479. [this](Token &Tok, bool &HasLexedNextToken) -> int {
  1480. IdentifierInfo *II = ExpectFeatureIdentifierInfo(Tok, *this,
  1481. diag::err_feature_check_malformed);
  1482. if (!II)
  1483. return false;
  1484. else if (II->getBuiltinID() != 0) {
  1485. switch (II->getBuiltinID()) {
  1486. case Builtin::BI__builtin_operator_new:
  1487. case Builtin::BI__builtin_operator_delete:
  1488. // denotes date of behavior change to support calling arbitrary
  1489. // usual allocation and deallocation functions. Required by libc++
  1490. return 201802;
  1491. default:
  1492. return Builtin::evaluateRequiredTargetFeatures(
  1493. getBuiltinInfo().getRequiredFeatures(II->getBuiltinID()),
  1494. getTargetInfo().getTargetOpts().FeatureMap);
  1495. }
  1496. return true;
  1497. } else if (II->getTokenID() != tok::identifier ||
  1498. II->hasRevertedTokenIDToIdentifier()) {
  1499. // Treat all keywords that introduce a custom syntax of the form
  1500. //
  1501. // '__some_keyword' '(' [...] ')'
  1502. //
  1503. // as being "builtin functions", even if the syntax isn't a valid
  1504. // function call (for example, because the builtin takes a type
  1505. // argument).
  1506. if (II->getName().startswith("__builtin_") ||
  1507. II->getName().startswith("__is_") ||
  1508. II->getName().startswith("__has_"))
  1509. return true;
  1510. return llvm::StringSwitch<bool>(II->getName())
  1511. .Case("__array_rank", true)
  1512. .Case("__array_extent", true)
  1513. .Case("__reference_binds_to_temporary", true)
  1514. #define TRANSFORM_TYPE_TRAIT_DEF(_, Trait) .Case("__" #Trait, true)
  1515. #include "clang/Basic/TransformTypeTraits.def"
  1516. .Default(false);
  1517. } else {
  1518. return llvm::StringSwitch<bool>(II->getName())
  1519. // Report builtin templates as being builtins.
  1520. .Case("__make_integer_seq", getLangOpts().CPlusPlus)
  1521. .Case("__type_pack_element", getLangOpts().CPlusPlus)
  1522. // Likewise for some builtin preprocessor macros.
  1523. // FIXME: This is inconsistent; we usually suggest detecting
  1524. // builtin macros via #ifdef. Don't add more cases here.
  1525. .Case("__is_target_arch", true)
  1526. .Case("__is_target_vendor", true)
  1527. .Case("__is_target_os", true)
  1528. .Case("__is_target_environment", true)
  1529. .Case("__is_target_variant_os", true)
  1530. .Case("__is_target_variant_environment", true)
  1531. .Default(false);
  1532. }
  1533. });
  1534. } else if (II == Ident__has_constexpr_builtin) {
  1535. EvaluateFeatureLikeBuiltinMacro(
  1536. OS, Tok, II, *this, false,
  1537. [this](Token &Tok, bool &HasLexedNextToken) -> int {
  1538. IdentifierInfo *II = ExpectFeatureIdentifierInfo(
  1539. Tok, *this, diag::err_feature_check_malformed);
  1540. if (!II)
  1541. return false;
  1542. unsigned BuiltinOp = II->getBuiltinID();
  1543. return BuiltinOp != 0 &&
  1544. this->getBuiltinInfo().isConstantEvaluated(BuiltinOp);
  1545. });
  1546. } else if (II == Ident__is_identifier) {
  1547. EvaluateFeatureLikeBuiltinMacro(OS, Tok, II, *this, false,
  1548. [](Token &Tok, bool &HasLexedNextToken) -> int {
  1549. return Tok.is(tok::identifier);
  1550. });
  1551. } else if (II == Ident__has_attribute) {
  1552. EvaluateFeatureLikeBuiltinMacro(OS, Tok, II, *this, true,
  1553. [this](Token &Tok, bool &HasLexedNextToken) -> int {
  1554. IdentifierInfo *II = ExpectFeatureIdentifierInfo(Tok, *this,
  1555. diag::err_feature_check_malformed);
  1556. return II ? hasAttribute(AttributeCommonInfo::Syntax::AS_GNU, nullptr,
  1557. II, getTargetInfo(), getLangOpts())
  1558. : 0;
  1559. });
  1560. } else if (II == Ident__has_declspec) {
  1561. EvaluateFeatureLikeBuiltinMacro(OS, Tok, II, *this, true,
  1562. [this](Token &Tok, bool &HasLexedNextToken) -> int {
  1563. IdentifierInfo *II = ExpectFeatureIdentifierInfo(Tok, *this,
  1564. diag::err_feature_check_malformed);
  1565. if (II) {
  1566. const LangOptions &LangOpts = getLangOpts();
  1567. return LangOpts.DeclSpecKeyword &&
  1568. hasAttribute(AttributeCommonInfo::Syntax::AS_Declspec, nullptr,
  1569. II, getTargetInfo(), LangOpts);
  1570. }
  1571. return false;
  1572. });
  1573. } else if (II == Ident__has_cpp_attribute ||
  1574. II == Ident__has_c_attribute) {
  1575. bool IsCXX = II == Ident__has_cpp_attribute;
  1576. EvaluateFeatureLikeBuiltinMacro(OS, Tok, II, *this, true,
  1577. [&](Token &Tok, bool &HasLexedNextToken) -> int {
  1578. IdentifierInfo *ScopeII = nullptr;
  1579. IdentifierInfo *II = ExpectFeatureIdentifierInfo(
  1580. Tok, *this, diag::err_feature_check_malformed);
  1581. if (!II)
  1582. return false;
  1583. // It is possible to receive a scope token. Read the "::", if it is
  1584. // available, and the subsequent identifier.
  1585. LexUnexpandedToken(Tok);
  1586. if (Tok.isNot(tok::coloncolon))
  1587. HasLexedNextToken = true;
  1588. else {
  1589. ScopeII = II;
  1590. // Lex an expanded token for the attribute name.
  1591. Lex(Tok);
  1592. II = ExpectFeatureIdentifierInfo(Tok, *this,
  1593. diag::err_feature_check_malformed);
  1594. }
  1595. AttributeCommonInfo::Syntax Syntax =
  1596. IsCXX ? AttributeCommonInfo::Syntax::AS_CXX11
  1597. : AttributeCommonInfo::Syntax::AS_C2x;
  1598. return II ? hasAttribute(Syntax, ScopeII, II, getTargetInfo(),
  1599. getLangOpts())
  1600. : 0;
  1601. });
  1602. } else if (II == Ident__has_include ||
  1603. II == Ident__has_include_next) {
  1604. // The argument to these two builtins should be a parenthesized
  1605. // file name string literal using angle brackets (<>) or
  1606. // double-quotes ("").
  1607. bool Value;
  1608. if (II == Ident__has_include)
  1609. Value = EvaluateHasInclude(Tok, II);
  1610. else
  1611. Value = EvaluateHasIncludeNext(Tok, II);
  1612. if (Tok.isNot(tok::r_paren))
  1613. return;
  1614. OS << (int)Value;
  1615. Tok.setKind(tok::numeric_constant);
  1616. } else if (II == Ident__has_warning) {
  1617. // The argument should be a parenthesized string literal.
  1618. EvaluateFeatureLikeBuiltinMacro(OS, Tok, II, *this, false,
  1619. [this](Token &Tok, bool &HasLexedNextToken) -> int {
  1620. std::string WarningName;
  1621. SourceLocation StrStartLoc = Tok.getLocation();
  1622. HasLexedNextToken = Tok.is(tok::string_literal);
  1623. if (!FinishLexStringLiteral(Tok, WarningName, "'__has_warning'",
  1624. /*AllowMacroExpansion=*/false))
  1625. return false;
  1626. // FIXME: Should we accept "-R..." flags here, or should that be
  1627. // handled by a separate __has_remark?
  1628. if (WarningName.size() < 3 || WarningName[0] != '-' ||
  1629. WarningName[1] != 'W') {
  1630. Diag(StrStartLoc, diag::warn_has_warning_invalid_option);
  1631. return false;
  1632. }
  1633. // Finally, check if the warning flags maps to a diagnostic group.
  1634. // We construct a SmallVector here to talk to getDiagnosticIDs().
  1635. // Although we don't use the result, this isn't a hot path, and not
  1636. // worth special casing.
  1637. SmallVector<diag::kind, 10> Diags;
  1638. return !getDiagnostics().getDiagnosticIDs()->
  1639. getDiagnosticsInGroup(diag::Flavor::WarningOrError,
  1640. WarningName.substr(2), Diags);
  1641. });
  1642. } else if (II == Ident__building_module) {
  1643. // The argument to this builtin should be an identifier. The
  1644. // builtin evaluates to 1 when that identifier names the module we are
  1645. // currently building.
  1646. EvaluateFeatureLikeBuiltinMacro(OS, Tok, II, *this, false,
  1647. [this](Token &Tok, bool &HasLexedNextToken) -> int {
  1648. IdentifierInfo *II = ExpectFeatureIdentifierInfo(Tok, *this,
  1649. diag::err_expected_id_building_module);
  1650. return getLangOpts().isCompilingModule() && II &&
  1651. (II->getName() == getLangOpts().CurrentModule);
  1652. });
  1653. } else if (II == Ident__MODULE__) {
  1654. // The current module as an identifier.
  1655. OS << getLangOpts().CurrentModule;
  1656. IdentifierInfo *ModuleII = getIdentifierInfo(getLangOpts().CurrentModule);
  1657. Tok.setIdentifierInfo(ModuleII);
  1658. Tok.setKind(ModuleII->getTokenID());
  1659. } else if (II == Ident__identifier) {
  1660. SourceLocation Loc = Tok.getLocation();
  1661. // We're expecting '__identifier' '(' identifier ')'. Try to recover
  1662. // if the parens are missing.
  1663. LexNonComment(Tok);
  1664. if (Tok.isNot(tok::l_paren)) {
  1665. // No '(', use end of last token.
  1666. Diag(getLocForEndOfToken(Loc), diag::err_pp_expected_after)
  1667. << II << tok::l_paren;
  1668. // If the next token isn't valid as our argument, we can't recover.
  1669. if (!Tok.isAnnotation() && Tok.getIdentifierInfo())
  1670. Tok.setKind(tok::identifier);
  1671. return;
  1672. }
  1673. SourceLocation LParenLoc = Tok.getLocation();
  1674. LexNonComment(Tok);
  1675. if (!Tok.isAnnotation() && Tok.getIdentifierInfo())
  1676. Tok.setKind(tok::identifier);
  1677. else if (Tok.is(tok::string_literal) && !Tok.hasUDSuffix()) {
  1678. StringLiteralParser Literal(Tok, *this);
  1679. if (Literal.hadError)
  1680. return;
  1681. Tok.setIdentifierInfo(getIdentifierInfo(Literal.GetString()));
  1682. Tok.setKind(tok::identifier);
  1683. } else {
  1684. Diag(Tok.getLocation(), diag::err_pp_identifier_arg_not_identifier)
  1685. << Tok.getKind();
  1686. // Don't walk past anything that's not a real token.
  1687. if (Tok.isOneOf(tok::eof, tok::eod) || Tok.isAnnotation())
  1688. return;
  1689. }
  1690. // Discard the ')', preserving 'Tok' as our result.
  1691. Token RParen;
  1692. LexNonComment(RParen);
  1693. if (RParen.isNot(tok::r_paren)) {
  1694. Diag(getLocForEndOfToken(Tok.getLocation()), diag::err_pp_expected_after)
  1695. << Tok.getKind() << tok::r_paren;
  1696. Diag(LParenLoc, diag::note_matching) << tok::l_paren;
  1697. }
  1698. return;
  1699. } else if (II == Ident__is_target_arch) {
  1700. EvaluateFeatureLikeBuiltinMacro(
  1701. OS, Tok, II, *this, false,
  1702. [this](Token &Tok, bool &HasLexedNextToken) -> int {
  1703. IdentifierInfo *II = ExpectFeatureIdentifierInfo(
  1704. Tok, *this, diag::err_feature_check_malformed);
  1705. return II && isTargetArch(getTargetInfo(), II);
  1706. });
  1707. } else if (II == Ident__is_target_vendor) {
  1708. EvaluateFeatureLikeBuiltinMacro(
  1709. OS, Tok, II, *this, false,
  1710. [this](Token &Tok, bool &HasLexedNextToken) -> int {
  1711. IdentifierInfo *II = ExpectFeatureIdentifierInfo(
  1712. Tok, *this, diag::err_feature_check_malformed);
  1713. return II && isTargetVendor(getTargetInfo(), II);
  1714. });
  1715. } else if (II == Ident__is_target_os) {
  1716. EvaluateFeatureLikeBuiltinMacro(
  1717. OS, Tok, II, *this, false,
  1718. [this](Token &Tok, bool &HasLexedNextToken) -> int {
  1719. IdentifierInfo *II = ExpectFeatureIdentifierInfo(
  1720. Tok, *this, diag::err_feature_check_malformed);
  1721. return II && isTargetOS(getTargetInfo(), II);
  1722. });
  1723. } else if (II == Ident__is_target_environment) {
  1724. EvaluateFeatureLikeBuiltinMacro(
  1725. OS, Tok, II, *this, false,
  1726. [this](Token &Tok, bool &HasLexedNextToken) -> int {
  1727. IdentifierInfo *II = ExpectFeatureIdentifierInfo(
  1728. Tok, *this, diag::err_feature_check_malformed);
  1729. return II && isTargetEnvironment(getTargetInfo(), II);
  1730. });
  1731. } else if (II == Ident__is_target_variant_os) {
  1732. EvaluateFeatureLikeBuiltinMacro(
  1733. OS, Tok, II, *this, false,
  1734. [this](Token &Tok, bool &HasLexedNextToken) -> int {
  1735. IdentifierInfo *II = ExpectFeatureIdentifierInfo(
  1736. Tok, *this, diag::err_feature_check_malformed);
  1737. return II && isTargetVariantOS(getTargetInfo(), II);
  1738. });
  1739. } else if (II == Ident__is_target_variant_environment) {
  1740. EvaluateFeatureLikeBuiltinMacro(
  1741. OS, Tok, II, *this, false,
  1742. [this](Token &Tok, bool &HasLexedNextToken) -> int {
  1743. IdentifierInfo *II = ExpectFeatureIdentifierInfo(
  1744. Tok, *this, diag::err_feature_check_malformed);
  1745. return II && isTargetVariantEnvironment(getTargetInfo(), II);
  1746. });
  1747. } else {
  1748. llvm_unreachable("Unknown identifier!");
  1749. }
  1750. CreateString(OS.str(), Tok, Tok.getLocation(), Tok.getLocation());
  1751. Tok.setFlagValue(Token::StartOfLine, IsAtStartOfLine);
  1752. Tok.setFlagValue(Token::LeadingSpace, HasLeadingSpace);
  1753. }
  1754. void Preprocessor::markMacroAsUsed(MacroInfo *MI) {
  1755. // If the 'used' status changed, and the macro requires 'unused' warning,
  1756. // remove its SourceLocation from the warn-for-unused-macro locations.
  1757. if (MI->isWarnIfUnused() && !MI->isUsed())
  1758. WarnUnusedMacroLocs.erase(MI->getDefinitionLoc());
  1759. MI->setIsUsed(true);
  1760. }
  1761. void Preprocessor::processPathForFileMacro(SmallVectorImpl<char> &Path,
  1762. const LangOptions &LangOpts,
  1763. const TargetInfo &TI) {
  1764. LangOpts.remapPathPrefix(Path);
  1765. if (LangOpts.UseTargetPathSeparator) {
  1766. if (TI.getTriple().isOSWindows())
  1767. llvm::sys::path::remove_dots(Path, false,
  1768. llvm::sys::path::Style::windows_backslash);
  1769. else
  1770. llvm::sys::path::remove_dots(Path, false, llvm::sys::path::Style::posix);
  1771. }
  1772. }