FrontendAction.cpp 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527
  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. std::string Error;
  158. ASTUnit *AST = ASTUnit::LoadFromASTFile(InputFile, Diags,
  159. CI.getFileSystemOpts());
  160. if (!AST)
  161. goto failure;
  162. setCurrentInput(Input, AST);
  163. // Set the shared objects, these are reset when we finish processing the
  164. // file, otherwise the CompilerInstance will happily destroy them.
  165. CI.setFileManager(&AST->getFileManager());
  166. CI.setSourceManager(&AST->getSourceManager());
  167. CI.setPreprocessor(&AST->getPreprocessor());
  168. CI.setASTContext(&AST->getASTContext());
  169. // Initialize the action.
  170. if (!BeginSourceFileAction(CI, InputFile))
  171. goto failure;
  172. // Create the AST consumer.
  173. CI.setASTConsumer(CreateWrappedASTConsumer(CI, InputFile));
  174. if (!CI.hasASTConsumer())
  175. goto failure;
  176. return true;
  177. }
  178. // Set up the file and source managers, if needed.
  179. if (!CI.hasFileManager())
  180. CI.createFileManager();
  181. if (!CI.hasSourceManager())
  182. CI.createSourceManager(CI.getFileManager());
  183. // IR files bypass the rest of initialization.
  184. if (Input.getKind() == IK_LLVM_IR) {
  185. assert(hasIRSupport() &&
  186. "This action does not have IR file support!");
  187. // Inform the diagnostic client we are processing a source file.
  188. CI.getDiagnosticClient().BeginSourceFile(CI.getLangOpts(), 0);
  189. HasBegunSourceFile = true;
  190. // Initialize the action.
  191. if (!BeginSourceFileAction(CI, InputFile))
  192. goto failure;
  193. return true;
  194. }
  195. // If the implicit PCH include is actually a directory, rather than
  196. // a single file, search for a suitable PCH file in that directory.
  197. if (!CI.getPreprocessorOpts().ImplicitPCHInclude.empty()) {
  198. FileManager &FileMgr = CI.getFileManager();
  199. PreprocessorOptions &PPOpts = CI.getPreprocessorOpts();
  200. StringRef PCHInclude = PPOpts.ImplicitPCHInclude;
  201. if (const DirectoryEntry *PCHDir = FileMgr.getDirectory(PCHInclude)) {
  202. llvm::error_code EC;
  203. SmallString<128> DirNative;
  204. llvm::sys::path::native(PCHDir->getName(), DirNative);
  205. bool Found = false;
  206. for (llvm::sys::fs::directory_iterator Dir(DirNative.str(), EC), DirEnd;
  207. Dir != DirEnd && !EC; Dir.increment(EC)) {
  208. // Check whether this is an acceptable AST file.
  209. if (ASTReader::isAcceptableASTFile(Dir->path(), FileMgr,
  210. CI.getLangOpts(),
  211. CI.getTargetOpts(),
  212. CI.getPreprocessorOpts())) {
  213. for (unsigned I = 0, N = PPOpts.Includes.size(); I != N; ++I) {
  214. if (PPOpts.Includes[I] == PPOpts.ImplicitPCHInclude) {
  215. PPOpts.Includes[I] = Dir->path();
  216. PPOpts.ImplicitPCHInclude = Dir->path();
  217. Found = true;
  218. break;
  219. }
  220. }
  221. assert(Found && "Implicit PCH include not in includes list?");
  222. break;
  223. }
  224. }
  225. if (!Found) {
  226. CI.getDiagnostics().Report(diag::err_fe_no_pch_in_dir) << PCHInclude;
  227. return true;
  228. }
  229. }
  230. }
  231. // Set up the preprocessor.
  232. CI.createPreprocessor();
  233. // Inform the diagnostic client we are processing a source file.
  234. CI.getDiagnosticClient().BeginSourceFile(CI.getLangOpts(),
  235. &CI.getPreprocessor());
  236. HasBegunSourceFile = true;
  237. // Initialize the action.
  238. if (!BeginSourceFileAction(CI, InputFile))
  239. goto failure;
  240. // Create the AST context and consumer unless this is a preprocessor only
  241. // action.
  242. if (!usesPreprocessorOnly()) {
  243. CI.createASTContext();
  244. OwningPtr<ASTConsumer> Consumer(
  245. CreateWrappedASTConsumer(CI, InputFile));
  246. if (!Consumer)
  247. goto failure;
  248. CI.getASTContext().setASTMutationListener(Consumer->GetASTMutationListener());
  249. CI.getPreprocessor().setPPMutationListener(
  250. Consumer->GetPPMutationListener());
  251. if (!CI.getPreprocessorOpts().ChainedIncludes.empty()) {
  252. // Convert headers to PCH and chain them.
  253. OwningPtr<ExternalASTSource> source;
  254. source.reset(ChainedIncludesSource::create(CI));
  255. if (!source)
  256. goto failure;
  257. CI.getASTContext().setExternalSource(source);
  258. } else if (!CI.getPreprocessorOpts().ImplicitPCHInclude.empty()) {
  259. // Use PCH.
  260. assert(hasPCHSupport() && "This action does not have PCH support!");
  261. ASTDeserializationListener *DeserialListener =
  262. Consumer->GetASTDeserializationListener();
  263. if (CI.getPreprocessorOpts().DumpDeserializedPCHDecls)
  264. DeserialListener = new DeserializedDeclsDumper(DeserialListener);
  265. if (!CI.getPreprocessorOpts().DeserializedPCHDeclsToErrorOn.empty())
  266. DeserialListener = new DeserializedDeclsChecker(CI.getASTContext(),
  267. CI.getPreprocessorOpts().DeserializedPCHDeclsToErrorOn,
  268. DeserialListener);
  269. CI.createPCHExternalASTSource(
  270. CI.getPreprocessorOpts().ImplicitPCHInclude,
  271. CI.getPreprocessorOpts().DisablePCHValidation,
  272. CI.getPreprocessorOpts().AllowPCHWithCompilerErrors,
  273. DeserialListener);
  274. if (!CI.getASTContext().getExternalSource())
  275. goto failure;
  276. }
  277. CI.setASTConsumer(Consumer.take());
  278. if (!CI.hasASTConsumer())
  279. goto failure;
  280. }
  281. // Initialize built-in info as long as we aren't using an external AST
  282. // source.
  283. if (!CI.hasASTContext() || !CI.getASTContext().getExternalSource()) {
  284. Preprocessor &PP = CI.getPreprocessor();
  285. PP.getBuiltinInfo().InitializeBuiltins(PP.getIdentifierTable(),
  286. PP.getLangOpts());
  287. }
  288. // If there is a layout overrides file, attach an external AST source that
  289. // provides the layouts from that file.
  290. if (!CI.getFrontendOpts().OverrideRecordLayoutsFile.empty() &&
  291. CI.hasASTContext() && !CI.getASTContext().getExternalSource()) {
  292. OwningPtr<ExternalASTSource>
  293. Override(new LayoutOverrideSource(
  294. CI.getFrontendOpts().OverrideRecordLayoutsFile));
  295. CI.getASTContext().setExternalSource(Override);
  296. }
  297. return true;
  298. // If we failed, reset state since the client will not end up calling the
  299. // matching EndSourceFile().
  300. failure:
  301. if (isCurrentFileAST()) {
  302. CI.setASTContext(0);
  303. CI.setPreprocessor(0);
  304. CI.setSourceManager(0);
  305. CI.setFileManager(0);
  306. }
  307. if (HasBegunSourceFile)
  308. CI.getDiagnosticClient().EndSourceFile();
  309. CI.clearOutputFiles(/*EraseFiles=*/true);
  310. setCurrentInput(FrontendInputFile());
  311. setCompilerInstance(0);
  312. return false;
  313. }
  314. bool FrontendAction::Execute() {
  315. CompilerInstance &CI = getCompilerInstance();
  316. // Initialize the main file entry. This needs to be delayed until after PCH
  317. // has loaded.
  318. if (!isCurrentFileAST()) {
  319. if (!CI.InitializeSourceManager(getCurrentInput()))
  320. return false;
  321. }
  322. if (CI.hasFrontendTimer()) {
  323. llvm::TimeRegion Timer(CI.getFrontendTimer());
  324. ExecuteAction();
  325. }
  326. else ExecuteAction();
  327. // If we are supposed to rebuild the global module index, do so now unless
  328. // an error occurred.
  329. if (CI.getBuildGlobalModuleIndex() && CI.hasFileManager() &&
  330. CI.hasPreprocessor() &&
  331. (!CI.hasDiagnostics() || !CI.getDiagnostics().hasErrorOccurred())) {
  332. GlobalModuleIndex::writeIndex(
  333. CI.getFileManager(),
  334. CI.getPreprocessor().getHeaderSearchInfo().getModuleCachePath());
  335. }
  336. return true;
  337. }
  338. void FrontendAction::EndSourceFile() {
  339. CompilerInstance &CI = getCompilerInstance();
  340. // Inform the diagnostic client we are done with this source file.
  341. CI.getDiagnosticClient().EndSourceFile();
  342. // Finalize the action.
  343. EndSourceFileAction();
  344. // Release the consumer and the AST, in that order since the consumer may
  345. // perform actions in its destructor which require the context.
  346. //
  347. // FIXME: There is more per-file stuff we could just drop here?
  348. if (CI.getFrontendOpts().DisableFree) {
  349. CI.takeASTConsumer();
  350. if (!isCurrentFileAST()) {
  351. CI.takeSema();
  352. CI.resetAndLeakASTContext();
  353. }
  354. } else {
  355. if (!isCurrentFileAST()) {
  356. CI.setSema(0);
  357. CI.setASTContext(0);
  358. }
  359. CI.setASTConsumer(0);
  360. }
  361. // Inform the preprocessor we are done.
  362. if (CI.hasPreprocessor())
  363. CI.getPreprocessor().EndSourceFile();
  364. if (CI.getFrontendOpts().ShowStats) {
  365. llvm::errs() << "\nSTATISTICS FOR '" << getCurrentFile() << "':\n";
  366. CI.getPreprocessor().PrintStats();
  367. CI.getPreprocessor().getIdentifierTable().PrintStats();
  368. CI.getPreprocessor().getHeaderSearchInfo().PrintStats();
  369. CI.getSourceManager().PrintStats();
  370. llvm::errs() << "\n";
  371. }
  372. // Cleanup the output streams, and erase the output files if we encountered
  373. // an error.
  374. CI.clearOutputFiles(/*EraseFiles=*/CI.getDiagnostics().hasErrorOccurred());
  375. if (isCurrentFileAST()) {
  376. CI.takeSema();
  377. CI.resetAndLeakASTContext();
  378. CI.resetAndLeakPreprocessor();
  379. CI.resetAndLeakSourceManager();
  380. CI.resetAndLeakFileManager();
  381. }
  382. setCompilerInstance(0);
  383. setCurrentInput(FrontendInputFile());
  384. }
  385. //===----------------------------------------------------------------------===//
  386. // Utility Actions
  387. //===----------------------------------------------------------------------===//
  388. void ASTFrontendAction::ExecuteAction() {
  389. CompilerInstance &CI = getCompilerInstance();
  390. // FIXME: Move the truncation aspect of this into Sema, we delayed this till
  391. // here so the source manager would be initialized.
  392. if (hasCodeCompletionSupport() &&
  393. !CI.getFrontendOpts().CodeCompletionAt.FileName.empty())
  394. CI.createCodeCompletionConsumer();
  395. // Use a code completion consumer?
  396. CodeCompleteConsumer *CompletionConsumer = 0;
  397. if (CI.hasCodeCompletionConsumer())
  398. CompletionConsumer = &CI.getCodeCompletionConsumer();
  399. if (!CI.hasSema())
  400. CI.createSema(getTranslationUnitKind(), CompletionConsumer);
  401. ParseAST(CI.getSema(), CI.getFrontendOpts().ShowStats,
  402. CI.getFrontendOpts().SkipFunctionBodies);
  403. }
  404. void PluginASTAction::anchor() { }
  405. ASTConsumer *
  406. PreprocessorFrontendAction::CreateASTConsumer(CompilerInstance &CI,
  407. StringRef InFile) {
  408. llvm_unreachable("Invalid CreateASTConsumer on preprocessor action!");
  409. }
  410. ASTConsumer *WrapperFrontendAction::CreateASTConsumer(CompilerInstance &CI,
  411. StringRef InFile) {
  412. return WrappedAction->CreateASTConsumer(CI, InFile);
  413. }
  414. bool WrapperFrontendAction::BeginInvocation(CompilerInstance &CI) {
  415. return WrappedAction->BeginInvocation(CI);
  416. }
  417. bool WrapperFrontendAction::BeginSourceFileAction(CompilerInstance &CI,
  418. StringRef Filename) {
  419. WrappedAction->setCurrentInput(getCurrentInput());
  420. WrappedAction->setCompilerInstance(&CI);
  421. return WrappedAction->BeginSourceFileAction(CI, Filename);
  422. }
  423. void WrapperFrontendAction::ExecuteAction() {
  424. WrappedAction->ExecuteAction();
  425. }
  426. void WrapperFrontendAction::EndSourceFileAction() {
  427. WrappedAction->EndSourceFileAction();
  428. }
  429. bool WrapperFrontendAction::usesPreprocessorOnly() const {
  430. return WrappedAction->usesPreprocessorOnly();
  431. }
  432. TranslationUnitKind WrapperFrontendAction::getTranslationUnitKind() {
  433. return WrappedAction->getTranslationUnitKind();
  434. }
  435. bool WrapperFrontendAction::hasPCHSupport() const {
  436. return WrappedAction->hasPCHSupport();
  437. }
  438. bool WrapperFrontendAction::hasASTFileSupport() const {
  439. return WrappedAction->hasASTFileSupport();
  440. }
  441. bool WrapperFrontendAction::hasIRSupport() const {
  442. return WrappedAction->hasIRSupport();
  443. }
  444. bool WrapperFrontendAction::hasCodeCompletionSupport() const {
  445. return WrappedAction->hasCodeCompletionSupport();
  446. }
  447. WrapperFrontendAction::WrapperFrontendAction(FrontendAction *WrappedAction)
  448. : WrappedAction(WrappedAction) {}