FrontendAction.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467
  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;
  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. 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. CI.getPreprocessorOpts().AllowPCHWithCompilerErrors,
  229. DeserialListener);
  230. if (!CI.getASTContext().getExternalSource())
  231. goto failure;
  232. }
  233. CI.setASTConsumer(Consumer.take());
  234. if (!CI.hasASTConsumer())
  235. goto failure;
  236. }
  237. // Initialize built-in 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.getLangOpts());
  243. }
  244. // If there is a layout overrides file, attach an external AST source that
  245. // provides the layouts from that file.
  246. if (!CI.getFrontendOpts().OverrideRecordLayoutsFile.empty() &&
  247. CI.hasASTContext() && !CI.getASTContext().getExternalSource()) {
  248. OwningPtr<ExternalASTSource>
  249. Override(new LayoutOverrideSource(
  250. CI.getFrontendOpts().OverrideRecordLayoutsFile));
  251. CI.getASTContext().setExternalSource(Override);
  252. }
  253. return true;
  254. // If we failed, reset state since the client will not end up calling the
  255. // matching EndSourceFile().
  256. failure:
  257. if (isCurrentFileAST()) {
  258. CI.setASTContext(0);
  259. CI.setPreprocessor(0);
  260. CI.setSourceManager(0);
  261. CI.setFileManager(0);
  262. }
  263. CI.getDiagnosticClient().EndSourceFile();
  264. setCurrentInput(FrontendInputFile());
  265. setCompilerInstance(0);
  266. return false;
  267. }
  268. void FrontendAction::Execute() {
  269. CompilerInstance &CI = getCompilerInstance();
  270. // Initialize the main file entry. This needs to be delayed until after PCH
  271. // has loaded.
  272. if (!isCurrentFileAST()) {
  273. if (!CI.InitializeSourceManager(getCurrentFile(),
  274. getCurrentInput().IsSystem
  275. ? SrcMgr::C_System
  276. : SrcMgr::C_User))
  277. return;
  278. }
  279. if (CI.hasFrontendTimer()) {
  280. llvm::TimeRegion Timer(CI.getFrontendTimer());
  281. ExecuteAction();
  282. }
  283. else ExecuteAction();
  284. }
  285. void FrontendAction::EndSourceFile() {
  286. CompilerInstance &CI = getCompilerInstance();
  287. // Inform the diagnostic client we are done with this source file.
  288. CI.getDiagnosticClient().EndSourceFile();
  289. // Finalize the action.
  290. EndSourceFileAction();
  291. // Release the consumer and the AST, in that order since the consumer may
  292. // perform actions in its destructor which require the context.
  293. //
  294. // FIXME: There is more per-file stuff we could just drop here?
  295. if (CI.getFrontendOpts().DisableFree) {
  296. CI.takeASTConsumer();
  297. if (!isCurrentFileAST()) {
  298. CI.takeSema();
  299. CI.resetAndLeakASTContext();
  300. }
  301. } else {
  302. if (!isCurrentFileAST()) {
  303. CI.setSema(0);
  304. CI.setASTContext(0);
  305. }
  306. CI.setASTConsumer(0);
  307. }
  308. // Inform the preprocessor we are done.
  309. if (CI.hasPreprocessor())
  310. CI.getPreprocessor().EndSourceFile();
  311. if (CI.getFrontendOpts().ShowStats) {
  312. llvm::errs() << "\nSTATISTICS FOR '" << getCurrentFile() << "':\n";
  313. CI.getPreprocessor().PrintStats();
  314. CI.getPreprocessor().getIdentifierTable().PrintStats();
  315. CI.getPreprocessor().getHeaderSearchInfo().PrintStats();
  316. CI.getSourceManager().PrintStats();
  317. llvm::errs() << "\n";
  318. }
  319. // Cleanup the output streams, and erase the output files if we encountered
  320. // an error.
  321. CI.clearOutputFiles(/*EraseFiles=*/CI.getDiagnostics().hasErrorOccurred());
  322. if (isCurrentFileAST()) {
  323. CI.takeSema();
  324. CI.resetAndLeakASTContext();
  325. CI.resetAndLeakPreprocessor();
  326. CI.resetAndLeakSourceManager();
  327. CI.resetAndLeakFileManager();
  328. }
  329. setCompilerInstance(0);
  330. setCurrentInput(FrontendInputFile());
  331. }
  332. //===----------------------------------------------------------------------===//
  333. // Utility Actions
  334. //===----------------------------------------------------------------------===//
  335. void ASTFrontendAction::ExecuteAction() {
  336. CompilerInstance &CI = getCompilerInstance();
  337. // FIXME: Move the truncation aspect of this into Sema, we delayed this till
  338. // here so the source manager would be initialized.
  339. if (hasCodeCompletionSupport() &&
  340. !CI.getFrontendOpts().CodeCompletionAt.FileName.empty())
  341. CI.createCodeCompletionConsumer();
  342. // Use a code completion consumer?
  343. CodeCompleteConsumer *CompletionConsumer = 0;
  344. if (CI.hasCodeCompletionConsumer())
  345. CompletionConsumer = &CI.getCodeCompletionConsumer();
  346. if (!CI.hasSema())
  347. CI.createSema(getTranslationUnitKind(), CompletionConsumer);
  348. ParseAST(CI.getSema(), CI.getFrontendOpts().ShowStats);
  349. }
  350. void PluginASTAction::anchor() { }
  351. ASTConsumer *
  352. PreprocessorFrontendAction::CreateASTConsumer(CompilerInstance &CI,
  353. StringRef InFile) {
  354. llvm_unreachable("Invalid CreateASTConsumer on preprocessor action!");
  355. }
  356. ASTConsumer *WrapperFrontendAction::CreateASTConsumer(CompilerInstance &CI,
  357. StringRef InFile) {
  358. return WrappedAction->CreateASTConsumer(CI, InFile);
  359. }
  360. bool WrapperFrontendAction::BeginInvocation(CompilerInstance &CI) {
  361. return WrappedAction->BeginInvocation(CI);
  362. }
  363. bool WrapperFrontendAction::BeginSourceFileAction(CompilerInstance &CI,
  364. StringRef Filename) {
  365. WrappedAction->setCurrentInput(getCurrentInput());
  366. WrappedAction->setCompilerInstance(&CI);
  367. return WrappedAction->BeginSourceFileAction(CI, Filename);
  368. }
  369. void WrapperFrontendAction::ExecuteAction() {
  370. WrappedAction->ExecuteAction();
  371. }
  372. void WrapperFrontendAction::EndSourceFileAction() {
  373. WrappedAction->EndSourceFileAction();
  374. }
  375. bool WrapperFrontendAction::usesPreprocessorOnly() const {
  376. return WrappedAction->usesPreprocessorOnly();
  377. }
  378. TranslationUnitKind WrapperFrontendAction::getTranslationUnitKind() {
  379. return WrappedAction->getTranslationUnitKind();
  380. }
  381. bool WrapperFrontendAction::hasPCHSupport() const {
  382. return WrappedAction->hasPCHSupport();
  383. }
  384. bool WrapperFrontendAction::hasASTFileSupport() const {
  385. return WrappedAction->hasASTFileSupport();
  386. }
  387. bool WrapperFrontendAction::hasIRSupport() const {
  388. return WrappedAction->hasIRSupport();
  389. }
  390. bool WrapperFrontendAction::hasCodeCompletionSupport() const {
  391. return WrappedAction->hasCodeCompletionSupport();
  392. }
  393. WrapperFrontendAction::WrapperFrontendAction(FrontendAction *WrappedAction)
  394. : WrappedAction(WrappedAction) {}