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/ChainedIncludesSource.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/Preprocessor.h"
24 #include "clang/Parse/ParseAST.h"
25 #include "clang/Serialization/ASTDeserializationListener.h"
26 #include "clang/Serialization/ASTReader.h"
27 #include "clang/Serialization/GlobalModuleIndex.h"
28 #include "llvm/Support/ErrorHandling.h"
29 #include "llvm/Support/FileSystem.h"
30 #include "llvm/Support/MemoryBuffer.h"
31 #include "llvm/Support/Timer.h"
32 #include "llvm/Support/raw_ostream.h"
33 #include "llvm/Support/system_error.h"
34 using namespace clang;
35 
36 namespace {
37 
38 class DelegatingDeserializationListener : public ASTDeserializationListener {
39   ASTDeserializationListener *Previous;
40   bool DeletePrevious;
41 
42 public:
43   explicit DelegatingDeserializationListener(
44       ASTDeserializationListener *Previous, bool DeletePrevious)
45       : Previous(Previous), DeletePrevious(DeletePrevious) {}
46   virtual ~DelegatingDeserializationListener() {
47     if (DeletePrevious)
48       delete Previous;
49   }
50 
51   void ReaderInitialized(ASTReader *Reader) override {
52     if (Previous)
53       Previous->ReaderInitialized(Reader);
54   }
55   void IdentifierRead(serialization::IdentID ID,
56                       IdentifierInfo *II) override {
57     if (Previous)
58       Previous->IdentifierRead(ID, II);
59   }
60   void TypeRead(serialization::TypeIdx Idx, QualType T) override {
61     if (Previous)
62       Previous->TypeRead(Idx, T);
63   }
64   void DeclRead(serialization::DeclID ID, const Decl *D) override {
65     if (Previous)
66       Previous->DeclRead(ID, D);
67   }
68   void SelectorRead(serialization::SelectorID ID, Selector Sel) override {
69     if (Previous)
70       Previous->SelectorRead(ID, Sel);
71   }
72   void MacroDefinitionRead(serialization::PreprocessedEntityID PPID,
73                            MacroDefinition *MD) override {
74     if (Previous)
75       Previous->MacroDefinitionRead(PPID, MD);
76   }
77 };
78 
79 /// \brief Dumps deserialized declarations.
80 class DeserializedDeclsDumper : public DelegatingDeserializationListener {
81 public:
82   explicit DeserializedDeclsDumper(ASTDeserializationListener *Previous,
83                                    bool DeletePrevious)
84       : DelegatingDeserializationListener(Previous, DeletePrevious) {}
85 
86   void DeclRead(serialization::DeclID ID, const Decl *D) override {
87     llvm::outs() << "PCH DECL: " << D->getDeclKindName();
88     if (const NamedDecl *ND = dyn_cast<NamedDecl>(D))
89       llvm::outs() << " - " << *ND;
90     llvm::outs() << "\n";
91 
92     DelegatingDeserializationListener::DeclRead(ID, D);
93   }
94 };
95 
96 /// \brief Checks deserialized declarations and emits error if a name
97 /// matches one given in command-line using -error-on-deserialized-decl.
98 class DeserializedDeclsChecker : public DelegatingDeserializationListener {
99   ASTContext &Ctx;
100   std::set<std::string> NamesToCheck;
101 
102 public:
103   DeserializedDeclsChecker(ASTContext &Ctx,
104                            const std::set<std::string> &NamesToCheck,
105                            ASTDeserializationListener *Previous,
106                            bool DeletePrevious)
107       : DelegatingDeserializationListener(Previous, DeletePrevious), Ctx(Ctx),
108         NamesToCheck(NamesToCheck) {}
109 
110   void DeclRead(serialization::DeclID ID, const Decl *D) override {
111     if (const NamedDecl *ND = dyn_cast<NamedDecl>(D))
112       if (NamesToCheck.find(ND->getNameAsString()) != NamesToCheck.end()) {
113         unsigned DiagID
114           = Ctx.getDiagnostics().getCustomDiagID(DiagnosticsEngine::Error,
115                                                  "%0 was deserialized");
116         Ctx.getDiagnostics().Report(Ctx.getFullLoc(D->getLocation()), DiagID)
117             << ND->getNameAsString();
118       }
119 
120     DelegatingDeserializationListener::DeclRead(ID, D);
121   }
122 };
123 
124 } // end anonymous namespace
125 
126 FrontendAction::FrontendAction() : Instance(nullptr) {}
127 
128 FrontendAction::~FrontendAction() {}
129 
130 void FrontendAction::setCurrentInput(const FrontendInputFile &CurrentInput,
131                                      ASTUnit *AST) {
132   this->CurrentInput = CurrentInput;
133   CurrentASTUnit.reset(AST);
134 }
135 
136 ASTConsumer* FrontendAction::CreateWrappedASTConsumer(CompilerInstance &CI,
137                                                       StringRef InFile) {
138   ASTConsumer* Consumer = CreateASTConsumer(CI, InFile);
139   if (!Consumer)
140     return nullptr;
141 
142   if (CI.getFrontendOpts().AddPluginActions.size() == 0)
143     return Consumer;
144 
145   // Make sure the non-plugin consumer is first, so that plugins can't
146   // modifiy the AST.
147   std::vector<ASTConsumer*> Consumers(1, Consumer);
148 
149   for (size_t i = 0, e = CI.getFrontendOpts().AddPluginActions.size();
150        i != e; ++i) {
151     // This is O(|plugins| * |add_plugins|), but since both numbers are
152     // way below 50 in practice, that's ok.
153     for (FrontendPluginRegistry::iterator
154         it = FrontendPluginRegistry::begin(),
155         ie = FrontendPluginRegistry::end();
156         it != ie; ++it) {
157       if (it->getName() == CI.getFrontendOpts().AddPluginActions[i]) {
158         std::unique_ptr<PluginASTAction> P(it->instantiate());
159         FrontendAction* c = P.get();
160         if (P->ParseArgs(CI, CI.getFrontendOpts().AddPluginArgs[i]))
161           Consumers.push_back(c->CreateASTConsumer(CI, InFile));
162       }
163     }
164   }
165 
166   return new MultiplexConsumer(Consumers);
167 }
168 
169 bool FrontendAction::BeginSourceFile(CompilerInstance &CI,
170                                      const FrontendInputFile &Input) {
171   assert(!Instance && "Already processing a source file!");
172   assert(!Input.isEmpty() && "Unexpected empty filename!");
173   setCurrentInput(Input);
174   setCompilerInstance(&CI);
175 
176   StringRef InputFile = Input.getFile();
177   bool HasBegunSourceFile = false;
178   if (!BeginInvocation(CI))
179     goto failure;
180 
181   // AST files follow a very different path, since they share objects via the
182   // AST unit.
183   if (Input.getKind() == IK_AST) {
184     assert(!usesPreprocessorOnly() &&
185            "Attempt to pass AST file to preprocessor only action!");
186     assert(hasASTFileSupport() &&
187            "This action does not have AST file support!");
188 
189     IntrusiveRefCntPtr<DiagnosticsEngine> Diags(&CI.getDiagnostics());
190 
191     ASTUnit *AST = ASTUnit::LoadFromASTFile(InputFile, Diags,
192                                             CI.getFileSystemOpts());
193     if (!AST)
194       goto failure;
195 
196     setCurrentInput(Input, AST);
197 
198     // Inform the diagnostic client we are processing a source file.
199     CI.getDiagnosticClient().BeginSourceFile(CI.getLangOpts(), nullptr);
200     HasBegunSourceFile = true;
201 
202     // Set the shared objects, these are reset when we finish processing the
203     // file, otherwise the CompilerInstance will happily destroy them.
204     CI.setFileManager(&AST->getFileManager());
205     CI.setSourceManager(&AST->getSourceManager());
206     CI.setPreprocessor(&AST->getPreprocessor());
207     CI.setASTContext(&AST->getASTContext());
208 
209     // Initialize the action.
210     if (!BeginSourceFileAction(CI, InputFile))
211       goto failure;
212 
213     // Create the AST consumer.
214     CI.setASTConsumer(CreateWrappedASTConsumer(CI, InputFile));
215     if (!CI.hasASTConsumer())
216       goto failure;
217 
218     return true;
219   }
220 
221   if (!CI.hasVirtualFileSystem()) {
222     if (IntrusiveRefCntPtr<vfs::FileSystem> VFS =
223           createVFSFromCompilerInvocation(CI.getInvocation(),
224                                           CI.getDiagnostics()))
225       CI.setVirtualFileSystem(VFS);
226     else
227       goto failure;
228   }
229 
230   // Set up the file and source managers, if needed.
231   if (!CI.hasFileManager())
232     CI.createFileManager();
233   if (!CI.hasSourceManager())
234     CI.createSourceManager(CI.getFileManager());
235 
236   // IR files bypass the rest of initialization.
237   if (Input.getKind() == IK_LLVM_IR) {
238     assert(hasIRSupport() &&
239            "This action does not have IR file support!");
240 
241     // Inform the diagnostic client we are processing a source file.
242     CI.getDiagnosticClient().BeginSourceFile(CI.getLangOpts(), nullptr);
243     HasBegunSourceFile = true;
244 
245     // Initialize the action.
246     if (!BeginSourceFileAction(CI, InputFile))
247       goto failure;
248 
249     // Initialize the main file entry.
250     if (!CI.InitializeSourceManager(CurrentInput))
251       goto failure;
252 
253     return true;
254   }
255 
256   // If the implicit PCH include is actually a directory, rather than
257   // a single file, search for a suitable PCH file in that directory.
258   if (!CI.getPreprocessorOpts().ImplicitPCHInclude.empty()) {
259     FileManager &FileMgr = CI.getFileManager();
260     PreprocessorOptions &PPOpts = CI.getPreprocessorOpts();
261     StringRef PCHInclude = PPOpts.ImplicitPCHInclude;
262     if (const DirectoryEntry *PCHDir = FileMgr.getDirectory(PCHInclude)) {
263       llvm::error_code EC;
264       SmallString<128> DirNative;
265       llvm::sys::path::native(PCHDir->getName(), DirNative);
266       bool Found = false;
267       for (llvm::sys::fs::directory_iterator Dir(DirNative.str(), EC), DirEnd;
268            Dir != DirEnd && !EC; Dir.increment(EC)) {
269         // Check whether this is an acceptable AST file.
270         if (ASTReader::isAcceptableASTFile(Dir->path(), FileMgr,
271                                            CI.getLangOpts(),
272                                            CI.getTargetOpts(),
273                                            CI.getPreprocessorOpts())) {
274           PPOpts.ImplicitPCHInclude = Dir->path();
275           Found = true;
276           break;
277         }
278       }
279 
280       if (!Found) {
281         CI.getDiagnostics().Report(diag::err_fe_no_pch_in_dir) << PCHInclude;
282         return true;
283       }
284     }
285   }
286 
287   // Set up the preprocessor.
288   CI.createPreprocessor(getTranslationUnitKind());
289 
290   // Inform the diagnostic client we are processing a source file.
291   CI.getDiagnosticClient().BeginSourceFile(CI.getLangOpts(),
292                                            &CI.getPreprocessor());
293   HasBegunSourceFile = true;
294 
295   // Initialize the action.
296   if (!BeginSourceFileAction(CI, InputFile))
297     goto failure;
298 
299   // Initialize the main file entry. It is important that this occurs after
300   // BeginSourceFileAction, which may change CurrentInput during module builds.
301   if (!CI.InitializeSourceManager(CurrentInput))
302     goto failure;
303 
304   // Create the AST context and consumer unless this is a preprocessor only
305   // action.
306   if (!usesPreprocessorOnly()) {
307     CI.createASTContext();
308 
309     std::unique_ptr<ASTConsumer> Consumer(
310         CreateWrappedASTConsumer(CI, InputFile));
311     if (!Consumer)
312       goto failure;
313 
314     CI.getASTContext().setASTMutationListener(Consumer->GetASTMutationListener());
315 
316     if (!CI.getPreprocessorOpts().ChainedIncludes.empty()) {
317       // Convert headers to PCH and chain them.
318       IntrusiveRefCntPtr<ChainedIncludesSource> source;
319       source = ChainedIncludesSource::create(CI);
320       if (!source)
321         goto failure;
322       CI.setModuleManager(static_cast<ASTReader*>(&source->getFinalReader()));
323       CI.getASTContext().setExternalSource(source);
324 
325     } else if (!CI.getPreprocessorOpts().ImplicitPCHInclude.empty()) {
326       // Use PCH.
327       assert(hasPCHSupport() && "This action does not have PCH support!");
328       ASTDeserializationListener *DeserialListener =
329           Consumer->GetASTDeserializationListener();
330       bool DeleteDeserialListener = false;
331       if (CI.getPreprocessorOpts().DumpDeserializedPCHDecls) {
332         DeserialListener = new DeserializedDeclsDumper(DeserialListener,
333                                                        DeleteDeserialListener);
334         DeleteDeserialListener = true;
335       }
336       if (!CI.getPreprocessorOpts().DeserializedPCHDeclsToErrorOn.empty()) {
337         DeserialListener = new DeserializedDeclsChecker(
338             CI.getASTContext(),
339             CI.getPreprocessorOpts().DeserializedPCHDeclsToErrorOn,
340             DeserialListener, DeleteDeserialListener);
341         DeleteDeserialListener = true;
342       }
343       CI.createPCHExternalASTSource(
344           CI.getPreprocessorOpts().ImplicitPCHInclude,
345           CI.getPreprocessorOpts().DisablePCHValidation,
346           CI.getPreprocessorOpts().AllowPCHWithCompilerErrors, DeserialListener,
347           DeleteDeserialListener);
348       if (!CI.getASTContext().getExternalSource())
349         goto failure;
350     }
351 
352     CI.setASTConsumer(Consumer.release());
353     if (!CI.hasASTConsumer())
354       goto failure;
355   }
356 
357   // Initialize built-in info as long as we aren't using an external AST
358   // source.
359   if (!CI.hasASTContext() || !CI.getASTContext().getExternalSource()) {
360     Preprocessor &PP = CI.getPreprocessor();
361 
362     // If modules are enabled, create the module manager before creating
363     // any builtins, so that all declarations know that they might be
364     // extended by an external source.
365     if (CI.getLangOpts().Modules)
366       CI.createModuleManager();
367 
368     PP.getBuiltinInfo().InitializeBuiltins(PP.getIdentifierTable(),
369                                            PP.getLangOpts());
370   } else {
371     // FIXME: If this is a problem, recover from it by creating a multiplex
372     // source.
373     assert((!CI.getLangOpts().Modules || CI.getModuleManager()) &&
374            "modules enabled but created an external source that "
375            "doesn't support modules");
376   }
377 
378   // If there is a layout overrides file, attach an external AST source that
379   // provides the layouts from that file.
380   if (!CI.getFrontendOpts().OverrideRecordLayoutsFile.empty() &&
381       CI.hasASTContext() && !CI.getASTContext().getExternalSource()) {
382     IntrusiveRefCntPtr<ExternalASTSource>
383       Override(new LayoutOverrideSource(
384                      CI.getFrontendOpts().OverrideRecordLayoutsFile));
385     CI.getASTContext().setExternalSource(Override);
386   }
387 
388   return true;
389 
390   // If we failed, reset state since the client will not end up calling the
391   // matching EndSourceFile().
392   failure:
393   if (isCurrentFileAST()) {
394     CI.setASTContext(nullptr);
395     CI.setPreprocessor(nullptr);
396     CI.setSourceManager(nullptr);
397     CI.setFileManager(nullptr);
398   }
399 
400   if (HasBegunSourceFile)
401     CI.getDiagnosticClient().EndSourceFile();
402   CI.clearOutputFiles(/*EraseFiles=*/true);
403   setCurrentInput(FrontendInputFile());
404   setCompilerInstance(nullptr);
405   return false;
406 }
407 
408 bool FrontendAction::Execute() {
409   CompilerInstance &CI = getCompilerInstance();
410 
411   if (CI.hasFrontendTimer()) {
412     llvm::TimeRegion Timer(CI.getFrontendTimer());
413     ExecuteAction();
414   }
415   else ExecuteAction();
416 
417   // If we are supposed to rebuild the global module index, do so now unless
418   // there were any module-build failures.
419   if (CI.shouldBuildGlobalModuleIndex() && CI.hasFileManager() &&
420       CI.hasPreprocessor()) {
421     GlobalModuleIndex::writeIndex(
422       CI.getFileManager(),
423       CI.getPreprocessor().getHeaderSearchInfo().getModuleCachePath());
424   }
425 
426   return true;
427 }
428 
429 void FrontendAction::EndSourceFile() {
430   CompilerInstance &CI = getCompilerInstance();
431 
432   // Inform the diagnostic client we are done with this source file.
433   CI.getDiagnosticClient().EndSourceFile();
434 
435   // Finalize the action.
436   EndSourceFileAction();
437 
438   // Sema references the ast consumer, so reset sema first.
439   //
440   // FIXME: There is more per-file stuff we could just drop here?
441   bool DisableFree = CI.getFrontendOpts().DisableFree;
442   if (DisableFree) {
443     if (!isCurrentFileAST()) {
444       CI.resetAndLeakSema();
445       CI.resetAndLeakASTContext();
446     }
447     BuryPointer(CI.takeASTConsumer());
448   } else {
449     if (!isCurrentFileAST()) {
450       CI.setSema(nullptr);
451       CI.setASTContext(nullptr);
452     }
453     CI.setASTConsumer(nullptr);
454   }
455 
456   // Inform the preprocessor we are done.
457   if (CI.hasPreprocessor())
458     CI.getPreprocessor().EndSourceFile();
459 
460   if (CI.getFrontendOpts().ShowStats) {
461     llvm::errs() << "\nSTATISTICS FOR '" << getCurrentFile() << "':\n";
462     CI.getPreprocessor().PrintStats();
463     CI.getPreprocessor().getIdentifierTable().PrintStats();
464     CI.getPreprocessor().getHeaderSearchInfo().PrintStats();
465     CI.getSourceManager().PrintStats();
466     llvm::errs() << "\n";
467   }
468 
469   // Cleanup the output streams, and erase the output files if instructed by the
470   // FrontendAction.
471   CI.clearOutputFiles(/*EraseFiles=*/shouldEraseOutputFiles());
472 
473   // FIXME: Only do this if DisableFree is set.
474   if (isCurrentFileAST()) {
475     CI.resetAndLeakSema();
476     CI.resetAndLeakASTContext();
477     CI.resetAndLeakPreprocessor();
478     CI.resetAndLeakSourceManager();
479     CI.resetAndLeakFileManager();
480   }
481 
482   setCompilerInstance(nullptr);
483   setCurrentInput(FrontendInputFile());
484 }
485 
486 bool FrontendAction::shouldEraseOutputFiles() {
487   return getCompilerInstance().getDiagnostics().hasErrorOccurred();
488 }
489 
490 //===----------------------------------------------------------------------===//
491 // Utility Actions
492 //===----------------------------------------------------------------------===//
493 
494 void ASTFrontendAction::ExecuteAction() {
495   CompilerInstance &CI = getCompilerInstance();
496   if (!CI.hasPreprocessor())
497     return;
498 
499   // FIXME: Move the truncation aspect of this into Sema, we delayed this till
500   // here so the source manager would be initialized.
501   if (hasCodeCompletionSupport() &&
502       !CI.getFrontendOpts().CodeCompletionAt.FileName.empty())
503     CI.createCodeCompletionConsumer();
504 
505   // Use a code completion consumer?
506   CodeCompleteConsumer *CompletionConsumer = nullptr;
507   if (CI.hasCodeCompletionConsumer())
508     CompletionConsumer = &CI.getCodeCompletionConsumer();
509 
510   if (!CI.hasSema())
511     CI.createSema(getTranslationUnitKind(), CompletionConsumer);
512 
513   ParseAST(CI.getSema(), CI.getFrontendOpts().ShowStats,
514            CI.getFrontendOpts().SkipFunctionBodies);
515 }
516 
517 void PluginASTAction::anchor() { }
518 
519 ASTConsumer *
520 PreprocessorFrontendAction::CreateASTConsumer(CompilerInstance &CI,
521                                               StringRef InFile) {
522   llvm_unreachable("Invalid CreateASTConsumer on preprocessor action!");
523 }
524 
525 ASTConsumer *WrapperFrontendAction::CreateASTConsumer(CompilerInstance &CI,
526                                                       StringRef InFile) {
527   return WrappedAction->CreateASTConsumer(CI, InFile);
528 }
529 bool WrapperFrontendAction::BeginInvocation(CompilerInstance &CI) {
530   return WrappedAction->BeginInvocation(CI);
531 }
532 bool WrapperFrontendAction::BeginSourceFileAction(CompilerInstance &CI,
533                                                   StringRef Filename) {
534   WrappedAction->setCurrentInput(getCurrentInput());
535   WrappedAction->setCompilerInstance(&CI);
536   return WrappedAction->BeginSourceFileAction(CI, Filename);
537 }
538 void WrapperFrontendAction::ExecuteAction() {
539   WrappedAction->ExecuteAction();
540 }
541 void WrapperFrontendAction::EndSourceFileAction() {
542   WrappedAction->EndSourceFileAction();
543 }
544 
545 bool WrapperFrontendAction::usesPreprocessorOnly() const {
546   return WrappedAction->usesPreprocessorOnly();
547 }
548 TranslationUnitKind WrapperFrontendAction::getTranslationUnitKind() {
549   return WrappedAction->getTranslationUnitKind();
550 }
551 bool WrapperFrontendAction::hasPCHSupport() const {
552   return WrappedAction->hasPCHSupport();
553 }
554 bool WrapperFrontendAction::hasASTFileSupport() const {
555   return WrappedAction->hasASTFileSupport();
556 }
557 bool WrapperFrontendAction::hasIRSupport() const {
558   return WrappedAction->hasIRSupport();
559 }
560 bool WrapperFrontendAction::hasCodeCompletionSupport() const {
561   return WrappedAction->hasCodeCompletionSupport();
562 }
563 
564 WrapperFrontendAction::WrapperFrontendAction(FrontendAction *WrappedAction)
565   : WrappedAction(WrappedAction) {}
566 
567