FrontendAction.cpp 11 KB

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