FrontendAction.cpp 40 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062
  1. //===--- FrontendAction.cpp -----------------------------------------------===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. #include "clang/Frontend/FrontendAction.h"
  10. #include "clang/AST/ASTConsumer.h"
  11. #include "clang/AST/ASTContext.h"
  12. #include "clang/AST/DeclGroup.h"
  13. #include "clang/Frontend/ASTUnit.h"
  14. #include "clang/Frontend/CompilerInstance.h"
  15. #include "clang/Frontend/FrontendDiagnostic.h"
  16. #include "clang/Frontend/FrontendPluginRegistry.h"
  17. #include "clang/Frontend/LayoutOverrideSource.h"
  18. #include "clang/Frontend/MultiplexConsumer.h"
  19. #include "clang/Frontend/Utils.h"
  20. #include "clang/Lex/HeaderSearch.h"
  21. #include "clang/Lex/LiteralSupport.h"
  22. #include "clang/Lex/Preprocessor.h"
  23. #include "clang/Lex/PreprocessorOptions.h"
  24. #include "clang/Parse/ParseAST.h"
  25. #include "clang/Serialization/ASTDeserializationListener.h"
  26. #include "clang/Serialization/ASTReader.h"
  27. #include "clang/Serialization/GlobalModuleIndex.h"
  28. #include "llvm/Support/ErrorHandling.h"
  29. #include "llvm/Support/FileSystem.h"
  30. #include "llvm/Support/Path.h"
  31. #include "llvm/Support/Timer.h"
  32. #include "llvm/Support/raw_ostream.h"
  33. #include <system_error>
  34. using namespace clang;
  35. LLVM_INSTANTIATE_REGISTRY(FrontendPluginRegistry)
  36. namespace {
  37. class DelegatingDeserializationListener : public ASTDeserializationListener {
  38. ASTDeserializationListener *Previous;
  39. bool DeletePrevious;
  40. public:
  41. explicit DelegatingDeserializationListener(
  42. ASTDeserializationListener *Previous, bool DeletePrevious)
  43. : Previous(Previous), DeletePrevious(DeletePrevious) {}
  44. ~DelegatingDeserializationListener() override {
  45. if (DeletePrevious)
  46. delete Previous;
  47. }
  48. void ReaderInitialized(ASTReader *Reader) override {
  49. if (Previous)
  50. Previous->ReaderInitialized(Reader);
  51. }
  52. void IdentifierRead(serialization::IdentID ID,
  53. IdentifierInfo *II) override {
  54. if (Previous)
  55. Previous->IdentifierRead(ID, II);
  56. }
  57. void TypeRead(serialization::TypeIdx Idx, QualType T) override {
  58. if (Previous)
  59. Previous->TypeRead(Idx, T);
  60. }
  61. void DeclRead(serialization::DeclID ID, const Decl *D) override {
  62. if (Previous)
  63. Previous->DeclRead(ID, D);
  64. }
  65. void SelectorRead(serialization::SelectorID ID, Selector Sel) override {
  66. if (Previous)
  67. Previous->SelectorRead(ID, Sel);
  68. }
  69. void MacroDefinitionRead(serialization::PreprocessedEntityID PPID,
  70. MacroDefinitionRecord *MD) override {
  71. if (Previous)
  72. Previous->MacroDefinitionRead(PPID, MD);
  73. }
  74. };
  75. /// \brief Dumps deserialized declarations.
  76. class DeserializedDeclsDumper : public DelegatingDeserializationListener {
  77. public:
  78. explicit DeserializedDeclsDumper(ASTDeserializationListener *Previous,
  79. bool DeletePrevious)
  80. : DelegatingDeserializationListener(Previous, DeletePrevious) {}
  81. void DeclRead(serialization::DeclID ID, const Decl *D) override {
  82. llvm::outs() << "PCH DECL: " << D->getDeclKindName();
  83. if (const NamedDecl *ND = dyn_cast<NamedDecl>(D))
  84. llvm::outs() << " - " << *ND;
  85. llvm::outs() << "\n";
  86. DelegatingDeserializationListener::DeclRead(ID, D);
  87. }
  88. };
  89. /// \brief Checks deserialized declarations and emits error if a name
  90. /// matches one given in command-line using -error-on-deserialized-decl.
  91. class DeserializedDeclsChecker : public DelegatingDeserializationListener {
  92. ASTContext &Ctx;
  93. std::set<std::string> NamesToCheck;
  94. public:
  95. DeserializedDeclsChecker(ASTContext &Ctx,
  96. const std::set<std::string> &NamesToCheck,
  97. ASTDeserializationListener *Previous,
  98. bool DeletePrevious)
  99. : DelegatingDeserializationListener(Previous, DeletePrevious), Ctx(Ctx),
  100. NamesToCheck(NamesToCheck) {}
  101. void DeclRead(serialization::DeclID ID, const Decl *D) override {
  102. if (const NamedDecl *ND = dyn_cast<NamedDecl>(D))
  103. if (NamesToCheck.find(ND->getNameAsString()) != NamesToCheck.end()) {
  104. unsigned DiagID
  105. = Ctx.getDiagnostics().getCustomDiagID(DiagnosticsEngine::Error,
  106. "%0 was deserialized");
  107. Ctx.getDiagnostics().Report(Ctx.getFullLoc(D->getLocation()), DiagID)
  108. << ND->getNameAsString();
  109. }
  110. DelegatingDeserializationListener::DeclRead(ID, D);
  111. }
  112. };
  113. } // end anonymous namespace
  114. FrontendAction::FrontendAction() : Instance(nullptr) {}
  115. FrontendAction::~FrontendAction() {}
  116. void FrontendAction::setCurrentInput(const FrontendInputFile &CurrentInput,
  117. std::unique_ptr<ASTUnit> AST) {
  118. this->CurrentInput = CurrentInput;
  119. CurrentASTUnit = std::move(AST);
  120. }
  121. Module *FrontendAction::getCurrentModule() const {
  122. CompilerInstance &CI = getCompilerInstance();
  123. return CI.getPreprocessor().getHeaderSearchInfo().lookupModule(
  124. CI.getLangOpts().CurrentModule, /*AllowSearch*/false);
  125. }
  126. std::unique_ptr<ASTConsumer>
  127. FrontendAction::CreateWrappedASTConsumer(CompilerInstance &CI,
  128. StringRef InFile) {
  129. std::unique_ptr<ASTConsumer> Consumer = CreateASTConsumer(CI, InFile);
  130. if (!Consumer)
  131. return nullptr;
  132. // If there are no registered plugins we don't need to wrap the consumer
  133. if (FrontendPluginRegistry::begin() == FrontendPluginRegistry::end())
  134. return Consumer;
  135. // Collect the list of plugins that go before the main action (in Consumers)
  136. // or after it (in AfterConsumers)
  137. std::vector<std::unique_ptr<ASTConsumer>> Consumers;
  138. std::vector<std::unique_ptr<ASTConsumer>> AfterConsumers;
  139. for (FrontendPluginRegistry::iterator it = FrontendPluginRegistry::begin(),
  140. ie = FrontendPluginRegistry::end();
  141. it != ie; ++it) {
  142. std::unique_ptr<PluginASTAction> P = it->instantiate();
  143. PluginASTAction::ActionType ActionType = P->getActionType();
  144. if (ActionType == PluginASTAction::Cmdline) {
  145. // This is O(|plugins| * |add_plugins|), but since both numbers are
  146. // way below 50 in practice, that's ok.
  147. for (size_t i = 0, e = CI.getFrontendOpts().AddPluginActions.size();
  148. i != e; ++i) {
  149. if (it->getName() == CI.getFrontendOpts().AddPluginActions[i]) {
  150. ActionType = PluginASTAction::AddAfterMainAction;
  151. break;
  152. }
  153. }
  154. }
  155. if ((ActionType == PluginASTAction::AddBeforeMainAction ||
  156. ActionType == PluginASTAction::AddAfterMainAction) &&
  157. P->ParseArgs(CI, CI.getFrontendOpts().PluginArgs[it->getName()])) {
  158. std::unique_ptr<ASTConsumer> PluginConsumer = P->CreateASTConsumer(CI, InFile);
  159. if (ActionType == PluginASTAction::AddBeforeMainAction) {
  160. Consumers.push_back(std::move(PluginConsumer));
  161. } else {
  162. AfterConsumers.push_back(std::move(PluginConsumer));
  163. }
  164. }
  165. }
  166. // Add to Consumers the main consumer, then all the plugins that go after it
  167. Consumers.push_back(std::move(Consumer));
  168. for (auto &C : AfterConsumers) {
  169. Consumers.push_back(std::move(C));
  170. }
  171. return llvm::make_unique<MultiplexConsumer>(std::move(Consumers));
  172. }
  173. /// For preprocessed files, if the first line is the linemarker and specifies
  174. /// the original source file name, use that name as the input file name.
  175. /// Returns the location of the first token after the line marker directive.
  176. ///
  177. /// \param CI The compiler instance.
  178. /// \param InputFile Populated with the filename from the line marker.
  179. /// \param AddLineNote If \c true, add a line note corresponding to this line
  180. /// directive. Only use this if the directive will not actually be
  181. /// visited by the preprocessor.
  182. static SourceLocation ReadOriginalFileName(CompilerInstance &CI,
  183. std::string &InputFile,
  184. bool AddLineNote = false) {
  185. auto &SourceMgr = CI.getSourceManager();
  186. auto MainFileID = SourceMgr.getMainFileID();
  187. bool Invalid = false;
  188. const auto *MainFileBuf = SourceMgr.getBuffer(MainFileID, &Invalid);
  189. if (Invalid)
  190. return SourceLocation();
  191. std::unique_ptr<Lexer> RawLexer(
  192. new Lexer(MainFileID, MainFileBuf, SourceMgr, CI.getLangOpts()));
  193. // If the first line has the syntax of
  194. //
  195. // # NUM "FILENAME"
  196. //
  197. // we use FILENAME as the input file name.
  198. Token T;
  199. if (RawLexer->LexFromRawLexer(T) || T.getKind() != tok::hash)
  200. return SourceLocation();
  201. if (RawLexer->LexFromRawLexer(T) || T.isAtStartOfLine() ||
  202. T.getKind() != tok::numeric_constant)
  203. return SourceLocation();
  204. unsigned LineNo;
  205. SourceLocation LineNoLoc = T.getLocation();
  206. if (AddLineNote) {
  207. llvm::SmallString<16> Buffer;
  208. if (Lexer::getSpelling(LineNoLoc, Buffer, SourceMgr, CI.getLangOpts())
  209. .getAsInteger(10, LineNo))
  210. return SourceLocation();
  211. }
  212. RawLexer->LexFromRawLexer(T);
  213. if (T.isAtStartOfLine() || T.getKind() != tok::string_literal)
  214. return SourceLocation();
  215. StringLiteralParser Literal(T, CI.getPreprocessor());
  216. if (Literal.hadError)
  217. return SourceLocation();
  218. RawLexer->LexFromRawLexer(T);
  219. if (T.isNot(tok::eof) && !T.isAtStartOfLine())
  220. return SourceLocation();
  221. InputFile = Literal.GetString().str();
  222. if (AddLineNote)
  223. CI.getSourceManager().AddLineNote(
  224. LineNoLoc, LineNo, SourceMgr.getLineTableFilenameID(InputFile), false,
  225. false, SrcMgr::C_User);
  226. return T.getLocation();
  227. }
  228. static SmallVectorImpl<char> &
  229. operator+=(SmallVectorImpl<char> &Includes, StringRef RHS) {
  230. Includes.append(RHS.begin(), RHS.end());
  231. return Includes;
  232. }
  233. static void addHeaderInclude(StringRef HeaderName,
  234. SmallVectorImpl<char> &Includes,
  235. const LangOptions &LangOpts,
  236. bool IsExternC) {
  237. if (IsExternC && LangOpts.CPlusPlus)
  238. Includes += "extern \"C\" {\n";
  239. if (LangOpts.ObjC1)
  240. Includes += "#import \"";
  241. else
  242. Includes += "#include \"";
  243. Includes += HeaderName;
  244. Includes += "\"\n";
  245. if (IsExternC && LangOpts.CPlusPlus)
  246. Includes += "}\n";
  247. }
  248. /// \brief Collect the set of header includes needed to construct the given
  249. /// module and update the TopHeaders file set of the module.
  250. ///
  251. /// \param Module The module we're collecting includes from.
  252. ///
  253. /// \param Includes Will be augmented with the set of \#includes or \#imports
  254. /// needed to load all of the named headers.
  255. static std::error_code collectModuleHeaderIncludes(
  256. const LangOptions &LangOpts, FileManager &FileMgr, DiagnosticsEngine &Diag,
  257. ModuleMap &ModMap, clang::Module *Module, SmallVectorImpl<char> &Includes) {
  258. // Don't collect any headers for unavailable modules.
  259. if (!Module->isAvailable())
  260. return std::error_code();
  261. // Resolve all lazy header directives to header files.
  262. ModMap.resolveHeaderDirectives(Module);
  263. // If any headers are missing, we can't build this module. In most cases,
  264. // diagnostics for this should have already been produced; we only get here
  265. // if explicit stat information was provided.
  266. // FIXME: If the name resolves to a file with different stat information,
  267. // produce a better diagnostic.
  268. if (!Module->MissingHeaders.empty()) {
  269. auto &MissingHeader = Module->MissingHeaders.front();
  270. Diag.Report(MissingHeader.FileNameLoc, diag::err_module_header_missing)
  271. << MissingHeader.IsUmbrella << MissingHeader.FileName;
  272. return std::error_code();
  273. }
  274. // Add includes for each of these headers.
  275. for (auto HK : {Module::HK_Normal, Module::HK_Private}) {
  276. for (Module::Header &H : Module->Headers[HK]) {
  277. Module->addTopHeader(H.Entry);
  278. // Use the path as specified in the module map file. We'll look for this
  279. // file relative to the module build directory (the directory containing
  280. // the module map file) so this will find the same file that we found
  281. // while parsing the module map.
  282. addHeaderInclude(H.NameAsWritten, Includes, LangOpts, Module->IsExternC);
  283. }
  284. }
  285. // Note that Module->PrivateHeaders will not be a TopHeader.
  286. if (Module::Header UmbrellaHeader = Module->getUmbrellaHeader()) {
  287. Module->addTopHeader(UmbrellaHeader.Entry);
  288. if (Module->Parent)
  289. // Include the umbrella header for submodules.
  290. addHeaderInclude(UmbrellaHeader.NameAsWritten, Includes, LangOpts,
  291. Module->IsExternC);
  292. } else if (Module::DirectoryName UmbrellaDir = Module->getUmbrellaDir()) {
  293. // Add all of the headers we find in this subdirectory.
  294. std::error_code EC;
  295. SmallString<128> DirNative;
  296. llvm::sys::path::native(UmbrellaDir.Entry->getName(), DirNative);
  297. vfs::FileSystem &FS = *FileMgr.getVirtualFileSystem();
  298. for (vfs::recursive_directory_iterator Dir(FS, DirNative, EC), End;
  299. Dir != End && !EC; Dir.increment(EC)) {
  300. // Check whether this entry has an extension typically associated with
  301. // headers.
  302. if (!llvm::StringSwitch<bool>(llvm::sys::path::extension(Dir->getName()))
  303. .Cases(".h", ".H", ".hh", ".hpp", true)
  304. .Default(false))
  305. continue;
  306. const FileEntry *Header = FileMgr.getFile(Dir->getName());
  307. // FIXME: This shouldn't happen unless there is a file system race. Is
  308. // that worth diagnosing?
  309. if (!Header)
  310. continue;
  311. // If this header is marked 'unavailable' in this module, don't include
  312. // it.
  313. if (ModMap.isHeaderUnavailableInModule(Header, Module))
  314. continue;
  315. // Compute the relative path from the directory to this file.
  316. SmallVector<StringRef, 16> Components;
  317. auto PathIt = llvm::sys::path::rbegin(Dir->getName());
  318. for (int I = 0; I != Dir.level() + 1; ++I, ++PathIt)
  319. Components.push_back(*PathIt);
  320. SmallString<128> RelativeHeader(UmbrellaDir.NameAsWritten);
  321. for (auto It = Components.rbegin(), End = Components.rend(); It != End;
  322. ++It)
  323. llvm::sys::path::append(RelativeHeader, *It);
  324. // Include this header as part of the umbrella directory.
  325. Module->addTopHeader(Header);
  326. addHeaderInclude(RelativeHeader, Includes, LangOpts, Module->IsExternC);
  327. }
  328. if (EC)
  329. return EC;
  330. }
  331. // Recurse into submodules.
  332. for (clang::Module::submodule_iterator Sub = Module->submodule_begin(),
  333. SubEnd = Module->submodule_end();
  334. Sub != SubEnd; ++Sub)
  335. if (std::error_code Err = collectModuleHeaderIncludes(
  336. LangOpts, FileMgr, Diag, ModMap, *Sub, Includes))
  337. return Err;
  338. return std::error_code();
  339. }
  340. static bool loadModuleMapForModuleBuild(CompilerInstance &CI, bool IsSystem,
  341. bool IsPreprocessed,
  342. std::string &PresumedModuleMapFile,
  343. unsigned &Offset) {
  344. auto &SrcMgr = CI.getSourceManager();
  345. HeaderSearch &HS = CI.getPreprocessor().getHeaderSearchInfo();
  346. // Map the current input to a file.
  347. FileID ModuleMapID = SrcMgr.getMainFileID();
  348. const FileEntry *ModuleMap = SrcMgr.getFileEntryForID(ModuleMapID);
  349. // If the module map is preprocessed, handle the initial line marker;
  350. // line directives are not part of the module map syntax in general.
  351. Offset = 0;
  352. if (IsPreprocessed) {
  353. SourceLocation EndOfLineMarker =
  354. ReadOriginalFileName(CI, PresumedModuleMapFile, /*AddLineNote*/true);
  355. if (EndOfLineMarker.isValid())
  356. Offset = CI.getSourceManager().getDecomposedLoc(EndOfLineMarker).second;
  357. }
  358. // Load the module map file.
  359. if (HS.loadModuleMapFile(ModuleMap, IsSystem, ModuleMapID, &Offset,
  360. PresumedModuleMapFile))
  361. return true;
  362. if (SrcMgr.getBuffer(ModuleMapID)->getBufferSize() == Offset)
  363. Offset = 0;
  364. return false;
  365. }
  366. static Module *prepareToBuildModule(CompilerInstance &CI,
  367. StringRef ModuleMapFilename) {
  368. if (CI.getLangOpts().CurrentModule.empty()) {
  369. CI.getDiagnostics().Report(diag::err_missing_module_name);
  370. // FIXME: Eventually, we could consider asking whether there was just
  371. // a single module described in the module map, and use that as a
  372. // default. Then it would be fairly trivial to just "compile" a module
  373. // map with a single module (the common case).
  374. return nullptr;
  375. }
  376. // Dig out the module definition.
  377. HeaderSearch &HS = CI.getPreprocessor().getHeaderSearchInfo();
  378. Module *M = HS.lookupModule(CI.getLangOpts().CurrentModule,
  379. /*AllowSearch=*/false);
  380. if (!M) {
  381. CI.getDiagnostics().Report(diag::err_missing_module)
  382. << CI.getLangOpts().CurrentModule << ModuleMapFilename;
  383. return nullptr;
  384. }
  385. // Check whether we can build this module at all.
  386. clang::Module::Requirement Requirement;
  387. clang::Module::UnresolvedHeaderDirective MissingHeader;
  388. if (!M->isAvailable(CI.getLangOpts(), CI.getTarget(), Requirement,
  389. MissingHeader)) {
  390. if (MissingHeader.FileNameLoc.isValid()) {
  391. CI.getDiagnostics().Report(MissingHeader.FileNameLoc,
  392. diag::err_module_header_missing)
  393. << MissingHeader.IsUmbrella << MissingHeader.FileName;
  394. } else {
  395. CI.getDiagnostics().Report(diag::err_module_unavailable)
  396. << M->getFullModuleName() << Requirement.second << Requirement.first;
  397. }
  398. return nullptr;
  399. }
  400. // Inform the preprocessor that includes from within the input buffer should
  401. // be resolved relative to the build directory of the module map file.
  402. CI.getPreprocessor().setMainFileDir(M->Directory);
  403. // If the module was inferred from a different module map (via an expanded
  404. // umbrella module definition), track that fact.
  405. // FIXME: It would be preferable to fill this in as part of processing
  406. // the module map, rather than adding it after the fact.
  407. StringRef OriginalModuleMapName = CI.getFrontendOpts().OriginalModuleMap;
  408. if (!OriginalModuleMapName.empty()) {
  409. auto *OriginalModuleMap =
  410. CI.getFileManager().getFile(OriginalModuleMapName,
  411. /*openFile*/ true);
  412. if (!OriginalModuleMap) {
  413. CI.getDiagnostics().Report(diag::err_module_map_not_found)
  414. << OriginalModuleMapName;
  415. return nullptr;
  416. }
  417. if (OriginalModuleMap != CI.getSourceManager().getFileEntryForID(
  418. CI.getSourceManager().getMainFileID())) {
  419. M->IsInferred = true;
  420. CI.getPreprocessor().getHeaderSearchInfo().getModuleMap()
  421. .setInferredModuleAllowedBy(M, OriginalModuleMap);
  422. }
  423. }
  424. // If we're being run from the command-line, the module build stack will not
  425. // have been filled in yet, so complete it now in order to allow us to detect
  426. // module cycles.
  427. SourceManager &SourceMgr = CI.getSourceManager();
  428. if (SourceMgr.getModuleBuildStack().empty())
  429. SourceMgr.pushModuleBuildStack(CI.getLangOpts().CurrentModule,
  430. FullSourceLoc(SourceLocation(), SourceMgr));
  431. return M;
  432. }
  433. /// Compute the input buffer that should be used to build the specified module.
  434. static std::unique_ptr<llvm::MemoryBuffer>
  435. getInputBufferForModule(CompilerInstance &CI, Module *M) {
  436. FileManager &FileMgr = CI.getFileManager();
  437. // Collect the set of #includes we need to build the module.
  438. SmallString<256> HeaderContents;
  439. std::error_code Err = std::error_code();
  440. if (Module::Header UmbrellaHeader = M->getUmbrellaHeader())
  441. addHeaderInclude(UmbrellaHeader.NameAsWritten, HeaderContents,
  442. CI.getLangOpts(), M->IsExternC);
  443. Err = collectModuleHeaderIncludes(
  444. CI.getLangOpts(), FileMgr, CI.getDiagnostics(),
  445. CI.getPreprocessor().getHeaderSearchInfo().getModuleMap(), M,
  446. HeaderContents);
  447. if (Err) {
  448. CI.getDiagnostics().Report(diag::err_module_cannot_create_includes)
  449. << M->getFullModuleName() << Err.message();
  450. return nullptr;
  451. }
  452. return llvm::MemoryBuffer::getMemBufferCopy(
  453. HeaderContents, Module::getModuleInputBufferName());
  454. }
  455. bool FrontendAction::BeginSourceFile(CompilerInstance &CI,
  456. const FrontendInputFile &RealInput) {
  457. FrontendInputFile Input(RealInput);
  458. assert(!Instance && "Already processing a source file!");
  459. assert(!Input.isEmpty() && "Unexpected empty filename!");
  460. setCurrentInput(Input);
  461. setCompilerInstance(&CI);
  462. StringRef InputFile = Input.getFile();
  463. bool HasBegunSourceFile = false;
  464. bool ReplayASTFile = Input.getKind().getFormat() == InputKind::Precompiled &&
  465. usesPreprocessorOnly();
  466. if (!BeginInvocation(CI))
  467. goto failure;
  468. // If we're replaying the build of an AST file, import it and set up
  469. // the initial state from its build.
  470. if (ReplayASTFile) {
  471. IntrusiveRefCntPtr<DiagnosticsEngine> Diags(&CI.getDiagnostics());
  472. // The AST unit populates its own diagnostics engine rather than ours.
  473. IntrusiveRefCntPtr<DiagnosticsEngine> ASTDiags(
  474. new DiagnosticsEngine(Diags->getDiagnosticIDs(),
  475. &Diags->getDiagnosticOptions()));
  476. ASTDiags->setClient(Diags->getClient(), /*OwnsClient*/false);
  477. std::unique_ptr<ASTUnit> AST = ASTUnit::LoadFromASTFile(
  478. InputFile, CI.getPCHContainerReader(), ASTDiags, CI.getFileSystemOpts(),
  479. CI.getCodeGenOpts().DebugTypeExtRefs);
  480. if (!AST)
  481. goto failure;
  482. // Options relating to how we treat the input (but not what we do with it)
  483. // are inherited from the AST unit.
  484. CI.getLangOpts() = AST->getLangOpts();
  485. // Preload all the module files loaded transitively by the AST unit.
  486. if (auto ASTReader = AST->getASTReader()) {
  487. auto &MM = ASTReader->getModuleManager();
  488. for (ModuleFile &MF : MM)
  489. if (&MF != &MM.getPrimaryModule())
  490. CI.getFrontendOpts().ModuleFiles.push_back(MF.FileName);
  491. }
  492. // Set the shared objects, these are reset when we finish processing the
  493. // file, otherwise the CompilerInstance will happily destroy them.
  494. CI.setFileManager(&AST->getFileManager());
  495. CI.createSourceManager(CI.getFileManager());
  496. CI.getSourceManager().initializeForReplay(AST->getSourceManager());
  497. CI.createPreprocessor(getTranslationUnitKind());
  498. // Set up the input file for replay purposes.
  499. auto Kind = AST->getInputKind();
  500. if (Kind.getFormat() == InputKind::ModuleMap) {
  501. Module *ASTModule =
  502. AST->getPreprocessor().getHeaderSearchInfo().lookupModule(
  503. AST->getLangOpts().CurrentModule, /*AllowSearch*/ false);
  504. Input = FrontendInputFile(ASTModule->PresumedModuleMapFile, Kind);
  505. } else {
  506. auto &SM = CI.getSourceManager();
  507. FileID ID = SM.getMainFileID();
  508. if (auto *File = SM.getFileEntryForID(ID))
  509. Input = FrontendInputFile(File->getName(), Kind);
  510. else
  511. Input = FrontendInputFile(SM.getBuffer(ID), Kind);
  512. }
  513. setCurrentInput(Input, std::move(AST));
  514. }
  515. // AST files follow a very different path, since they share objects via the
  516. // AST unit.
  517. if (Input.getKind().getFormat() == InputKind::Precompiled) {
  518. assert(!usesPreprocessorOnly() && "this case was handled above");
  519. assert(hasASTFileSupport() &&
  520. "This action does not have AST file support!");
  521. IntrusiveRefCntPtr<DiagnosticsEngine> Diags(&CI.getDiagnostics());
  522. std::unique_ptr<ASTUnit> AST = ASTUnit::LoadFromASTFile(
  523. InputFile, CI.getPCHContainerReader(), Diags, CI.getFileSystemOpts(),
  524. CI.getCodeGenOpts().DebugTypeExtRefs);
  525. if (!AST)
  526. goto failure;
  527. // Inform the diagnostic client we are processing a source file.
  528. CI.getDiagnosticClient().BeginSourceFile(CI.getLangOpts(), nullptr);
  529. HasBegunSourceFile = true;
  530. // Set the shared objects, these are reset when we finish processing the
  531. // file, otherwise the CompilerInstance will happily destroy them.
  532. CI.setFileManager(&AST->getFileManager());
  533. CI.setSourceManager(&AST->getSourceManager());
  534. CI.setPreprocessor(AST->getPreprocessorPtr());
  535. Preprocessor &PP = CI.getPreprocessor();
  536. PP.getBuiltinInfo().initializeBuiltins(PP.getIdentifierTable(),
  537. PP.getLangOpts());
  538. CI.setASTContext(&AST->getASTContext());
  539. setCurrentInput(Input, std::move(AST));
  540. // Initialize the action.
  541. if (!BeginSourceFileAction(CI, InputFile))
  542. goto failure;
  543. // Create the AST consumer.
  544. CI.setASTConsumer(CreateWrappedASTConsumer(CI, InputFile));
  545. if (!CI.hasASTConsumer())
  546. goto failure;
  547. return true;
  548. }
  549. if (!CI.hasVirtualFileSystem()) {
  550. if (IntrusiveRefCntPtr<vfs::FileSystem> VFS =
  551. createVFSFromCompilerInvocation(CI.getInvocation(),
  552. CI.getDiagnostics()))
  553. CI.setVirtualFileSystem(VFS);
  554. else
  555. goto failure;
  556. }
  557. // Set up the file and source managers, if needed.
  558. if (!CI.hasFileManager())
  559. CI.createFileManager();
  560. if (!CI.hasSourceManager())
  561. CI.createSourceManager(CI.getFileManager());
  562. // Set up embedding for any specified files. Do this before we load any
  563. // source files, including the primary module map for the compilation.
  564. for (const auto &F : CI.getFrontendOpts().ModulesEmbedFiles) {
  565. if (const auto *FE = CI.getFileManager().getFile(F, /*openFile*/true))
  566. CI.getSourceManager().setFileIsTransient(FE);
  567. else
  568. CI.getDiagnostics().Report(diag::err_modules_embed_file_not_found) << F;
  569. }
  570. if (CI.getFrontendOpts().ModulesEmbedAllFiles)
  571. CI.getSourceManager().setAllFilesAreTransient(true);
  572. // IR files bypass the rest of initialization.
  573. if (Input.getKind().getLanguage() == InputKind::LLVM_IR) {
  574. assert(hasIRSupport() &&
  575. "This action does not have IR file support!");
  576. // Inform the diagnostic client we are processing a source file.
  577. CI.getDiagnosticClient().BeginSourceFile(CI.getLangOpts(), nullptr);
  578. HasBegunSourceFile = true;
  579. // Initialize the action.
  580. if (!BeginSourceFileAction(CI, InputFile))
  581. goto failure;
  582. // Initialize the main file entry.
  583. if (!CI.InitializeSourceManager(CurrentInput))
  584. goto failure;
  585. return true;
  586. }
  587. // If the implicit PCH include is actually a directory, rather than
  588. // a single file, search for a suitable PCH file in that directory.
  589. if (!CI.getPreprocessorOpts().ImplicitPCHInclude.empty()) {
  590. FileManager &FileMgr = CI.getFileManager();
  591. PreprocessorOptions &PPOpts = CI.getPreprocessorOpts();
  592. StringRef PCHInclude = PPOpts.ImplicitPCHInclude;
  593. std::string SpecificModuleCachePath = CI.getSpecificModuleCachePath();
  594. if (const DirectoryEntry *PCHDir = FileMgr.getDirectory(PCHInclude)) {
  595. std::error_code EC;
  596. SmallString<128> DirNative;
  597. llvm::sys::path::native(PCHDir->getName(), DirNative);
  598. bool Found = false;
  599. vfs::FileSystem &FS = *FileMgr.getVirtualFileSystem();
  600. for (vfs::directory_iterator Dir = FS.dir_begin(DirNative, EC), DirEnd;
  601. Dir != DirEnd && !EC; Dir.increment(EC)) {
  602. // Check whether this is an acceptable AST file.
  603. if (ASTReader::isAcceptableASTFile(
  604. Dir->getName(), FileMgr, CI.getPCHContainerReader(),
  605. CI.getLangOpts(), CI.getTargetOpts(), CI.getPreprocessorOpts(),
  606. SpecificModuleCachePath)) {
  607. PPOpts.ImplicitPCHInclude = Dir->getName();
  608. Found = true;
  609. break;
  610. }
  611. }
  612. if (!Found) {
  613. CI.getDiagnostics().Report(diag::err_fe_no_pch_in_dir) << PCHInclude;
  614. goto failure;
  615. }
  616. }
  617. }
  618. // Set up the preprocessor if needed. When parsing model files the
  619. // preprocessor of the original source is reused.
  620. if (!isModelParsingAction())
  621. CI.createPreprocessor(getTranslationUnitKind());
  622. // Inform the diagnostic client we are processing a source file.
  623. CI.getDiagnosticClient().BeginSourceFile(CI.getLangOpts(),
  624. &CI.getPreprocessor());
  625. HasBegunSourceFile = true;
  626. // Initialize the main file entry.
  627. if (!CI.InitializeSourceManager(Input))
  628. goto failure;
  629. // For module map files, we first parse the module map and synthesize a
  630. // "<module-includes>" buffer before more conventional processing.
  631. if (Input.getKind().getFormat() == InputKind::ModuleMap) {
  632. CI.getLangOpts().setCompilingModule(LangOptions::CMK_ModuleMap);
  633. std::string PresumedModuleMapFile;
  634. unsigned OffsetToContents;
  635. if (loadModuleMapForModuleBuild(CI, Input.isSystem(),
  636. Input.isPreprocessed(),
  637. PresumedModuleMapFile, OffsetToContents))
  638. goto failure;
  639. auto *CurrentModule = prepareToBuildModule(CI, Input.getFile());
  640. if (!CurrentModule)
  641. goto failure;
  642. CurrentModule->PresumedModuleMapFile = PresumedModuleMapFile;
  643. if (OffsetToContents)
  644. // If the module contents are in the same file, skip to them.
  645. CI.getPreprocessor().setSkipMainFilePreamble(OffsetToContents, true);
  646. else {
  647. // Otherwise, convert the module description to a suitable input buffer.
  648. auto Buffer = getInputBufferForModule(CI, CurrentModule);
  649. if (!Buffer)
  650. goto failure;
  651. // Reinitialize the main file entry to refer to the new input.
  652. if (!CI.InitializeSourceManager(FrontendInputFile(
  653. Buffer.release(), Input.getKind().withFormat(InputKind::Source),
  654. CurrentModule->IsSystem)))
  655. goto failure;
  656. }
  657. }
  658. // Initialize the action.
  659. if (!BeginSourceFileAction(CI, InputFile))
  660. goto failure;
  661. // Create the AST context and consumer unless this is a preprocessor only
  662. // action.
  663. if (!usesPreprocessorOnly()) {
  664. // Parsing a model file should reuse the existing ASTContext.
  665. if (!isModelParsingAction())
  666. CI.createASTContext();
  667. // For preprocessed files, check if the first line specifies the original
  668. // source file name with a linemarker.
  669. std::string PresumedInputFile = InputFile;
  670. if (Input.isPreprocessed())
  671. ReadOriginalFileName(CI, PresumedInputFile);
  672. std::unique_ptr<ASTConsumer> Consumer =
  673. CreateWrappedASTConsumer(CI, PresumedInputFile);
  674. if (!Consumer)
  675. goto failure;
  676. // FIXME: should not overwrite ASTMutationListener when parsing model files?
  677. if (!isModelParsingAction())
  678. CI.getASTContext().setASTMutationListener(Consumer->GetASTMutationListener());
  679. if (!CI.getPreprocessorOpts().ChainedIncludes.empty()) {
  680. // Convert headers to PCH and chain them.
  681. IntrusiveRefCntPtr<ExternalSemaSource> source, FinalReader;
  682. source = createChainedIncludesSource(CI, FinalReader);
  683. if (!source)
  684. goto failure;
  685. CI.setModuleManager(static_cast<ASTReader *>(FinalReader.get()));
  686. CI.getASTContext().setExternalSource(source);
  687. } else if (CI.getLangOpts().Modules ||
  688. !CI.getPreprocessorOpts().ImplicitPCHInclude.empty()) {
  689. // Use PCM or PCH.
  690. assert(hasPCHSupport() && "This action does not have PCH support!");
  691. ASTDeserializationListener *DeserialListener =
  692. Consumer->GetASTDeserializationListener();
  693. bool DeleteDeserialListener = false;
  694. if (CI.getPreprocessorOpts().DumpDeserializedPCHDecls) {
  695. DeserialListener = new DeserializedDeclsDumper(DeserialListener,
  696. DeleteDeserialListener);
  697. DeleteDeserialListener = true;
  698. }
  699. if (!CI.getPreprocessorOpts().DeserializedPCHDeclsToErrorOn.empty()) {
  700. DeserialListener = new DeserializedDeclsChecker(
  701. CI.getASTContext(),
  702. CI.getPreprocessorOpts().DeserializedPCHDeclsToErrorOn,
  703. DeserialListener, DeleteDeserialListener);
  704. DeleteDeserialListener = true;
  705. }
  706. if (!CI.getPreprocessorOpts().ImplicitPCHInclude.empty()) {
  707. CI.createPCHExternalASTSource(
  708. CI.getPreprocessorOpts().ImplicitPCHInclude,
  709. CI.getPreprocessorOpts().DisablePCHValidation,
  710. CI.getPreprocessorOpts().AllowPCHWithCompilerErrors, DeserialListener,
  711. DeleteDeserialListener);
  712. if (!CI.getASTContext().getExternalSource())
  713. goto failure;
  714. }
  715. // If modules are enabled, create the module manager before creating
  716. // any builtins, so that all declarations know that they might be
  717. // extended by an external source.
  718. if (CI.getLangOpts().Modules || !CI.hasASTContext() ||
  719. !CI.getASTContext().getExternalSource()) {
  720. CI.createModuleManager();
  721. CI.getModuleManager()->setDeserializationListener(DeserialListener,
  722. DeleteDeserialListener);
  723. }
  724. }
  725. CI.setASTConsumer(std::move(Consumer));
  726. if (!CI.hasASTConsumer())
  727. goto failure;
  728. }
  729. // Initialize built-in info as long as we aren't using an external AST
  730. // source.
  731. if (CI.getLangOpts().Modules || !CI.hasASTContext() ||
  732. !CI.getASTContext().getExternalSource()) {
  733. Preprocessor &PP = CI.getPreprocessor();
  734. PP.getBuiltinInfo().initializeBuiltins(PP.getIdentifierTable(),
  735. PP.getLangOpts());
  736. } else {
  737. // FIXME: If this is a problem, recover from it by creating a multiplex
  738. // source.
  739. assert((!CI.getLangOpts().Modules || CI.getModuleManager()) &&
  740. "modules enabled but created an external source that "
  741. "doesn't support modules");
  742. }
  743. // If we were asked to load any module map files, do so now.
  744. for (const auto &Filename : CI.getFrontendOpts().ModuleMapFiles) {
  745. if (auto *File = CI.getFileManager().getFile(Filename))
  746. CI.getPreprocessor().getHeaderSearchInfo().loadModuleMapFile(
  747. File, /*IsSystem*/false);
  748. else
  749. CI.getDiagnostics().Report(diag::err_module_map_not_found) << Filename;
  750. }
  751. // If we were asked to load any module files, do so now.
  752. for (const auto &ModuleFile : CI.getFrontendOpts().ModuleFiles)
  753. if (!CI.loadModuleFile(ModuleFile))
  754. goto failure;
  755. // If there is a layout overrides file, attach an external AST source that
  756. // provides the layouts from that file.
  757. if (!CI.getFrontendOpts().OverrideRecordLayoutsFile.empty() &&
  758. CI.hasASTContext() && !CI.getASTContext().getExternalSource()) {
  759. IntrusiveRefCntPtr<ExternalASTSource>
  760. Override(new LayoutOverrideSource(
  761. CI.getFrontendOpts().OverrideRecordLayoutsFile));
  762. CI.getASTContext().setExternalSource(Override);
  763. }
  764. return true;
  765. // If we failed, reset state since the client will not end up calling the
  766. // matching EndSourceFile().
  767. failure:
  768. if (HasBegunSourceFile)
  769. CI.getDiagnosticClient().EndSourceFile();
  770. CI.clearOutputFiles(/*EraseFiles=*/true);
  771. CI.getLangOpts().setCompilingModule(LangOptions::CMK_None);
  772. setCurrentInput(FrontendInputFile());
  773. setCompilerInstance(nullptr);
  774. return false;
  775. }
  776. bool FrontendAction::Execute() {
  777. CompilerInstance &CI = getCompilerInstance();
  778. if (CI.hasFrontendTimer()) {
  779. llvm::TimeRegion Timer(CI.getFrontendTimer());
  780. ExecuteAction();
  781. }
  782. else ExecuteAction();
  783. // If we are supposed to rebuild the global module index, do so now unless
  784. // there were any module-build failures.
  785. if (CI.shouldBuildGlobalModuleIndex() && CI.hasFileManager() &&
  786. CI.hasPreprocessor()) {
  787. StringRef Cache =
  788. CI.getPreprocessor().getHeaderSearchInfo().getModuleCachePath();
  789. if (!Cache.empty())
  790. GlobalModuleIndex::writeIndex(CI.getFileManager(),
  791. CI.getPCHContainerReader(), Cache);
  792. }
  793. return true;
  794. }
  795. void FrontendAction::EndSourceFile() {
  796. CompilerInstance &CI = getCompilerInstance();
  797. // Inform the diagnostic client we are done with this source file.
  798. CI.getDiagnosticClient().EndSourceFile();
  799. // Inform the preprocessor we are done.
  800. if (CI.hasPreprocessor())
  801. CI.getPreprocessor().EndSourceFile();
  802. // Finalize the action.
  803. EndSourceFileAction();
  804. // Sema references the ast consumer, so reset sema first.
  805. //
  806. // FIXME: There is more per-file stuff we could just drop here?
  807. bool DisableFree = CI.getFrontendOpts().DisableFree;
  808. if (DisableFree) {
  809. CI.resetAndLeakSema();
  810. CI.resetAndLeakASTContext();
  811. BuryPointer(CI.takeASTConsumer().get());
  812. } else {
  813. CI.setSema(nullptr);
  814. CI.setASTContext(nullptr);
  815. CI.setASTConsumer(nullptr);
  816. }
  817. if (CI.getFrontendOpts().ShowStats) {
  818. llvm::errs() << "\nSTATISTICS FOR '" << getCurrentFile() << "':\n";
  819. CI.getPreprocessor().PrintStats();
  820. CI.getPreprocessor().getIdentifierTable().PrintStats();
  821. CI.getPreprocessor().getHeaderSearchInfo().PrintStats();
  822. CI.getSourceManager().PrintStats();
  823. llvm::errs() << "\n";
  824. }
  825. // Cleanup the output streams, and erase the output files if instructed by the
  826. // FrontendAction.
  827. CI.clearOutputFiles(/*EraseFiles=*/shouldEraseOutputFiles());
  828. if (isCurrentFileAST()) {
  829. if (DisableFree) {
  830. CI.resetAndLeakPreprocessor();
  831. CI.resetAndLeakSourceManager();
  832. CI.resetAndLeakFileManager();
  833. BuryPointer(CurrentASTUnit.release());
  834. } else {
  835. CI.setPreprocessor(nullptr);
  836. CI.setSourceManager(nullptr);
  837. CI.setFileManager(nullptr);
  838. }
  839. }
  840. setCompilerInstance(nullptr);
  841. setCurrentInput(FrontendInputFile());
  842. CI.getLangOpts().setCompilingModule(LangOptions::CMK_None);
  843. }
  844. bool FrontendAction::shouldEraseOutputFiles() {
  845. return getCompilerInstance().getDiagnostics().hasErrorOccurred();
  846. }
  847. //===----------------------------------------------------------------------===//
  848. // Utility Actions
  849. //===----------------------------------------------------------------------===//
  850. void ASTFrontendAction::ExecuteAction() {
  851. CompilerInstance &CI = getCompilerInstance();
  852. if (!CI.hasPreprocessor())
  853. return;
  854. // FIXME: Move the truncation aspect of this into Sema, we delayed this till
  855. // here so the source manager would be initialized.
  856. if (hasCodeCompletionSupport() &&
  857. !CI.getFrontendOpts().CodeCompletionAt.FileName.empty())
  858. CI.createCodeCompletionConsumer();
  859. // Use a code completion consumer?
  860. CodeCompleteConsumer *CompletionConsumer = nullptr;
  861. if (CI.hasCodeCompletionConsumer())
  862. CompletionConsumer = &CI.getCodeCompletionConsumer();
  863. if (!CI.hasSema())
  864. CI.createSema(getTranslationUnitKind(), CompletionConsumer);
  865. ParseAST(CI.getSema(), CI.getFrontendOpts().ShowStats,
  866. CI.getFrontendOpts().SkipFunctionBodies);
  867. }
  868. void PluginASTAction::anchor() { }
  869. std::unique_ptr<ASTConsumer>
  870. PreprocessorFrontendAction::CreateASTConsumer(CompilerInstance &CI,
  871. StringRef InFile) {
  872. llvm_unreachable("Invalid CreateASTConsumer on preprocessor action!");
  873. }
  874. std::unique_ptr<ASTConsumer>
  875. WrapperFrontendAction::CreateASTConsumer(CompilerInstance &CI,
  876. StringRef InFile) {
  877. return WrappedAction->CreateASTConsumer(CI, InFile);
  878. }
  879. bool WrapperFrontendAction::BeginInvocation(CompilerInstance &CI) {
  880. return WrappedAction->BeginInvocation(CI);
  881. }
  882. bool WrapperFrontendAction::BeginSourceFileAction(CompilerInstance &CI,
  883. StringRef Filename) {
  884. WrappedAction->setCurrentInput(getCurrentInput());
  885. WrappedAction->setCompilerInstance(&CI);
  886. auto Ret = WrappedAction->BeginSourceFileAction(CI, Filename);
  887. // BeginSourceFileAction may change CurrentInput, e.g. during module builds.
  888. setCurrentInput(WrappedAction->getCurrentInput());
  889. return Ret;
  890. }
  891. void WrapperFrontendAction::ExecuteAction() {
  892. WrappedAction->ExecuteAction();
  893. }
  894. void WrapperFrontendAction::EndSourceFileAction() {
  895. WrappedAction->EndSourceFileAction();
  896. }
  897. bool WrapperFrontendAction::usesPreprocessorOnly() const {
  898. return WrappedAction->usesPreprocessorOnly();
  899. }
  900. TranslationUnitKind WrapperFrontendAction::getTranslationUnitKind() {
  901. return WrappedAction->getTranslationUnitKind();
  902. }
  903. bool WrapperFrontendAction::hasPCHSupport() const {
  904. return WrappedAction->hasPCHSupport();
  905. }
  906. bool WrapperFrontendAction::hasASTFileSupport() const {
  907. return WrappedAction->hasASTFileSupport();
  908. }
  909. bool WrapperFrontendAction::hasIRSupport() const {
  910. return WrappedAction->hasIRSupport();
  911. }
  912. bool WrapperFrontendAction::hasCodeCompletionSupport() const {
  913. return WrappedAction->hasCodeCompletionSupport();
  914. }
  915. WrapperFrontendAction::WrapperFrontendAction(
  916. std::unique_ptr<FrontendAction> WrappedAction)
  917. : WrappedAction(std::move(WrappedAction)) {}