FrontendAction.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331
  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. if (!AST)
  91. goto failure;
  92. setCurrentFile(Filename, InputKind, AST);
  93. // Set the shared objects, these are reset when we finish processing the
  94. // file, otherwise the CompilerInstance will happily destroy them.
  95. CI.setFileManager(&AST->getFileManager());
  96. CI.setSourceManager(&AST->getSourceManager());
  97. CI.setPreprocessor(&AST->getPreprocessor());
  98. CI.setASTContext(&AST->getASTContext());
  99. // Initialize the action.
  100. if (!BeginSourceFileAction(CI, Filename))
  101. goto failure;
  102. /// Create the AST consumer.
  103. CI.setASTConsumer(CreateASTConsumer(CI, Filename));
  104. if (!CI.hasASTConsumer())
  105. goto failure;
  106. return true;
  107. }
  108. // Set up the file and source managers, if needed.
  109. if (!CI.hasFileManager())
  110. CI.createFileManager();
  111. if (!CI.hasSourceManager())
  112. CI.createSourceManager();
  113. // IR files bypass the rest of initialization.
  114. if (InputKind == IK_LLVM_IR) {
  115. assert(hasIRSupport() &&
  116. "This action does not have IR file support!");
  117. // Inform the diagnostic client we are processing a source file.
  118. CI.getDiagnosticClient().BeginSourceFile(CI.getLangOpts(), 0);
  119. // Initialize the action.
  120. if (!BeginSourceFileAction(CI, Filename))
  121. goto failure;
  122. return true;
  123. }
  124. // Set up the preprocessor.
  125. CI.createPreprocessor();
  126. // Inform the diagnostic client we are processing a source file.
  127. CI.getDiagnosticClient().BeginSourceFile(CI.getLangOpts(),
  128. &CI.getPreprocessor());
  129. // Initialize the action.
  130. if (!BeginSourceFileAction(CI, Filename))
  131. goto failure;
  132. /// Create the AST context and consumer unless this is a preprocessor only
  133. /// action.
  134. if (!usesPreprocessorOnly()) {
  135. CI.createASTContext();
  136. llvm::OwningPtr<ASTConsumer> Consumer(CreateASTConsumer(CI, Filename));
  137. /// Use PCH?
  138. if (!CI.getPreprocessorOpts().ImplicitPCHInclude.empty()) {
  139. assert(hasPCHSupport() && "This action does not have PCH support!");
  140. ASTDeserializationListener *DeserialListener
  141. = CI.getInvocation().getFrontendOpts().ChainedPCH ?
  142. Consumer->GetASTDeserializationListener() : 0;
  143. if (CI.getPreprocessorOpts().DumpDeserializedPCHDecls)
  144. DeserialListener = new DeserializedDeclsDumper(DeserialListener);
  145. if (!CI.getPreprocessorOpts().DeserializedPCHDeclsToErrorOn.empty())
  146. DeserialListener = new DeserializedDeclsChecker(CI.getASTContext(),
  147. CI.getPreprocessorOpts().DeserializedPCHDeclsToErrorOn,
  148. DeserialListener);
  149. CI.createPCHExternalASTSource(
  150. CI.getPreprocessorOpts().ImplicitPCHInclude,
  151. CI.getPreprocessorOpts().DisablePCHValidation,
  152. DeserialListener);
  153. if (!CI.getASTContext().getExternalSource())
  154. goto failure;
  155. }
  156. CI.setASTConsumer(Consumer.take());
  157. if (!CI.hasASTConsumer())
  158. goto failure;
  159. }
  160. // Initialize builtin info as long as we aren't using an external AST
  161. // source.
  162. if (!CI.hasASTContext() || !CI.getASTContext().getExternalSource()) {
  163. Preprocessor &PP = CI.getPreprocessor();
  164. PP.getBuiltinInfo().InitializeBuiltins(PP.getIdentifierTable(),
  165. PP.getLangOptions().NoBuiltin);
  166. }
  167. return true;
  168. // If we failed, reset state since the client will not end up calling the
  169. // matching EndSourceFile().
  170. failure:
  171. if (isCurrentFileAST()) {
  172. CI.takeASTContext();
  173. CI.takePreprocessor();
  174. CI.takeSourceManager();
  175. CI.takeFileManager();
  176. }
  177. CI.getDiagnosticClient().EndSourceFile();
  178. setCurrentFile("", IK_None);
  179. setCompilerInstance(0);
  180. return false;
  181. }
  182. void FrontendAction::Execute() {
  183. CompilerInstance &CI = getCompilerInstance();
  184. // Initialize the main file entry. This needs to be delayed until after PCH
  185. // has loaded.
  186. if (isCurrentFileAST()) {
  187. // Set the main file ID to an empty file.
  188. //
  189. // FIXME: We probably shouldn't need this, but for now this is the
  190. // simplest way to reuse the logic in ParseAST.
  191. const char *EmptyStr = "";
  192. llvm::MemoryBuffer *SB =
  193. llvm::MemoryBuffer::getMemBuffer(EmptyStr, "<dummy input>");
  194. CI.getSourceManager().createMainFileIDForMemBuffer(SB);
  195. } else {
  196. if (!CI.InitializeSourceManager(getCurrentFile()))
  197. return;
  198. }
  199. if (CI.hasFrontendTimer()) {
  200. llvm::TimeRegion Timer(CI.getFrontendTimer());
  201. ExecuteAction();
  202. }
  203. else ExecuteAction();
  204. }
  205. void FrontendAction::EndSourceFile() {
  206. CompilerInstance &CI = getCompilerInstance();
  207. // Finalize the action.
  208. EndSourceFileAction();
  209. // Release the consumer and the AST, in that order since the consumer may
  210. // perform actions in its destructor which require the context.
  211. //
  212. // FIXME: There is more per-file stuff we could just drop here?
  213. if (CI.getFrontendOpts().DisableFree) {
  214. CI.takeASTConsumer();
  215. if (!isCurrentFileAST()) {
  216. CI.takeSema();
  217. CI.takeASTContext();
  218. }
  219. } else {
  220. if (!isCurrentFileAST()) {
  221. CI.setSema(0);
  222. CI.setASTContext(0);
  223. }
  224. CI.setASTConsumer(0);
  225. }
  226. // Inform the preprocessor we are done.
  227. if (CI.hasPreprocessor())
  228. CI.getPreprocessor().EndSourceFile();
  229. if (CI.getFrontendOpts().ShowStats) {
  230. llvm::errs() << "\nSTATISTICS FOR '" << getCurrentFile() << "':\n";
  231. CI.getPreprocessor().PrintStats();
  232. CI.getPreprocessor().getIdentifierTable().PrintStats();
  233. CI.getPreprocessor().getHeaderSearchInfo().PrintStats();
  234. CI.getSourceManager().PrintStats();
  235. llvm::errs() << "\n";
  236. }
  237. // Cleanup the output streams, and erase the output files if we encountered
  238. // an error.
  239. CI.clearOutputFiles(/*EraseFiles=*/CI.getDiagnostics().getNumErrors());
  240. // Inform the diagnostic client we are done with this source file.
  241. CI.getDiagnosticClient().EndSourceFile();
  242. if (isCurrentFileAST()) {
  243. CI.takeSema();
  244. CI.takeASTContext();
  245. CI.takePreprocessor();
  246. CI.takeSourceManager();
  247. CI.takeFileManager();
  248. }
  249. setCompilerInstance(0);
  250. setCurrentFile("", IK_None);
  251. }
  252. //===----------------------------------------------------------------------===//
  253. // Utility Actions
  254. //===----------------------------------------------------------------------===//
  255. void ASTFrontendAction::ExecuteAction() {
  256. CompilerInstance &CI = getCompilerInstance();
  257. // FIXME: Move the truncation aspect of this into Sema, we delayed this till
  258. // here so the source manager would be initialized.
  259. if (hasCodeCompletionSupport() &&
  260. !CI.getFrontendOpts().CodeCompletionAt.FileName.empty())
  261. CI.createCodeCompletionConsumer();
  262. // Use a code completion consumer?
  263. CodeCompleteConsumer *CompletionConsumer = 0;
  264. if (CI.hasCodeCompletionConsumer())
  265. CompletionConsumer = &CI.getCodeCompletionConsumer();
  266. if (!CI.hasSema())
  267. CI.createSema(usesCompleteTranslationUnit(), CompletionConsumer);
  268. ParseAST(CI.getSema(), CI.getFrontendOpts().ShowStats);
  269. }
  270. ASTConsumer *
  271. PreprocessorFrontendAction::CreateASTConsumer(CompilerInstance &CI,
  272. llvm::StringRef InFile) {
  273. llvm_unreachable("Invalid CreateASTConsumer on preprocessor action!");
  274. }