FrontendAction.cpp 16 KB

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