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