1 //===--- FrontendAction.cpp -----------------------------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
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/Lex/HeaderSearch.h"
15 #include "clang/Lex/Preprocessor.h"
16 #include "clang/Frontend/ASTUnit.h"
17 #include "clang/Frontend/ChainedIncludesSource.h"
18 #include "clang/Frontend/CompilerInstance.h"
19 #include "clang/Frontend/FrontendDiagnostic.h"
20 #include "clang/Frontend/FrontendPluginRegistry.h"
21 #include "clang/Frontend/LayoutOverrideSource.h"
22 #include "clang/Frontend/MultiplexConsumer.h"
23 #include "clang/Parse/ParseAST.h"
24 #include "clang/Serialization/ASTDeserializationListener.h"
25 #include "clang/Serialization/ASTReader.h"
26 #include "llvm/Support/MemoryBuffer.h"
27 #include "llvm/Support/Timer.h"
28 #include "llvm/Support/ErrorHandling.h"
29 #include "llvm/Support/raw_ostream.h"
30 using namespace clang;
34 class DelegatingDeserializationListener : public ASTDeserializationListener {
35 ASTDeserializationListener *Previous;
38 explicit DelegatingDeserializationListener(
39 ASTDeserializationListener *Previous)
40 : Previous(Previous) { }
42 virtual void ReaderInitialized(ASTReader *Reader) {
44 Previous->ReaderInitialized(Reader);
46 virtual void IdentifierRead(serialization::IdentID ID,
49 Previous->IdentifierRead(ID, II);
51 virtual void TypeRead(serialization::TypeIdx Idx, QualType T) {
53 Previous->TypeRead(Idx, T);
55 virtual void DeclRead(serialization::DeclID ID, const Decl *D) {
57 Previous->DeclRead(ID, D);
59 virtual void SelectorRead(serialization::SelectorID ID, Selector Sel) {
61 Previous->SelectorRead(ID, Sel);
63 virtual void MacroDefinitionRead(serialization::PreprocessedEntityID PPID,
64 MacroDefinition *MD) {
66 Previous->MacroDefinitionRead(PPID, MD);
70 /// \brief Dumps deserialized declarations.
71 class DeserializedDeclsDumper : public DelegatingDeserializationListener {
73 explicit DeserializedDeclsDumper(ASTDeserializationListener *Previous)
74 : DelegatingDeserializationListener(Previous) { }
76 virtual void DeclRead(serialization::DeclID ID, const Decl *D) {
77 llvm::outs() << "PCH DECL: " << D->getDeclKindName();
78 if (const NamedDecl *ND = dyn_cast<NamedDecl>(D))
79 llvm::outs() << " - " << *ND;
82 DelegatingDeserializationListener::DeclRead(ID, D);
86 /// \brief Checks deserialized declarations and emits error if a name
87 /// matches one given in command-line using -error-on-deserialized-decl.
88 class DeserializedDeclsChecker : public DelegatingDeserializationListener {
90 std::set<std::string> NamesToCheck;
93 DeserializedDeclsChecker(ASTContext &Ctx,
94 const std::set<std::string> &NamesToCheck,
95 ASTDeserializationListener *Previous)
96 : DelegatingDeserializationListener(Previous),
97 Ctx(Ctx), NamesToCheck(NamesToCheck) { }
99 virtual void DeclRead(serialization::DeclID ID, const Decl *D) {
100 if (const NamedDecl *ND = dyn_cast<NamedDecl>(D))
101 if (NamesToCheck.find(ND->getNameAsString()) != NamesToCheck.end()) {
103 = Ctx.getDiagnostics().getCustomDiagID(DiagnosticsEngine::Error,
104 "%0 was deserialized");
105 Ctx.getDiagnostics().Report(Ctx.getFullLoc(D->getLocation()), DiagID)
106 << ND->getNameAsString();
109 DelegatingDeserializationListener::DeclRead(ID, D);
113 } // end anonymous namespace
115 FrontendAction::FrontendAction() : Instance(0) {}
117 FrontendAction::~FrontendAction() {}
119 void FrontendAction::setCurrentInput(const FrontendInputFile &CurrentInput,
121 this->CurrentInput = CurrentInput;
122 CurrentASTUnit.reset(AST);
125 ASTConsumer* FrontendAction::CreateWrappedASTConsumer(CompilerInstance &CI,
127 ASTConsumer* Consumer = CreateASTConsumer(CI, InFile);
131 if (CI.getFrontendOpts().AddPluginActions.size() == 0)
134 // Make sure the non-plugin consumer is first, so that plugins can't
136 std::vector<ASTConsumer*> Consumers(1, Consumer);
138 for (size_t i = 0, e = CI.getFrontendOpts().AddPluginActions.size();
140 // This is O(|plugins| * |add_plugins|), but since both numbers are
141 // way below 50 in practice, that's ok.
142 for (FrontendPluginRegistry::iterator
143 it = FrontendPluginRegistry::begin(),
144 ie = FrontendPluginRegistry::end();
146 if (it->getName() == CI.getFrontendOpts().AddPluginActions[i]) {
147 OwningPtr<PluginASTAction> P(it->instantiate());
148 FrontendAction* c = P.get();
149 if (P->ParseArgs(CI, CI.getFrontendOpts().AddPluginArgs[i]))
150 Consumers.push_back(c->CreateASTConsumer(CI, InFile));
155 return new MultiplexConsumer(Consumers);
158 bool FrontendAction::BeginSourceFile(CompilerInstance &CI,
159 const FrontendInputFile &Input) {
160 assert(!Instance && "Already processing a source file!");
161 assert(!Input.File.empty() && "Unexpected empty filename!");
162 setCurrentInput(Input);
163 setCompilerInstance(&CI);
165 if (!BeginInvocation(CI))
168 // AST files follow a very different path, since they share objects via the
170 if (Input.Kind == IK_AST) {
171 assert(!usesPreprocessorOnly() &&
172 "Attempt to pass AST file to preprocessor only action!");
173 assert(hasASTFileSupport() &&
174 "This action does not have AST file support!");
176 IntrusiveRefCntPtr<DiagnosticsEngine> Diags(&CI.getDiagnostics());
178 ASTUnit *AST = ASTUnit::LoadFromASTFile(Input.File, Diags,
179 CI.getFileSystemOpts());
183 setCurrentInput(Input, AST);
185 // Set the shared objects, these are reset when we finish processing the
186 // file, otherwise the CompilerInstance will happily destroy them.
187 CI.setFileManager(&AST->getFileManager());
188 CI.setSourceManager(&AST->getSourceManager());
189 CI.setPreprocessor(&AST->getPreprocessor());
190 CI.setASTContext(&AST->getASTContext());
192 // Initialize the action.
193 if (!BeginSourceFileAction(CI, Input.File))
196 /// Create the AST consumer.
197 CI.setASTConsumer(CreateWrappedASTConsumer(CI, Input.File));
198 if (!CI.hasASTConsumer())
204 // Set up the file and source managers, if needed.
205 if (!CI.hasFileManager())
206 CI.createFileManager();
207 if (!CI.hasSourceManager())
208 CI.createSourceManager(CI.getFileManager());
210 // IR files bypass the rest of initialization.
211 if (Input.Kind == IK_LLVM_IR) {
212 assert(hasIRSupport() &&
213 "This action does not have IR file support!");
215 // Inform the diagnostic client we are processing a source file.
216 CI.getDiagnosticClient().BeginSourceFile(CI.getLangOpts(), 0);
218 // Initialize the action.
219 if (!BeginSourceFileAction(CI, Input.File))
225 // Set up the preprocessor.
226 CI.createPreprocessor();
228 // Inform the diagnostic client we are processing a source file.
229 CI.getDiagnosticClient().BeginSourceFile(CI.getLangOpts(),
230 &CI.getPreprocessor());
232 // Initialize the action.
233 if (!BeginSourceFileAction(CI, Input.File))
236 /// Create the AST context and consumer unless this is a preprocessor only
238 if (!usesPreprocessorOnly()) {
239 CI.createASTContext();
241 OwningPtr<ASTConsumer> Consumer(
242 CreateWrappedASTConsumer(CI, Input.File));
246 CI.getASTContext().setASTMutationListener(Consumer->GetASTMutationListener());
248 if (!CI.getPreprocessorOpts().ChainedIncludes.empty()) {
249 // Convert headers to PCH and chain them.
250 OwningPtr<ExternalASTSource> source;
251 source.reset(ChainedIncludesSource::create(CI));
254 CI.getASTContext().setExternalSource(source);
256 } else if (!CI.getPreprocessorOpts().ImplicitPCHInclude.empty()) {
258 assert(hasPCHSupport() && "This action does not have PCH support!");
259 ASTDeserializationListener *DeserialListener =
260 Consumer->GetASTDeserializationListener();
261 if (CI.getPreprocessorOpts().DumpDeserializedPCHDecls)
262 DeserialListener = new DeserializedDeclsDumper(DeserialListener);
263 if (!CI.getPreprocessorOpts().DeserializedPCHDeclsToErrorOn.empty())
264 DeserialListener = new DeserializedDeclsChecker(CI.getASTContext(),
265 CI.getPreprocessorOpts().DeserializedPCHDeclsToErrorOn,
267 CI.createPCHExternalASTSource(
268 CI.getPreprocessorOpts().ImplicitPCHInclude,
269 CI.getPreprocessorOpts().DisablePCHValidation,
270 CI.getPreprocessorOpts().DisableStatCache,
271 CI.getPreprocessorOpts().AllowPCHWithCompilerErrors,
273 if (!CI.getASTContext().getExternalSource())
277 CI.setASTConsumer(Consumer.take());
278 if (!CI.hasASTConsumer())
282 // Initialize built-in info as long as we aren't using an external AST
284 if (!CI.hasASTContext() || !CI.getASTContext().getExternalSource()) {
285 Preprocessor &PP = CI.getPreprocessor();
286 PP.getBuiltinInfo().InitializeBuiltins(PP.getIdentifierTable(),
290 // If there is a layout overrides file, attach an external AST source that
291 // provides the layouts from that file.
292 if (!CI.getFrontendOpts().OverrideRecordLayoutsFile.empty() &&
293 CI.hasASTContext() && !CI.getASTContext().getExternalSource()) {
294 OwningPtr<ExternalASTSource>
295 Override(new LayoutOverrideSource(
296 CI.getFrontendOpts().OverrideRecordLayoutsFile));
297 CI.getASTContext().setExternalSource(Override);
302 // If we failed, reset state since the client will not end up calling the
303 // matching EndSourceFile().
305 if (isCurrentFileAST()) {
307 CI.setPreprocessor(0);
308 CI.setSourceManager(0);
309 CI.setFileManager(0);
312 CI.getDiagnosticClient().EndSourceFile();
313 setCurrentInput(FrontendInputFile());
314 setCompilerInstance(0);
318 void FrontendAction::Execute() {
319 CompilerInstance &CI = getCompilerInstance();
321 // Initialize the main file entry. This needs to be delayed until after PCH
323 if (!isCurrentFileAST()) {
324 if (!CI.InitializeSourceManager(getCurrentFile(),
325 getCurrentInput().IsSystem
331 if (CI.hasFrontendTimer()) {
332 llvm::TimeRegion Timer(CI.getFrontendTimer());
335 else ExecuteAction();
338 void FrontendAction::EndSourceFile() {
339 CompilerInstance &CI = getCompilerInstance();
341 // Inform the diagnostic client we are done with this source file.
342 CI.getDiagnosticClient().EndSourceFile();
344 // Finalize the action.
345 EndSourceFileAction();
347 // Release the consumer and the AST, in that order since the consumer may
348 // perform actions in its destructor which require the context.
350 // FIXME: There is more per-file stuff we could just drop here?
351 if (CI.getFrontendOpts().DisableFree) {
352 CI.takeASTConsumer();
353 if (!isCurrentFileAST()) {
355 CI.resetAndLeakASTContext();
358 if (!isCurrentFileAST()) {
362 CI.setASTConsumer(0);
365 // Inform the preprocessor we are done.
366 if (CI.hasPreprocessor())
367 CI.getPreprocessor().EndSourceFile();
369 if (CI.getFrontendOpts().ShowStats) {
370 llvm::errs() << "\nSTATISTICS FOR '" << getCurrentFile() << "':\n";
371 CI.getPreprocessor().PrintStats();
372 CI.getPreprocessor().getIdentifierTable().PrintStats();
373 CI.getPreprocessor().getHeaderSearchInfo().PrintStats();
374 CI.getSourceManager().PrintStats();
375 llvm::errs() << "\n";
378 // Cleanup the output streams, and erase the output files if we encountered
380 CI.clearOutputFiles(/*EraseFiles=*/CI.getDiagnostics().hasErrorOccurred());
382 if (isCurrentFileAST()) {
384 CI.resetAndLeakASTContext();
385 CI.resetAndLeakPreprocessor();
386 CI.resetAndLeakSourceManager();
387 CI.resetAndLeakFileManager();
390 setCompilerInstance(0);
391 setCurrentInput(FrontendInputFile());
394 //===----------------------------------------------------------------------===//
396 //===----------------------------------------------------------------------===//
398 void ASTFrontendAction::ExecuteAction() {
399 CompilerInstance &CI = getCompilerInstance();
401 // FIXME: Move the truncation aspect of this into Sema, we delayed this till
402 // here so the source manager would be initialized.
403 if (hasCodeCompletionSupport() &&
404 !CI.getFrontendOpts().CodeCompletionAt.FileName.empty())
405 CI.createCodeCompletionConsumer();
407 // Use a code completion consumer?
408 CodeCompleteConsumer *CompletionConsumer = 0;
409 if (CI.hasCodeCompletionConsumer())
410 CompletionConsumer = &CI.getCodeCompletionConsumer();
413 CI.createSema(getTranslationUnitKind(), CompletionConsumer);
415 ParseAST(CI.getSema(), CI.getFrontendOpts().ShowStats,
416 CI.getFrontendOpts().SkipFunctionBodies);
419 void PluginASTAction::anchor() { }
422 PreprocessorFrontendAction::CreateASTConsumer(CompilerInstance &CI,
424 llvm_unreachable("Invalid CreateASTConsumer on preprocessor action!");
427 ASTConsumer *WrapperFrontendAction::CreateASTConsumer(CompilerInstance &CI,
429 return WrappedAction->CreateASTConsumer(CI, InFile);
431 bool WrapperFrontendAction::BeginInvocation(CompilerInstance &CI) {
432 return WrappedAction->BeginInvocation(CI);
434 bool WrapperFrontendAction::BeginSourceFileAction(CompilerInstance &CI,
435 StringRef Filename) {
436 WrappedAction->setCurrentInput(getCurrentInput());
437 WrappedAction->setCompilerInstance(&CI);
438 return WrappedAction->BeginSourceFileAction(CI, Filename);
440 void WrapperFrontendAction::ExecuteAction() {
441 WrappedAction->ExecuteAction();
443 void WrapperFrontendAction::EndSourceFileAction() {
444 WrappedAction->EndSourceFileAction();
447 bool WrapperFrontendAction::usesPreprocessorOnly() const {
448 return WrappedAction->usesPreprocessorOnly();
450 TranslationUnitKind WrapperFrontendAction::getTranslationUnitKind() {
451 return WrappedAction->getTranslationUnitKind();
453 bool WrapperFrontendAction::hasPCHSupport() const {
454 return WrappedAction->hasPCHSupport();
456 bool WrapperFrontendAction::hasASTFileSupport() const {
457 return WrappedAction->hasASTFileSupport();
459 bool WrapperFrontendAction::hasIRSupport() const {
460 return WrappedAction->hasIRSupport();
462 bool WrapperFrontendAction::hasCodeCompletionSupport() const {
463 return WrappedAction->hasCodeCompletionSupport();
466 WrapperFrontendAction::WrapperFrontendAction(FrontendAction *WrappedAction)
467 : WrappedAction(WrappedAction) {}