PPMacroExpansion.cpp 70 KB

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