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