FrontendAction.cpp 18 KB

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