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