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