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