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, SourceLocation(), /*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, SourceLocation(),
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, SourceLocation(),
634               /*AllowSearch*/ false);
635       assert(ASTModule && "module file does not define its own module");
636       Input = FrontendInputFile(ASTModule->PresumedModuleMapFile, Kind);
637     } else {
638       auto &OldSM = AST->getSourceManager();
639       FileID ID = OldSM.getMainFileID();
640       if (auto *File = OldSM.getFileEntryForID(ID))
641         Input = FrontendInputFile(File->getName(), Kind);
642       else
643         Input = FrontendInputFile(OldSM.getBufferOrFake(ID), Kind);
644     }
645     setCurrentInput(Input, std::move(AST));
646   }
647 
648   // AST files follow a very different path, since they share objects via the
649   // AST unit.
650   if (Input.getKind().getFormat() == InputKind::Precompiled) {
651     assert(!usesPreprocessorOnly() && "this case was handled above");
652     assert(hasASTFileSupport() &&
653            "This action does not have AST file support!");
654 
655     IntrusiveRefCntPtr<DiagnosticsEngine> Diags(&CI.getDiagnostics());
656 
657     // FIXME: What if the input is a memory buffer?
658     StringRef InputFile = Input.getFile();
659 
660     std::unique_ptr<ASTUnit> AST = ASTUnit::LoadFromASTFile(
661         std::string(InputFile), CI.getPCHContainerReader(),
662         ASTUnit::LoadEverything, Diags, CI.getFileSystemOpts(),
663         CI.getCodeGenOpts().DebugTypeExtRefs);
664 
665     if (!AST)
666       return false;
667 
668     // Inform the diagnostic client we are processing a source file.
669     CI.getDiagnosticClient().BeginSourceFile(CI.getLangOpts(), nullptr);
670     HasBegunSourceFile = true;
671 
672     // Set the shared objects, these are reset when we finish processing the
673     // file, otherwise the CompilerInstance will happily destroy them.
674     CI.setFileManager(&AST->getFileManager());
675     CI.setSourceManager(&AST->getSourceManager());
676     CI.setPreprocessor(AST->getPreprocessorPtr());
677     Preprocessor &PP = CI.getPreprocessor();
678     PP.getBuiltinInfo().initializeBuiltins(PP.getIdentifierTable(),
679                                            PP.getLangOpts());
680     CI.setASTContext(&AST->getASTContext());
681 
682     setCurrentInput(Input, std::move(AST));
683 
684     // Initialize the action.
685     if (!BeginSourceFileAction(CI))
686       return false;
687 
688     // Create the AST consumer.
689     CI.setASTConsumer(CreateWrappedASTConsumer(CI, InputFile));
690     if (!CI.hasASTConsumer())
691       return false;
692 
693     FailureCleanup.release();
694     return true;
695   }
696 
697   // Set up the file and source managers, if needed.
698   if (!CI.hasFileManager()) {
699     if (!CI.createFileManager()) {
700       return false;
701     }
702   }
703   if (!CI.hasSourceManager())
704     CI.createSourceManager(CI.getFileManager());
705 
706   // Set up embedding for any specified files. Do this before we load any
707   // source files, including the primary module map for the compilation.
708   for (const auto &F : CI.getFrontendOpts().ModulesEmbedFiles) {
709     if (auto FE = CI.getFileManager().getFile(F, /*openFile*/true))
710       CI.getSourceManager().setFileIsTransient(*FE);
711     else
712       CI.getDiagnostics().Report(diag::err_modules_embed_file_not_found) << F;
713   }
714   if (CI.getFrontendOpts().ModulesEmbedAllFiles)
715     CI.getSourceManager().setAllFilesAreTransient(true);
716 
717   // IR files bypass the rest of initialization.
718   if (Input.getKind().getLanguage() == Language::LLVM_IR) {
719     assert(hasIRSupport() &&
720            "This action does not have IR file support!");
721 
722     // Inform the diagnostic client we are processing a source file.
723     CI.getDiagnosticClient().BeginSourceFile(CI.getLangOpts(), nullptr);
724     HasBegunSourceFile = true;
725 
726     // Initialize the action.
727     if (!BeginSourceFileAction(CI))
728       return false;
729 
730     // Initialize the main file entry.
731     if (!CI.InitializeSourceManager(CurrentInput))
732       return false;
733 
734     FailureCleanup.release();
735     return true;
736   }
737 
738   // If the implicit PCH include is actually a directory, rather than
739   // a single file, search for a suitable PCH file in that directory.
740   if (!CI.getPreprocessorOpts().ImplicitPCHInclude.empty()) {
741     FileManager &FileMgr = CI.getFileManager();
742     PreprocessorOptions &PPOpts = CI.getPreprocessorOpts();
743     StringRef PCHInclude = PPOpts.ImplicitPCHInclude;
744     std::string SpecificModuleCachePath = CI.getSpecificModuleCachePath();
745     if (auto PCHDir = FileMgr.getDirectory(PCHInclude)) {
746       std::error_code EC;
747       SmallString<128> DirNative;
748       llvm::sys::path::native((*PCHDir)->getName(), DirNative);
749       bool Found = false;
750       llvm::vfs::FileSystem &FS = FileMgr.getVirtualFileSystem();
751       for (llvm::vfs::directory_iterator Dir = FS.dir_begin(DirNative, EC),
752                                          DirEnd;
753            Dir != DirEnd && !EC; Dir.increment(EC)) {
754         // Check whether this is an acceptable AST file.
755         if (ASTReader::isAcceptableASTFile(
756                 Dir->path(), FileMgr, CI.getPCHContainerReader(),
757                 CI.getLangOpts(), CI.getTargetOpts(), CI.getPreprocessorOpts(),
758                 SpecificModuleCachePath)) {
759           PPOpts.ImplicitPCHInclude = std::string(Dir->path());
760           Found = true;
761           break;
762         }
763       }
764 
765       if (!Found) {
766         CI.getDiagnostics().Report(diag::err_fe_no_pch_in_dir) << PCHInclude;
767         return false;
768       }
769     }
770   }
771 
772   // Set up the preprocessor if needed. When parsing model files the
773   // preprocessor of the original source is reused.
774   if (!isModelParsingAction())
775     CI.createPreprocessor(getTranslationUnitKind());
776 
777   // Inform the diagnostic client we are processing a source file.
778   CI.getDiagnosticClient().BeginSourceFile(CI.getLangOpts(),
779                                            &CI.getPreprocessor());
780   HasBegunSourceFile = true;
781 
782   // Initialize the main file entry.
783   if (!CI.InitializeSourceManager(Input))
784     return false;
785 
786   // For module map files, we first parse the module map and synthesize a
787   // "<module-includes>" buffer before more conventional processing.
788   if (Input.getKind().getFormat() == InputKind::ModuleMap) {
789     CI.getLangOpts().setCompilingModule(LangOptions::CMK_ModuleMap);
790 
791     std::string PresumedModuleMapFile;
792     unsigned OffsetToContents;
793     if (loadModuleMapForModuleBuild(CI, Input.isSystem(),
794                                     Input.isPreprocessed(),
795                                     PresumedModuleMapFile, OffsetToContents))
796       return false;
797 
798     auto *CurrentModule = prepareToBuildModule(CI, Input.getFile());
799     if (!CurrentModule)
800       return false;
801 
802     CurrentModule->PresumedModuleMapFile = PresumedModuleMapFile;
803 
804     if (OffsetToContents)
805       // If the module contents are in the same file, skip to them.
806       CI.getPreprocessor().setSkipMainFilePreamble(OffsetToContents, true);
807     else {
808       // Otherwise, convert the module description to a suitable input buffer.
809       auto Buffer = getInputBufferForModule(CI, CurrentModule);
810       if (!Buffer)
811         return false;
812 
813       // Reinitialize the main file entry to refer to the new input.
814       auto Kind = CurrentModule->IsSystem ? SrcMgr::C_System : SrcMgr::C_User;
815       auto &SourceMgr = CI.getSourceManager();
816       auto BufferID = SourceMgr.createFileID(std::move(Buffer), Kind);
817       assert(BufferID.isValid() && "couldn't create module buffer ID");
818       SourceMgr.setMainFileID(BufferID);
819     }
820   }
821 
822   // Initialize the action.
823   if (!BeginSourceFileAction(CI))
824     return false;
825 
826   // If we were asked to load any module map files, do so now.
827   for (const auto &Filename : CI.getFrontendOpts().ModuleMapFiles) {
828     if (auto File = CI.getFileManager().getFile(Filename))
829       CI.getPreprocessor().getHeaderSearchInfo().loadModuleMapFile(
830           *File, /*IsSystem*/false);
831     else
832       CI.getDiagnostics().Report(diag::err_module_map_not_found) << Filename;
833   }
834 
835   // Add a module declaration scope so that modules from -fmodule-map-file
836   // arguments may shadow modules found implicitly in search paths.
837   CI.getPreprocessor()
838       .getHeaderSearchInfo()
839       .getModuleMap()
840       .finishModuleDeclarationScope();
841 
842   // Create the AST context and consumer unless this is a preprocessor only
843   // action.
844   if (!usesPreprocessorOnly()) {
845     // Parsing a model file should reuse the existing ASTContext.
846     if (!isModelParsingAction())
847       CI.createASTContext();
848 
849     // For preprocessed files, check if the first line specifies the original
850     // source file name with a linemarker.
851     std::string PresumedInputFile = std::string(getCurrentFileOrBufferName());
852     if (Input.isPreprocessed())
853       ReadOriginalFileName(CI, PresumedInputFile);
854 
855     std::unique_ptr<ASTConsumer> Consumer =
856         CreateWrappedASTConsumer(CI, PresumedInputFile);
857     if (!Consumer)
858       return false;
859 
860     // FIXME: should not overwrite ASTMutationListener when parsing model files?
861     if (!isModelParsingAction())
862       CI.getASTContext().setASTMutationListener(Consumer->GetASTMutationListener());
863 
864     if (!CI.getPreprocessorOpts().ChainedIncludes.empty()) {
865       // Convert headers to PCH and chain them.
866       IntrusiveRefCntPtr<ExternalSemaSource> source, FinalReader;
867       source = createChainedIncludesSource(CI, FinalReader);
868       if (!source)
869         return false;
870       CI.setASTReader(static_cast<ASTReader *>(FinalReader.get()));
871       CI.getASTContext().setExternalSource(source);
872     } else if (CI.getLangOpts().Modules ||
873                !CI.getPreprocessorOpts().ImplicitPCHInclude.empty()) {
874       // Use PCM or PCH.
875       assert(hasPCHSupport() && "This action does not have PCH support!");
876       ASTDeserializationListener *DeserialListener =
877           Consumer->GetASTDeserializationListener();
878       bool DeleteDeserialListener = false;
879       if (CI.getPreprocessorOpts().DumpDeserializedPCHDecls) {
880         DeserialListener = new DeserializedDeclsDumper(DeserialListener,
881                                                        DeleteDeserialListener);
882         DeleteDeserialListener = true;
883       }
884       if (!CI.getPreprocessorOpts().DeserializedPCHDeclsToErrorOn.empty()) {
885         DeserialListener = new DeserializedDeclsChecker(
886             CI.getASTContext(),
887             CI.getPreprocessorOpts().DeserializedPCHDeclsToErrorOn,
888             DeserialListener, DeleteDeserialListener);
889         DeleteDeserialListener = true;
890       }
891       if (!CI.getPreprocessorOpts().ImplicitPCHInclude.empty()) {
892         CI.createPCHExternalASTSource(
893             CI.getPreprocessorOpts().ImplicitPCHInclude,
894             CI.getPreprocessorOpts().DisablePCHOrModuleValidation,
895             CI.getPreprocessorOpts().AllowPCHWithCompilerErrors,
896             DeserialListener, DeleteDeserialListener);
897         if (!CI.getASTContext().getExternalSource())
898           return false;
899       }
900       // If modules are enabled, create the AST reader before creating
901       // any builtins, so that all declarations know that they might be
902       // extended by an external source.
903       if (CI.getLangOpts().Modules || !CI.hasASTContext() ||
904           !CI.getASTContext().getExternalSource()) {
905         CI.createASTReader();
906         CI.getASTReader()->setDeserializationListener(DeserialListener,
907                                                       DeleteDeserialListener);
908       }
909     }
910 
911     CI.setASTConsumer(std::move(Consumer));
912     if (!CI.hasASTConsumer())
913       return false;
914   }
915 
916   // Initialize built-in info as long as we aren't using an external AST
917   // source.
918   if (CI.getLangOpts().Modules || !CI.hasASTContext() ||
919       !CI.getASTContext().getExternalSource()) {
920     Preprocessor &PP = CI.getPreprocessor();
921     PP.getBuiltinInfo().initializeBuiltins(PP.getIdentifierTable(),
922                                            PP.getLangOpts());
923   } else {
924     // FIXME: If this is a problem, recover from it by creating a multiplex
925     // source.
926     assert((!CI.getLangOpts().Modules || CI.getASTReader()) &&
927            "modules enabled but created an external source that "
928            "doesn't support modules");
929   }
930 
931   // If we were asked to load any module files, do so now.
932   for (const auto &ModuleFile : CI.getFrontendOpts().ModuleFiles)
933     if (!CI.loadModuleFile(ModuleFile))
934       return false;
935 
936   // If there is a layout overrides file, attach an external AST source that
937   // provides the layouts from that file.
938   if (!CI.getFrontendOpts().OverrideRecordLayoutsFile.empty() &&
939       CI.hasASTContext() && !CI.getASTContext().getExternalSource()) {
940     IntrusiveRefCntPtr<ExternalASTSource>
941       Override(new LayoutOverrideSource(
942                      CI.getFrontendOpts().OverrideRecordLayoutsFile));
943     CI.getASTContext().setExternalSource(Override);
944   }
945 
946   FailureCleanup.release();
947   return true;
948 }
949 
950 llvm::Error FrontendAction::Execute() {
951   CompilerInstance &CI = getCompilerInstance();
952 
953   if (CI.hasFrontendTimer()) {
954     llvm::TimeRegion Timer(CI.getFrontendTimer());
955     ExecuteAction();
956   }
957   else ExecuteAction();
958 
959   // If we are supposed to rebuild the global module index, do so now unless
960   // there were any module-build failures.
961   if (CI.shouldBuildGlobalModuleIndex() && CI.hasFileManager() &&
962       CI.hasPreprocessor()) {
963     StringRef Cache =
964         CI.getPreprocessor().getHeaderSearchInfo().getModuleCachePath();
965     if (!Cache.empty()) {
966       if (llvm::Error Err = GlobalModuleIndex::writeIndex(
967               CI.getFileManager(), CI.getPCHContainerReader(), Cache)) {
968         // FIXME this drops the error on the floor, but
969         // Index/pch-from-libclang.c seems to rely on dropping at least some of
970         // the error conditions!
971         consumeError(std::move(Err));
972       }
973     }
974   }
975 
976   return llvm::Error::success();
977 }
978 
979 void FrontendAction::EndSourceFile() {
980   CompilerInstance &CI = getCompilerInstance();
981 
982   // Inform the diagnostic client we are done with this source file.
983   CI.getDiagnosticClient().EndSourceFile();
984 
985   // Inform the preprocessor we are done.
986   if (CI.hasPreprocessor())
987     CI.getPreprocessor().EndSourceFile();
988 
989   // Finalize the action.
990   EndSourceFileAction();
991 
992   // Sema references the ast consumer, so reset sema first.
993   //
994   // FIXME: There is more per-file stuff we could just drop here?
995   bool DisableFree = CI.getFrontendOpts().DisableFree;
996   if (DisableFree) {
997     CI.resetAndLeakSema();
998     CI.resetAndLeakASTContext();
999     llvm::BuryPointer(CI.takeASTConsumer().get());
1000   } else {
1001     CI.setSema(nullptr);
1002     CI.setASTContext(nullptr);
1003     CI.setASTConsumer(nullptr);
1004   }
1005 
1006   if (CI.getFrontendOpts().ShowStats) {
1007     llvm::errs() << "\nSTATISTICS FOR '" << getCurrentFile() << "':\n";
1008     CI.getPreprocessor().PrintStats();
1009     CI.getPreprocessor().getIdentifierTable().PrintStats();
1010     CI.getPreprocessor().getHeaderSearchInfo().PrintStats();
1011     CI.getSourceManager().PrintStats();
1012     llvm::errs() << "\n";
1013   }
1014 
1015   // Cleanup the output streams, and erase the output files if instructed by the
1016   // FrontendAction.
1017   CI.clearOutputFiles(/*EraseFiles=*/shouldEraseOutputFiles());
1018 
1019   if (isCurrentFileAST()) {
1020     if (DisableFree) {
1021       CI.resetAndLeakPreprocessor();
1022       CI.resetAndLeakSourceManager();
1023       CI.resetAndLeakFileManager();
1024       llvm::BuryPointer(std::move(CurrentASTUnit));
1025     } else {
1026       CI.setPreprocessor(nullptr);
1027       CI.setSourceManager(nullptr);
1028       CI.setFileManager(nullptr);
1029     }
1030   }
1031 
1032   setCompilerInstance(nullptr);
1033   setCurrentInput(FrontendInputFile());
1034   CI.getLangOpts().setCompilingModule(LangOptions::CMK_None);
1035 }
1036 
1037 bool FrontendAction::shouldEraseOutputFiles() {
1038   return getCompilerInstance().getDiagnostics().hasErrorOccurred();
1039 }
1040 
1041 //===----------------------------------------------------------------------===//
1042 // Utility Actions
1043 //===----------------------------------------------------------------------===//
1044 
1045 void ASTFrontendAction::ExecuteAction() {
1046   CompilerInstance &CI = getCompilerInstance();
1047   if (!CI.hasPreprocessor())
1048     return;
1049 
1050   // FIXME: Move the truncation aspect of this into Sema, we delayed this till
1051   // here so the source manager would be initialized.
1052   if (hasCodeCompletionSupport() &&
1053       !CI.getFrontendOpts().CodeCompletionAt.FileName.empty())
1054     CI.createCodeCompletionConsumer();
1055 
1056   // Use a code completion consumer?
1057   CodeCompleteConsumer *CompletionConsumer = nullptr;
1058   if (CI.hasCodeCompletionConsumer())
1059     CompletionConsumer = &CI.getCodeCompletionConsumer();
1060 
1061   if (!CI.hasSema())
1062     CI.createSema(getTranslationUnitKind(), CompletionConsumer);
1063 
1064   ParseAST(CI.getSema(), CI.getFrontendOpts().ShowStats,
1065            CI.getFrontendOpts().SkipFunctionBodies);
1066 }
1067 
1068 void PluginASTAction::anchor() { }
1069 
1070 std::unique_ptr<ASTConsumer>
1071 PreprocessorFrontendAction::CreateASTConsumer(CompilerInstance &CI,
1072                                               StringRef InFile) {
1073   llvm_unreachable("Invalid CreateASTConsumer on preprocessor action!");
1074 }
1075 
1076 bool WrapperFrontendAction::PrepareToExecuteAction(CompilerInstance &CI) {
1077   return WrappedAction->PrepareToExecuteAction(CI);
1078 }
1079 std::unique_ptr<ASTConsumer>
1080 WrapperFrontendAction::CreateASTConsumer(CompilerInstance &CI,
1081                                          StringRef InFile) {
1082   return WrappedAction->CreateASTConsumer(CI, InFile);
1083 }
1084 bool WrapperFrontendAction::BeginInvocation(CompilerInstance &CI) {
1085   return WrappedAction->BeginInvocation(CI);
1086 }
1087 bool WrapperFrontendAction::BeginSourceFileAction(CompilerInstance &CI) {
1088   WrappedAction->setCurrentInput(getCurrentInput());
1089   WrappedAction->setCompilerInstance(&CI);
1090   auto Ret = WrappedAction->BeginSourceFileAction(CI);
1091   // BeginSourceFileAction may change CurrentInput, e.g. during module builds.
1092   setCurrentInput(WrappedAction->getCurrentInput());
1093   return Ret;
1094 }
1095 void WrapperFrontendAction::ExecuteAction() {
1096   WrappedAction->ExecuteAction();
1097 }
1098 void WrapperFrontendAction::EndSourceFile() { WrappedAction->EndSourceFile(); }
1099 void WrapperFrontendAction::EndSourceFileAction() {
1100   WrappedAction->EndSourceFileAction();
1101 }
1102 bool WrapperFrontendAction::shouldEraseOutputFiles() {
1103   return WrappedAction->shouldEraseOutputFiles();
1104 }
1105 
1106 bool WrapperFrontendAction::usesPreprocessorOnly() const {
1107   return WrappedAction->usesPreprocessorOnly();
1108 }
1109 TranslationUnitKind WrapperFrontendAction::getTranslationUnitKind() {
1110   return WrappedAction->getTranslationUnitKind();
1111 }
1112 bool WrapperFrontendAction::hasPCHSupport() const {
1113   return WrappedAction->hasPCHSupport();
1114 }
1115 bool WrapperFrontendAction::hasASTFileSupport() const {
1116   return WrappedAction->hasASTFileSupport();
1117 }
1118 bool WrapperFrontendAction::hasIRSupport() const {
1119   return WrappedAction->hasIRSupport();
1120 }
1121 bool WrapperFrontendAction::hasCodeCompletionSupport() const {
1122   return WrappedAction->hasCodeCompletionSupport();
1123 }
1124 
1125 WrapperFrontendAction::WrapperFrontendAction(
1126     std::unique_ptr<FrontendAction> WrappedAction)
1127   : WrappedAction(std::move(WrappedAction)) {}
1128 
1129