FrontendAction.cpp revision 5bf27ab741084eb379b40bc5e08a71ba7c26fb49
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/Lex/HeaderSearch.h"
15#include "clang/Lex/Preprocessor.h"
16#include "clang/Frontend/ASTUnit.h"
17#include "clang/Frontend/CompilerInstance.h"
18#include "clang/Frontend/FrontendDiagnostic.h"
19#include "clang/Frontend/FrontendPluginRegistry.h"
20#include "clang/Frontend/MultiplexConsumer.h"
21#include "clang/Parse/ParseAST.h"
22#include "clang/Serialization/ASTDeserializationListener.h"
23#include "clang/Serialization/ASTReader.h"
24#include "clang/Serialization/ChainedIncludesSource.h"
25#include "llvm/Support/MemoryBuffer.h"
26#include "llvm/Support/Timer.h"
27#include "llvm/Support/ErrorHandling.h"
28#include "llvm/Support/raw_ostream.h"
29using namespace clang;
30
31namespace {
32
33class DelegatingDeserializationListener : public ASTDeserializationListener {
34  ASTDeserializationListener *Previous;
35
36public:
37  explicit DelegatingDeserializationListener(
38                                           ASTDeserializationListener *Previous)
39    : Previous(Previous) { }
40
41  virtual void ReaderInitialized(ASTReader *Reader) {
42    if (Previous)
43      Previous->ReaderInitialized(Reader);
44  }
45  virtual void IdentifierRead(serialization::IdentID ID,
46                              IdentifierInfo *II) {
47    if (Previous)
48      Previous->IdentifierRead(ID, II);
49  }
50  virtual void TypeRead(serialization::TypeIdx Idx, QualType T) {
51    if (Previous)
52      Previous->TypeRead(Idx, T);
53  }
54  virtual void DeclRead(serialization::DeclID ID, const Decl *D) {
55    if (Previous)
56      Previous->DeclRead(ID, D);
57  }
58  virtual void SelectorRead(serialization::SelectorID ID, Selector Sel) {
59    if (Previous)
60      Previous->SelectorRead(ID, Sel);
61  }
62  virtual void MacroDefinitionRead(serialization::PreprocessedEntityID PPID,
63                                   MacroDefinition *MD) {
64    if (Previous)
65      Previous->MacroDefinitionRead(PPID, MD);
66  }
67};
68
69/// \brief Dumps deserialized declarations.
70class DeserializedDeclsDumper : public DelegatingDeserializationListener {
71public:
72  explicit DeserializedDeclsDumper(ASTDeserializationListener *Previous)
73    : DelegatingDeserializationListener(Previous) { }
74
75  virtual void DeclRead(serialization::DeclID ID, const Decl *D) {
76    llvm::outs() << "PCH DECL: " << D->getDeclKindName();
77    if (const NamedDecl *ND = dyn_cast<NamedDecl>(D))
78      llvm::outs() << " - " << ND->getNameAsString();
79    llvm::outs() << "\n";
80
81    DelegatingDeserializationListener::DeclRead(ID, D);
82  }
83};
84
85  /// \brief Checks deserialized declarations and emits error if a name
86  /// matches one given in command-line using -error-on-deserialized-decl.
87  class DeserializedDeclsChecker : public DelegatingDeserializationListener {
88    ASTContext &Ctx;
89    std::set<std::string> NamesToCheck;
90
91  public:
92    DeserializedDeclsChecker(ASTContext &Ctx,
93                             const std::set<std::string> &NamesToCheck,
94                             ASTDeserializationListener *Previous)
95      : DelegatingDeserializationListener(Previous),
96        Ctx(Ctx), NamesToCheck(NamesToCheck) { }
97
98    virtual void DeclRead(serialization::DeclID ID, const Decl *D) {
99      if (const NamedDecl *ND = dyn_cast<NamedDecl>(D))
100        if (NamesToCheck.find(ND->getNameAsString()) != NamesToCheck.end()) {
101          unsigned DiagID
102            = Ctx.getDiagnostics().getCustomDiagID(DiagnosticsEngine::Error,
103                                                   "%0 was deserialized");
104          Ctx.getDiagnostics().Report(Ctx.getFullLoc(D->getLocation()), DiagID)
105              << ND->getNameAsString();
106        }
107
108      DelegatingDeserializationListener::DeclRead(ID, D);
109    }
110};
111
112} // end anonymous namespace
113
114FrontendAction::FrontendAction() : Instance(0) {}
115
116FrontendAction::~FrontendAction() {}
117
118void FrontendAction::setCurrentFile(StringRef Value, InputKind Kind,
119                                    ASTUnit *AST) {
120  CurrentFile = Value;
121  CurrentFileKind = Kind;
122  CurrentASTUnit.reset(AST);
123}
124
125ASTConsumer* FrontendAction::CreateWrappedASTConsumer(CompilerInstance &CI,
126                                                      StringRef InFile) {
127  ASTConsumer* Consumer = CreateASTConsumer(CI, InFile);
128  if (!Consumer)
129    return 0;
130
131  if (CI.getFrontendOpts().AddPluginActions.size() == 0)
132    return Consumer;
133
134  // Make sure the non-plugin consumer is first, so that plugins can't
135  // modifiy the AST.
136  std::vector<ASTConsumer*> Consumers(1, Consumer);
137
138  for (size_t i = 0, e = CI.getFrontendOpts().AddPluginActions.size();
139       i != e; ++i) {
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();
145        it != ie; ++it) {
146      if (it->getName() == CI.getFrontendOpts().AddPluginActions[i]) {
147        llvm::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));
151      }
152    }
153  }
154
155  return new MultiplexConsumer(Consumers);
156}
157
158bool FrontendAction::BeginSourceFile(CompilerInstance &CI,
159                                     StringRef Filename,
160                                     InputKind InputKind) {
161  assert(!Instance && "Already processing a source file!");
162  assert(!Filename.empty() && "Unexpected empty filename!");
163  setCurrentFile(Filename, InputKind);
164  setCompilerInstance(&CI);
165
166  if (!BeginInvocation(CI))
167    goto failure;
168
169  // AST files follow a very different path, since they share objects via the
170  // AST unit.
171  if (InputKind == IK_AST) {
172    assert(!usesPreprocessorOnly() &&
173           "Attempt to pass AST file to preprocessor only action!");
174    assert(hasASTFileSupport() &&
175           "This action does not have AST file support!");
176
177    llvm::IntrusiveRefCntPtr<DiagnosticsEngine> Diags(&CI.getDiagnostics());
178    std::string Error;
179    ASTUnit *AST = ASTUnit::LoadFromASTFile(Filename, Diags,
180                                            CI.getFileSystemOpts());
181    if (!AST)
182      goto failure;
183
184    setCurrentFile(Filename, InputKind, AST);
185
186    // Set the shared objects, these are reset when we finish processing the
187    // file, otherwise the CompilerInstance will happily destroy them.
188    CI.setFileManager(&AST->getFileManager());
189    CI.setSourceManager(&AST->getSourceManager());
190    CI.setPreprocessor(&AST->getPreprocessor());
191    CI.setASTContext(&AST->getASTContext());
192
193    // Initialize the action.
194    if (!BeginSourceFileAction(CI, Filename))
195      goto failure;
196
197    /// Create the AST consumer.
198    CI.setASTConsumer(CreateWrappedASTConsumer(CI, Filename));
199    if (!CI.hasASTConsumer())
200      goto failure;
201
202    return true;
203  }
204
205  // Set up the file and source managers, if needed.
206  if (!CI.hasFileManager())
207    CI.createFileManager();
208  if (!CI.hasSourceManager())
209    CI.createSourceManager(CI.getFileManager());
210
211  // IR files bypass the rest of initialization.
212  if (InputKind == IK_LLVM_IR) {
213    assert(hasIRSupport() &&
214           "This action does not have IR file support!");
215
216    // Inform the diagnostic client we are processing a source file.
217    CI.getDiagnosticClient().BeginSourceFile(CI.getLangOpts(), 0);
218
219    // Initialize the action.
220    if (!BeginSourceFileAction(CI, Filename))
221      goto failure;
222
223    return true;
224  }
225
226  // Set up the preprocessor.
227  CI.createPreprocessor();
228
229  // Inform the diagnostic client we are processing a source file.
230  CI.getDiagnosticClient().BeginSourceFile(CI.getLangOpts(),
231                                           &CI.getPreprocessor());
232
233  // Initialize the action.
234  if (!BeginSourceFileAction(CI, Filename))
235    goto failure;
236
237  /// Create the AST context and consumer unless this is a preprocessor only
238  /// action.
239  if (!usesPreprocessorOnly()) {
240    CI.createASTContext();
241
242    llvm::OwningPtr<ASTConsumer> Consumer(
243        CreateWrappedASTConsumer(CI, Filename));
244    if (!Consumer)
245      goto failure;
246
247    CI.getASTContext().setASTMutationListener(Consumer->GetASTMutationListener());
248
249    if (!CI.getPreprocessorOpts().ChainedIncludes.empty()) {
250      // Convert headers to PCH and chain them.
251      llvm::OwningPtr<ExternalASTSource> source;
252      source.reset(ChainedIncludesSource::create(CI));
253      if (!source)
254        goto failure;
255      CI.getASTContext().setExternalSource(source);
256
257    } else if (!CI.getPreprocessorOpts().ImplicitPCHInclude.empty()) {
258      // Use PCH.
259      assert(hasPCHSupport() && "This action does not have PCH support!");
260      ASTDeserializationListener *DeserialListener =
261          Consumer->GetASTDeserializationListener();
262      if (CI.getPreprocessorOpts().DumpDeserializedPCHDecls)
263        DeserialListener = new DeserializedDeclsDumper(DeserialListener);
264      if (!CI.getPreprocessorOpts().DeserializedPCHDeclsToErrorOn.empty())
265        DeserialListener = new DeserializedDeclsChecker(CI.getASTContext(),
266                         CI.getPreprocessorOpts().DeserializedPCHDeclsToErrorOn,
267                                                        DeserialListener);
268      CI.createPCHExternalASTSource(
269                                CI.getPreprocessorOpts().ImplicitPCHInclude,
270                                CI.getPreprocessorOpts().DisablePCHValidation,
271                                CI.getPreprocessorOpts().DisableStatCache,
272                                DeserialListener);
273      if (!CI.getASTContext().getExternalSource())
274        goto failure;
275    }
276
277    CI.setASTConsumer(Consumer.take());
278    if (!CI.hasASTConsumer())
279      goto failure;
280  }
281
282  // Initialize built-in info as long as we aren't using an external AST
283  // source.
284  if (!CI.hasASTContext() || !CI.getASTContext().getExternalSource()) {
285    Preprocessor &PP = CI.getPreprocessor();
286    PP.getBuiltinInfo().InitializeBuiltins(PP.getIdentifierTable(),
287                                           PP.getLangOptions());
288  }
289
290  return true;
291
292  // If we failed, reset state since the client will not end up calling the
293  // matching EndSourceFile().
294  failure:
295  if (isCurrentFileAST()) {
296    CI.setASTContext(0);
297    CI.setPreprocessor(0);
298    CI.setSourceManager(0);
299    CI.setFileManager(0);
300  }
301
302  CI.getDiagnosticClient().EndSourceFile();
303  setCurrentFile("", IK_None);
304  setCompilerInstance(0);
305  return false;
306}
307
308void FrontendAction::Execute() {
309  CompilerInstance &CI = getCompilerInstance();
310
311  // Initialize the main file entry. This needs to be delayed until after PCH
312  // has loaded.
313  if (isCurrentFileAST()) {
314    // Set the main file ID to an empty file.
315    //
316    // FIXME: We probably shouldn't need this, but for now this is the
317    // simplest way to reuse the logic in ParseAST.
318    const char *EmptyStr = "";
319    llvm::MemoryBuffer *SB =
320      llvm::MemoryBuffer::getMemBuffer(EmptyStr, "<dummy input>");
321    CI.getSourceManager().createMainFileIDForMemBuffer(SB);
322  } else {
323    if (!CI.InitializeSourceManager(getCurrentFile()))
324      return;
325  }
326
327  if (CI.hasFrontendTimer()) {
328    llvm::TimeRegion Timer(CI.getFrontendTimer());
329    ExecuteAction();
330  }
331  else ExecuteAction();
332}
333
334void FrontendAction::EndSourceFile() {
335  CompilerInstance &CI = getCompilerInstance();
336
337  // Inform the diagnostic client we are done with this source file.
338  CI.getDiagnosticClient().EndSourceFile();
339
340  // Finalize the action.
341  EndSourceFileAction();
342
343  // Release the consumer and the AST, in that order since the consumer may
344  // perform actions in its destructor which require the context.
345  //
346  // FIXME: There is more per-file stuff we could just drop here?
347  if (CI.getFrontendOpts().DisableFree) {
348    CI.takeASTConsumer();
349    if (!isCurrentFileAST()) {
350      CI.takeSema();
351      CI.resetAndLeakASTContext();
352    }
353  } else {
354    if (!isCurrentFileAST()) {
355      CI.setSema(0);
356      CI.setASTContext(0);
357    }
358    CI.setASTConsumer(0);
359  }
360
361  // Inform the preprocessor we are done.
362  if (CI.hasPreprocessor())
363    CI.getPreprocessor().EndSourceFile();
364
365  if (CI.getFrontendOpts().ShowStats) {
366    llvm::errs() << "\nSTATISTICS FOR '" << getCurrentFile() << "':\n";
367    CI.getPreprocessor().PrintStats();
368    CI.getPreprocessor().getIdentifierTable().PrintStats();
369    CI.getPreprocessor().getHeaderSearchInfo().PrintStats();
370    CI.getSourceManager().PrintStats();
371    llvm::errs() << "\n";
372  }
373
374  // Cleanup the output streams, and erase the output files if we encountered
375  // an error.
376  CI.clearOutputFiles(/*EraseFiles=*/CI.getDiagnostics().hasErrorOccurred());
377
378  if (isCurrentFileAST()) {
379    CI.takeSema();
380    CI.resetAndLeakASTContext();
381    CI.resetAndLeakPreprocessor();
382    CI.resetAndLeakSourceManager();
383    CI.resetAndLeakFileManager();
384  }
385
386  setCompilerInstance(0);
387  setCurrentFile("", IK_None);
388}
389
390//===----------------------------------------------------------------------===//
391// Utility Actions
392//===----------------------------------------------------------------------===//
393
394void ASTFrontendAction::ExecuteAction() {
395  CompilerInstance &CI = getCompilerInstance();
396
397  // FIXME: Move the truncation aspect of this into Sema, we delayed this till
398  // here so the source manager would be initialized.
399  if (hasCodeCompletionSupport() &&
400      !CI.getFrontendOpts().CodeCompletionAt.FileName.empty())
401    CI.createCodeCompletionConsumer();
402
403  // Use a code completion consumer?
404  CodeCompleteConsumer *CompletionConsumer = 0;
405  if (CI.hasCodeCompletionConsumer())
406    CompletionConsumer = &CI.getCodeCompletionConsumer();
407
408  if (!CI.hasSema())
409    CI.createSema(getTranslationUnitKind(), CompletionConsumer);
410
411  ParseAST(CI.getSema(), CI.getFrontendOpts().ShowStats);
412}
413
414ASTConsumer *
415PreprocessorFrontendAction::CreateASTConsumer(CompilerInstance &CI,
416                                              StringRef InFile) {
417  llvm_unreachable("Invalid CreateASTConsumer on preprocessor action!");
418}
419
420ASTConsumer *WrapperFrontendAction::CreateASTConsumer(CompilerInstance &CI,
421                                                      StringRef InFile) {
422  return WrappedAction->CreateASTConsumer(CI, InFile);
423}
424bool WrapperFrontendAction::BeginInvocation(CompilerInstance &CI) {
425  return WrappedAction->BeginInvocation(CI);
426}
427bool WrapperFrontendAction::BeginSourceFileAction(CompilerInstance &CI,
428                                                  StringRef Filename) {
429  WrappedAction->setCurrentFile(getCurrentFile(), getCurrentFileKind());
430  WrappedAction->setCompilerInstance(&CI);
431  return WrappedAction->BeginSourceFileAction(CI, Filename);
432}
433void WrapperFrontendAction::ExecuteAction() {
434  WrappedAction->ExecuteAction();
435}
436void WrapperFrontendAction::EndSourceFileAction() {
437  WrappedAction->EndSourceFileAction();
438}
439
440bool WrapperFrontendAction::usesPreprocessorOnly() const {
441  return WrappedAction->usesPreprocessorOnly();
442}
443TranslationUnitKind WrapperFrontendAction::getTranslationUnitKind() {
444  return WrappedAction->getTranslationUnitKind();
445}
446bool WrapperFrontendAction::hasPCHSupport() const {
447  return WrappedAction->hasPCHSupport();
448}
449bool WrapperFrontendAction::hasASTFileSupport() const {
450  return WrappedAction->hasASTFileSupport();
451}
452bool WrapperFrontendAction::hasIRSupport() const {
453  return WrappedAction->hasIRSupport();
454}
455bool WrapperFrontendAction::hasCodeCompletionSupport() const {
456  return WrappedAction->hasCodeCompletionSupport();
457}
458
459WrapperFrontendAction::WrapperFrontendAction(FrontendAction *WrappedAction)
460  : WrappedAction(WrappedAction) {}
461
462