FrontendAction.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345
  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. #include "clang/Frontend/FrontendAction.h"
  10. #include "clang/AST/ASTConsumer.h"
  11. #include "clang/AST/ASTContext.h"
  12. #include "clang/Lex/HeaderSearch.h"
  13. #include "clang/Lex/Preprocessor.h"
  14. #include "clang/Frontend/ASTUnit.h"
  15. #include "clang/Frontend/CompilerInstance.h"
  16. #include "clang/Frontend/FrontendDiagnostic.h"
  17. #include "clang/Parse/ParseAST.h"
  18. #include "clang/Serialization/ASTDeserializationListener.h"
  19. #include "llvm/Support/MemoryBuffer.h"
  20. #include "llvm/Support/Timer.h"
  21. #include "llvm/Support/ErrorHandling.h"
  22. #include "llvm/Support/raw_ostream.h"
  23. using namespace clang;
  24. namespace {
  25. /// \brief Dumps deserialized declarations.
  26. class DeserializedDeclsDumper : public ASTDeserializationListener {
  27. ASTDeserializationListener *Previous;
  28. public:
  29. DeserializedDeclsDumper(ASTDeserializationListener *Previous)
  30. : Previous(Previous) { }
  31. virtual void DeclRead(serialization::DeclID ID, const Decl *D) {
  32. llvm::outs() << "PCH DECL: " << D->getDeclKindName();
  33. if (const NamedDecl *ND = dyn_cast<NamedDecl>(D))
  34. llvm::outs() << " - " << ND->getNameAsString();
  35. llvm::outs() << "\n";
  36. if (Previous)
  37. Previous->DeclRead(ID, D);
  38. }
  39. virtual void SetReader(ASTReader *Reader) {}
  40. virtual void IdentifierRead(serialization::IdentID ID, IdentifierInfo *II) {}
  41. virtual void TypeRead(serialization::TypeIdx Idx, QualType T) {}
  42. virtual void SelectorRead(serialization::SelectorID iD, Selector Sel) {}
  43. virtual void MacroDefinitionRead(serialization::MacroID,
  44. MacroDefinition *MD) {}
  45. };
  46. /// \brief Checks deserialized declarations and emits error if a name
  47. /// matches one given in command-line using -error-on-deserialized-decl.
  48. class DeserializedDeclsChecker : public ASTDeserializationListener {
  49. ASTContext &Ctx;
  50. std::set<std::string> NamesToCheck;
  51. ASTDeserializationListener *Previous;
  52. public:
  53. DeserializedDeclsChecker(ASTContext &Ctx,
  54. const std::set<std::string> &NamesToCheck,
  55. ASTDeserializationListener *Previous)
  56. : Ctx(Ctx), NamesToCheck(NamesToCheck), Previous(Previous) { }
  57. virtual void DeclRead(serialization::DeclID ID, const Decl *D) {
  58. if (const NamedDecl *ND = dyn_cast<NamedDecl>(D))
  59. if (NamesToCheck.find(ND->getNameAsString()) != NamesToCheck.end()) {
  60. unsigned DiagID
  61. = Ctx.getDiagnostics().getCustomDiagID(Diagnostic::Error,
  62. "%0 was deserialized");
  63. Ctx.getDiagnostics().Report(Ctx.getFullLoc(D->getLocation()), DiagID)
  64. << ND->getNameAsString();
  65. }
  66. if (Previous)
  67. Previous->DeclRead(ID, D);
  68. }
  69. virtual void SetReader(ASTReader *Reader) {}
  70. virtual void IdentifierRead(serialization::IdentID ID, IdentifierInfo *II) {}
  71. virtual void TypeRead(serialization::TypeIdx Idx, QualType T) {}
  72. virtual void SelectorRead(serialization::SelectorID iD, Selector Sel) {}
  73. virtual void MacroDefinitionRead(serialization::MacroID,
  74. MacroDefinition *MD) {}
  75. };
  76. } // end anonymous namespace
  77. FrontendAction::FrontendAction() : Instance(0) {}
  78. FrontendAction::~FrontendAction() {}
  79. void FrontendAction::setCurrentFile(llvm::StringRef Value, InputKind Kind,
  80. ASTUnit *AST) {
  81. CurrentFile = Value;
  82. CurrentFileKind = Kind;
  83. CurrentASTUnit.reset(AST);
  84. }
  85. bool FrontendAction::BeginSourceFile(CompilerInstance &CI,
  86. llvm::StringRef Filename,
  87. InputKind InputKind) {
  88. assert(!Instance && "Already processing a source file!");
  89. assert(!Filename.empty() && "Unexpected empty filename!");
  90. setCurrentFile(Filename, InputKind);
  91. setCompilerInstance(&CI);
  92. // AST files follow a very different path, since they share objects via the
  93. // AST unit.
  94. if (InputKind == IK_AST) {
  95. assert(!usesPreprocessorOnly() &&
  96. "Attempt to pass AST file to preprocessor only action!");
  97. assert(hasASTFileSupport() &&
  98. "This action does not have AST file support!");
  99. llvm::IntrusiveRefCntPtr<Diagnostic> Diags(&CI.getDiagnostics());
  100. std::string Error;
  101. ASTUnit *AST = ASTUnit::LoadFromASTFile(Filename, Diags);
  102. if (!AST)
  103. goto failure;
  104. setCurrentFile(Filename, InputKind, AST);
  105. // Set the shared objects, these are reset when we finish processing the
  106. // file, otherwise the CompilerInstance will happily destroy them.
  107. CI.setFileManager(&AST->getFileManager());
  108. CI.setSourceManager(&AST->getSourceManager());
  109. CI.setPreprocessor(&AST->getPreprocessor());
  110. CI.setASTContext(&AST->getASTContext());
  111. // Initialize the action.
  112. if (!BeginSourceFileAction(CI, Filename))
  113. goto failure;
  114. /// Create the AST consumer.
  115. CI.setASTConsumer(CreateASTConsumer(CI, Filename));
  116. if (!CI.hasASTConsumer())
  117. goto failure;
  118. return true;
  119. }
  120. // Set up the file and source managers, if needed.
  121. if (!CI.hasFileManager())
  122. CI.createFileManager();
  123. if (!CI.hasSourceManager())
  124. CI.createSourceManager();
  125. // IR files bypass the rest of initialization.
  126. if (InputKind == IK_LLVM_IR) {
  127. assert(hasIRSupport() &&
  128. "This action does not have IR file support!");
  129. // Inform the diagnostic client we are processing a source file.
  130. CI.getDiagnosticClient().BeginSourceFile(CI.getLangOpts(), 0);
  131. // Initialize the action.
  132. if (!BeginSourceFileAction(CI, Filename))
  133. goto failure;
  134. return true;
  135. }
  136. // Set up the preprocessor.
  137. CI.createPreprocessor();
  138. // Inform the diagnostic client we are processing a source file.
  139. CI.getDiagnosticClient().BeginSourceFile(CI.getLangOpts(),
  140. &CI.getPreprocessor());
  141. // Initialize the action.
  142. if (!BeginSourceFileAction(CI, Filename))
  143. goto failure;
  144. /// Create the AST context and consumer unless this is a preprocessor only
  145. /// action.
  146. if (!usesPreprocessorOnly()) {
  147. CI.createASTContext();
  148. llvm::OwningPtr<ASTConsumer> Consumer(CreateASTConsumer(CI, Filename));
  149. /// Use PCH?
  150. if (!CI.getPreprocessorOpts().ImplicitPCHInclude.empty()) {
  151. assert(hasPCHSupport() && "This action does not have PCH support!");
  152. ASTDeserializationListener *DeserialListener
  153. = CI.getInvocation().getFrontendOpts().ChainedPCH ?
  154. Consumer->GetASTDeserializationListener() : 0;
  155. if (CI.getPreprocessorOpts().DumpDeserializedPCHDecls)
  156. DeserialListener = new DeserializedDeclsDumper(DeserialListener);
  157. if (!CI.getPreprocessorOpts().DeserializedPCHDeclsToErrorOn.empty())
  158. DeserialListener = new DeserializedDeclsChecker(CI.getASTContext(),
  159. CI.getPreprocessorOpts().DeserializedPCHDeclsToErrorOn,
  160. DeserialListener);
  161. CI.createPCHExternalASTSource(
  162. CI.getPreprocessorOpts().ImplicitPCHInclude,
  163. CI.getPreprocessorOpts().DisablePCHValidation,
  164. DeserialListener);
  165. if (!CI.getASTContext().getExternalSource())
  166. goto failure;
  167. }
  168. CI.setASTConsumer(Consumer.take());
  169. if (!CI.hasASTConsumer())
  170. goto failure;
  171. }
  172. // Initialize builtin info as long as we aren't using an external AST
  173. // source.
  174. if (!CI.hasASTContext() || !CI.getASTContext().getExternalSource()) {
  175. Preprocessor &PP = CI.getPreprocessor();
  176. PP.getBuiltinInfo().InitializeBuiltins(PP.getIdentifierTable(),
  177. PP.getLangOptions().NoBuiltin);
  178. }
  179. return true;
  180. // If we failed, reset state since the client will not end up calling the
  181. // matching EndSourceFile().
  182. failure:
  183. if (isCurrentFileAST()) {
  184. CI.takeASTContext();
  185. CI.takePreprocessor();
  186. CI.takeSourceManager();
  187. CI.takeFileManager();
  188. }
  189. CI.getDiagnosticClient().EndSourceFile();
  190. setCurrentFile("", IK_None);
  191. setCompilerInstance(0);
  192. return false;
  193. }
  194. void FrontendAction::Execute() {
  195. CompilerInstance &CI = getCompilerInstance();
  196. // Initialize the main file entry. This needs to be delayed until after PCH
  197. // has loaded.
  198. if (isCurrentFileAST()) {
  199. // Set the main file ID to an empty file.
  200. //
  201. // FIXME: We probably shouldn't need this, but for now this is the
  202. // simplest way to reuse the logic in ParseAST.
  203. const char *EmptyStr = "";
  204. llvm::MemoryBuffer *SB =
  205. llvm::MemoryBuffer::getMemBuffer(EmptyStr, "<dummy input>");
  206. CI.getSourceManager().createMainFileIDForMemBuffer(SB);
  207. } else {
  208. if (!CI.InitializeSourceManager(getCurrentFile()))
  209. return;
  210. }
  211. if (CI.hasFrontendTimer()) {
  212. llvm::TimeRegion Timer(CI.getFrontendTimer());
  213. ExecuteAction();
  214. }
  215. else ExecuteAction();
  216. }
  217. void FrontendAction::EndSourceFile() {
  218. CompilerInstance &CI = getCompilerInstance();
  219. // Finalize the action.
  220. EndSourceFileAction();
  221. // Release the consumer and the AST, in that order since the consumer may
  222. // perform actions in its destructor which require the context.
  223. //
  224. // FIXME: There is more per-file stuff we could just drop here?
  225. if (CI.getFrontendOpts().DisableFree) {
  226. CI.takeASTConsumer();
  227. if (!isCurrentFileAST()) {
  228. CI.takeSema();
  229. CI.takeASTContext();
  230. }
  231. } else {
  232. if (!isCurrentFileAST()) {
  233. CI.setSema(0);
  234. CI.setASTContext(0);
  235. }
  236. CI.setASTConsumer(0);
  237. }
  238. // Inform the preprocessor we are done.
  239. if (CI.hasPreprocessor())
  240. CI.getPreprocessor().EndSourceFile();
  241. if (CI.getFrontendOpts().ShowStats) {
  242. llvm::errs() << "\nSTATISTICS FOR '" << getCurrentFile() << "':\n";
  243. CI.getPreprocessor().PrintStats();
  244. CI.getPreprocessor().getIdentifierTable().PrintStats();
  245. CI.getPreprocessor().getHeaderSearchInfo().PrintStats();
  246. CI.getSourceManager().PrintStats();
  247. llvm::errs() << "\n";
  248. }
  249. // Cleanup the output streams, and erase the output files if we encountered
  250. // an error.
  251. CI.clearOutputFiles(/*EraseFiles=*/CI.getDiagnostics().getNumErrors());
  252. // Inform the diagnostic client we are done with this source file.
  253. CI.getDiagnosticClient().EndSourceFile();
  254. if (isCurrentFileAST()) {
  255. CI.takeSema();
  256. CI.takeASTContext();
  257. CI.takePreprocessor();
  258. CI.takeSourceManager();
  259. CI.takeFileManager();
  260. }
  261. setCompilerInstance(0);
  262. setCurrentFile("", IK_None);
  263. }
  264. //===----------------------------------------------------------------------===//
  265. // Utility Actions
  266. //===----------------------------------------------------------------------===//
  267. void ASTFrontendAction::ExecuteAction() {
  268. CompilerInstance &CI = getCompilerInstance();
  269. // FIXME: Move the truncation aspect of this into Sema, we delayed this till
  270. // here so the source manager would be initialized.
  271. if (hasCodeCompletionSupport() &&
  272. !CI.getFrontendOpts().CodeCompletionAt.FileName.empty())
  273. CI.createCodeCompletionConsumer();
  274. // Use a code completion consumer?
  275. CodeCompleteConsumer *CompletionConsumer = 0;
  276. if (CI.hasCodeCompletionConsumer())
  277. CompletionConsumer = &CI.getCodeCompletionConsumer();
  278. if (!CI.hasSema())
  279. CI.createSema(usesCompleteTranslationUnit(), CompletionConsumer);
  280. ParseAST(CI.getSema(), CI.getFrontendOpts().ShowStats);
  281. }
  282. ASTConsumer *
  283. PreprocessorFrontendAction::CreateASTConsumer(CompilerInstance &CI,
  284. llvm::StringRef InFile) {
  285. llvm_unreachable("Invalid CreateASTConsumer on preprocessor action!");
  286. }