FrontendAction.cpp revision f25649c74397d2620e6ac61f1045261644707c80
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 "llvm/Support/MemoryBuffer.h"
24#include "llvm/Support/Timer.h"
25#include "llvm/Support/ErrorHandling.h"
26#include "llvm/Support/raw_ostream.h"
27using namespace clang;
28
29namespace {
30
31/// \brief Dumps deserialized declarations.
32class DeserializedDeclsDumper : public ASTDeserializationListener {
33  ASTDeserializationListener *Previous;
34
35public:
36  DeserializedDeclsDumper(ASTDeserializationListener *Previous)
37    : Previous(Previous) { }
38
39  virtual void DeclRead(serialization::DeclID ID, const Decl *D) {
40    llvm::outs() << "PCH DECL: " << D->getDeclKindName();
41    if (const NamedDecl *ND = dyn_cast<NamedDecl>(D))
42      llvm::outs() << " - " << ND->getNameAsString();
43    llvm::outs() << "\n";
44
45    if (Previous)
46      Previous->DeclRead(ID, D);
47  }
48};
49
50  /// \brief Checks deserialized declarations and emits error if a name
51  /// matches one given in command-line using -error-on-deserialized-decl.
52  class DeserializedDeclsChecker : public ASTDeserializationListener {
53    ASTContext &Ctx;
54    std::set<std::string> NamesToCheck;
55    ASTDeserializationListener *Previous;
56
57  public:
58    DeserializedDeclsChecker(ASTContext &Ctx,
59                             const std::set<std::string> &NamesToCheck,
60                             ASTDeserializationListener *Previous)
61      : Ctx(Ctx), NamesToCheck(NamesToCheck), Previous(Previous) { }
62
63    virtual void DeclRead(serialization::DeclID ID, const Decl *D) {
64      if (const NamedDecl *ND = dyn_cast<NamedDecl>(D))
65        if (NamesToCheck.find(ND->getNameAsString()) != NamesToCheck.end()) {
66          unsigned DiagID
67            = Ctx.getDiagnostics().getCustomDiagID(Diagnostic::Error,
68                                                   "%0 was deserialized");
69          Ctx.getDiagnostics().Report(Ctx.getFullLoc(D->getLocation()), DiagID)
70              << ND->getNameAsString();
71        }
72
73      if (Previous)
74        Previous->DeclRead(ID, D);
75    }
76};
77
78} // end anonymous namespace
79
80FrontendAction::FrontendAction() : Instance(0) {}
81
82FrontendAction::~FrontendAction() {}
83
84void FrontendAction::setCurrentFile(llvm::StringRef Value, InputKind Kind,
85                                    ASTUnit *AST) {
86  CurrentFile = Value;
87  CurrentFileKind = Kind;
88  CurrentASTUnit.reset(AST);
89}
90
91ASTConsumer* FrontendAction::CreateWrappedASTConsumer(CompilerInstance &CI,
92                                                      llvm::StringRef InFile) {
93  ASTConsumer* Consumer = CreateASTConsumer(CI, InFile);
94  if (!Consumer)
95    return 0;
96
97  if (CI.getFrontendOpts().AddPluginActions.size() == 0)
98    return Consumer;
99
100  // Make sure the non-plugin consumer is first, so that plugins can't
101  // modifiy the AST.
102  std::vector<ASTConsumer*> Consumers(1, Consumer);
103
104  for (size_t i = 0, e = CI.getFrontendOpts().AddPluginActions.size();
105       i != e; ++i) {
106    // This is O(|plugins| * |add_plugins|), but since both numbers are
107    // way below 50 in practice, that's ok.
108    for (FrontendPluginRegistry::iterator
109        it = FrontendPluginRegistry::begin(),
110        ie = FrontendPluginRegistry::end();
111        it != ie; ++it) {
112      if (it->getName() == CI.getFrontendOpts().AddPluginActions[i]) {
113        llvm::OwningPtr<PluginASTAction> P(it->instantiate());
114        FrontendAction* c = P.get();
115        if (P->ParseArgs(CI, CI.getFrontendOpts().AddPluginArgs[i]))
116          Consumers.push_back(c->CreateASTConsumer(CI, InFile));
117      }
118    }
119  }
120
121  return new MultiplexConsumer(Consumers);
122}
123
124bool FrontendAction::BeginSourceFile(CompilerInstance &CI,
125                                     llvm::StringRef Filename,
126                                     InputKind InputKind) {
127  assert(!Instance && "Already processing a source file!");
128  assert(!Filename.empty() && "Unexpected empty filename!");
129  setCurrentFile(Filename, InputKind);
130  setCompilerInstance(&CI);
131
132  // AST files follow a very different path, since they share objects via the
133  // AST unit.
134  if (InputKind == IK_AST) {
135    assert(!usesPreprocessorOnly() &&
136           "Attempt to pass AST file to preprocessor only action!");
137    assert(hasASTFileSupport() &&
138           "This action does not have AST file support!");
139
140    llvm::IntrusiveRefCntPtr<Diagnostic> Diags(&CI.getDiagnostics());
141    std::string Error;
142    ASTUnit *AST = ASTUnit::LoadFromASTFile(Filename, Diags,
143                                            CI.getFileSystemOpts());
144    if (!AST)
145      goto failure;
146
147    setCurrentFile(Filename, InputKind, AST);
148
149    // Set the shared objects, these are reset when we finish processing the
150    // file, otherwise the CompilerInstance will happily destroy them.
151    CI.setFileManager(&AST->getFileManager());
152    CI.setSourceManager(&AST->getSourceManager());
153    CI.setPreprocessor(&AST->getPreprocessor());
154    CI.setASTContext(&AST->getASTContext());
155
156    // Initialize the action.
157    if (!BeginSourceFileAction(CI, Filename))
158      goto failure;
159
160    /// Create the AST consumer.
161    CI.setASTConsumer(CreateWrappedASTConsumer(CI, Filename));
162    if (!CI.hasASTConsumer())
163      goto failure;
164
165    return true;
166  }
167
168  // Set up the file and source managers, if needed.
169  if (!CI.hasFileManager())
170    CI.createFileManager();
171  if (!CI.hasSourceManager())
172    CI.createSourceManager(CI.getFileManager());
173
174  // IR files bypass the rest of initialization.
175  if (InputKind == IK_LLVM_IR) {
176    assert(hasIRSupport() &&
177           "This action does not have IR file support!");
178
179    // Inform the diagnostic client we are processing a source file.
180    CI.getDiagnosticClient().BeginSourceFile(CI.getLangOpts(), 0);
181
182    // Initialize the action.
183    if (!BeginSourceFileAction(CI, Filename))
184      goto failure;
185
186    return true;
187  }
188
189  // Set up the preprocessor.
190  CI.createPreprocessor();
191
192  // Inform the diagnostic client we are processing a source file.
193  CI.getDiagnosticClient().BeginSourceFile(CI.getLangOpts(),
194                                           &CI.getPreprocessor());
195
196  // Initialize the action.
197  if (!BeginSourceFileAction(CI, Filename))
198    goto failure;
199
200  /// Create the AST context and consumer unless this is a preprocessor only
201  /// action.
202  if (!usesPreprocessorOnly()) {
203    CI.createASTContext();
204
205    llvm::OwningPtr<ASTConsumer> Consumer(
206        CreateWrappedASTConsumer(CI, Filename));
207    if (!Consumer)
208      goto failure;
209
210    CI.getASTContext().setASTMutationListener(Consumer->GetASTMutationListener());
211
212    /// Use PCH?
213    if (!CI.getPreprocessorOpts().ImplicitPCHInclude.empty()) {
214      assert(hasPCHSupport() && "This action does not have PCH support!");
215      ASTDeserializationListener *DeserialListener
216          = CI.getInvocation().getFrontendOpts().ChainedPCH ?
217                  Consumer->GetASTDeserializationListener() : 0;
218      if (CI.getPreprocessorOpts().DumpDeserializedPCHDecls)
219        DeserialListener = new DeserializedDeclsDumper(DeserialListener);
220      if (!CI.getPreprocessorOpts().DeserializedPCHDeclsToErrorOn.empty())
221        DeserialListener = new DeserializedDeclsChecker(CI.getASTContext(),
222                         CI.getPreprocessorOpts().DeserializedPCHDeclsToErrorOn,
223                                                        DeserialListener);
224      CI.createPCHExternalASTSource(
225                                CI.getPreprocessorOpts().ImplicitPCHInclude,
226                                CI.getPreprocessorOpts().DisablePCHValidation,
227                                DeserialListener);
228      if (!CI.getASTContext().getExternalSource())
229        goto failure;
230    }
231
232    CI.setASTConsumer(Consumer.take());
233    if (!CI.hasASTConsumer())
234      goto failure;
235  }
236
237  // Initialize builtin info as long as we aren't using an external AST
238  // source.
239  if (!CI.hasASTContext() || !CI.getASTContext().getExternalSource()) {
240    Preprocessor &PP = CI.getPreprocessor();
241    PP.getBuiltinInfo().InitializeBuiltins(PP.getIdentifierTable(),
242                                           PP.getLangOptions());
243  }
244
245  return true;
246
247  // If we failed, reset state since the client will not end up calling the
248  // matching EndSourceFile().
249  failure:
250  if (isCurrentFileAST()) {
251    CI.takeASTContext();
252    CI.takePreprocessor();
253    CI.takeSourceManager();
254    CI.takeFileManager();
255  }
256
257  CI.getDiagnosticClient().EndSourceFile();
258  setCurrentFile("", IK_None);
259  setCompilerInstance(0);
260  return false;
261}
262
263void FrontendAction::Execute() {
264  CompilerInstance &CI = getCompilerInstance();
265
266  // Initialize the main file entry. This needs to be delayed until after PCH
267  // has loaded.
268  if (isCurrentFileAST()) {
269    // Set the main file ID to an empty file.
270    //
271    // FIXME: We probably shouldn't need this, but for now this is the
272    // simplest way to reuse the logic in ParseAST.
273    const char *EmptyStr = "";
274    llvm::MemoryBuffer *SB =
275      llvm::MemoryBuffer::getMemBuffer(EmptyStr, "<dummy input>");
276    CI.getSourceManager().createMainFileIDForMemBuffer(SB);
277  } else {
278    if (!CI.InitializeSourceManager(getCurrentFile()))
279      return;
280  }
281
282  if (CI.hasFrontendTimer()) {
283    llvm::TimeRegion Timer(CI.getFrontendTimer());
284    ExecuteAction();
285  }
286  else ExecuteAction();
287}
288
289void FrontendAction::EndSourceFile() {
290  CompilerInstance &CI = getCompilerInstance();
291
292  // Finalize the action.
293  EndSourceFileAction();
294
295  // Release the consumer and the AST, in that order since the consumer may
296  // perform actions in its destructor which require the context.
297  //
298  // FIXME: There is more per-file stuff we could just drop here?
299  if (CI.getFrontendOpts().DisableFree) {
300    CI.takeASTConsumer();
301    if (!isCurrentFileAST()) {
302      CI.takeSema();
303      CI.takeASTContext();
304    }
305  } else {
306    if (!isCurrentFileAST()) {
307      CI.setSema(0);
308      CI.setASTContext(0);
309    }
310    CI.setASTConsumer(0);
311  }
312
313  // Inform the preprocessor we are done.
314  if (CI.hasPreprocessor())
315    CI.getPreprocessor().EndSourceFile();
316
317  if (CI.getFrontendOpts().ShowStats) {
318    llvm::errs() << "\nSTATISTICS FOR '" << getCurrentFile() << "':\n";
319    CI.getPreprocessor().PrintStats();
320    CI.getPreprocessor().getIdentifierTable().PrintStats();
321    CI.getPreprocessor().getHeaderSearchInfo().PrintStats();
322    CI.getSourceManager().PrintStats();
323    llvm::errs() << "\n";
324  }
325
326  // Cleanup the output streams, and erase the output files if we encountered
327  // an error.
328  CI.clearOutputFiles(/*EraseFiles=*/CI.getDiagnostics().hasErrorOccurred());
329
330  // Inform the diagnostic client we are done with this source file.
331  CI.getDiagnosticClient().EndSourceFile();
332
333  if (isCurrentFileAST()) {
334    CI.takeSema();
335    CI.takeASTContext();
336    CI.takePreprocessor();
337    CI.takeSourceManager();
338    CI.takeFileManager();
339  }
340
341  setCompilerInstance(0);
342  setCurrentFile("", IK_None);
343}
344
345//===----------------------------------------------------------------------===//
346// Utility Actions
347//===----------------------------------------------------------------------===//
348
349void ASTFrontendAction::ExecuteAction() {
350  CompilerInstance &CI = getCompilerInstance();
351
352  // FIXME: Move the truncation aspect of this into Sema, we delayed this till
353  // here so the source manager would be initialized.
354  if (hasCodeCompletionSupport() &&
355      !CI.getFrontendOpts().CodeCompletionAt.FileName.empty())
356    CI.createCodeCompletionConsumer();
357
358  // Use a code completion consumer?
359  CodeCompleteConsumer *CompletionConsumer = 0;
360  if (CI.hasCodeCompletionConsumer())
361    CompletionConsumer = &CI.getCodeCompletionConsumer();
362
363  if (!CI.hasSema())
364    CI.createSema(usesCompleteTranslationUnit(), CompletionConsumer);
365
366  ParseAST(CI.getSema(), CI.getFrontendOpts().ShowStats);
367}
368
369ASTConsumer *
370PreprocessorFrontendAction::CreateASTConsumer(CompilerInstance &CI,
371                                              llvm::StringRef InFile) {
372  llvm_unreachable("Invalid CreateASTConsumer on preprocessor action!");
373}
374