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