FrontendActions.cpp 39 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077
  1. //===--- FrontendActions.cpp ----------------------------------------------===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. #include "clang/Frontend/FrontendActions.h"
  9. #include "clang/AST/ASTConsumer.h"
  10. #include "clang/AST/Decl.h"
  11. #include "clang/Basic/FileManager.h"
  12. #include "clang/Basic/LangStandard.h"
  13. #include "clang/Basic/TargetInfo.h"
  14. #include "clang/Frontend/ASTConsumers.h"
  15. #include "clang/Frontend/CompilerInstance.h"
  16. #include "clang/Frontend/FrontendDiagnostic.h"
  17. #include "clang/Frontend/MultiplexConsumer.h"
  18. #include "clang/Frontend/Utils.h"
  19. #include "clang/Lex/DependencyDirectivesSourceMinimizer.h"
  20. #include "clang/Lex/HeaderSearch.h"
  21. #include "clang/Lex/Preprocessor.h"
  22. #include "clang/Lex/PreprocessorOptions.h"
  23. #include "clang/Sema/TemplateInstCallback.h"
  24. #include "clang/Serialization/ASTReader.h"
  25. #include "clang/Serialization/ASTWriter.h"
  26. #include "llvm/Support/ErrorHandling.h"
  27. #include "llvm/Support/FileSystem.h"
  28. #include "llvm/Support/MemoryBuffer.h"
  29. #include "llvm/Support/Path.h"
  30. #include "llvm/Support/YAMLTraits.h"
  31. #include "llvm/Support/raw_ostream.h"
  32. #include <memory>
  33. #include <system_error>
  34. using namespace clang;
  35. namespace {
  36. CodeCompleteConsumer *GetCodeCompletionConsumer(CompilerInstance &CI) {
  37. return CI.hasCodeCompletionConsumer() ? &CI.getCodeCompletionConsumer()
  38. : nullptr;
  39. }
  40. void EnsureSemaIsCreated(CompilerInstance &CI, FrontendAction &Action) {
  41. if (Action.hasCodeCompletionSupport() &&
  42. !CI.getFrontendOpts().CodeCompletionAt.FileName.empty())
  43. CI.createCodeCompletionConsumer();
  44. if (!CI.hasSema())
  45. CI.createSema(Action.getTranslationUnitKind(),
  46. GetCodeCompletionConsumer(CI));
  47. }
  48. } // namespace
  49. //===----------------------------------------------------------------------===//
  50. // Custom Actions
  51. //===----------------------------------------------------------------------===//
  52. std::unique_ptr<ASTConsumer>
  53. InitOnlyAction::CreateASTConsumer(CompilerInstance &CI, StringRef InFile) {
  54. return std::make_unique<ASTConsumer>();
  55. }
  56. void InitOnlyAction::ExecuteAction() {
  57. }
  58. // Basically PreprocessOnlyAction::ExecuteAction.
  59. void ReadPCHAndPreprocessAction::ExecuteAction() {
  60. Preprocessor &PP = getCompilerInstance().getPreprocessor();
  61. // Ignore unknown pragmas.
  62. PP.IgnorePragmas();
  63. Token Tok;
  64. // Start parsing the specified input file.
  65. PP.EnterMainSourceFile();
  66. do {
  67. PP.Lex(Tok);
  68. } while (Tok.isNot(tok::eof));
  69. }
  70. std::unique_ptr<ASTConsumer>
  71. ReadPCHAndPreprocessAction::CreateASTConsumer(CompilerInstance &CI,
  72. StringRef InFile) {
  73. return std::make_unique<ASTConsumer>();
  74. }
  75. //===----------------------------------------------------------------------===//
  76. // AST Consumer Actions
  77. //===----------------------------------------------------------------------===//
  78. std::unique_ptr<ASTConsumer>
  79. ASTPrintAction::CreateASTConsumer(CompilerInstance &CI, StringRef InFile) {
  80. if (std::unique_ptr<raw_ostream> OS =
  81. CI.createDefaultOutputFile(false, InFile))
  82. return CreateASTPrinter(std::move(OS), CI.getFrontendOpts().ASTDumpFilter);
  83. return nullptr;
  84. }
  85. std::unique_ptr<ASTConsumer>
  86. ASTDumpAction::CreateASTConsumer(CompilerInstance &CI, StringRef InFile) {
  87. const FrontendOptions &Opts = CI.getFrontendOpts();
  88. return CreateASTDumper(nullptr /*Dump to stdout.*/, Opts.ASTDumpFilter,
  89. Opts.ASTDumpDecls, Opts.ASTDumpAll,
  90. Opts.ASTDumpLookups, Opts.ASTDumpDeclTypes,
  91. Opts.ASTDumpFormat);
  92. }
  93. std::unique_ptr<ASTConsumer>
  94. ASTDeclListAction::CreateASTConsumer(CompilerInstance &CI, StringRef InFile) {
  95. return CreateASTDeclNodeLister();
  96. }
  97. std::unique_ptr<ASTConsumer>
  98. ASTViewAction::CreateASTConsumer(CompilerInstance &CI, StringRef InFile) {
  99. return CreateASTViewer();
  100. }
  101. std::unique_ptr<ASTConsumer>
  102. GeneratePCHAction::CreateASTConsumer(CompilerInstance &CI, StringRef InFile) {
  103. std::string Sysroot;
  104. if (!ComputeASTConsumerArguments(CI, /*ref*/ Sysroot))
  105. return nullptr;
  106. std::string OutputFile;
  107. std::unique_ptr<raw_pwrite_stream> OS =
  108. CreateOutputFile(CI, InFile, /*ref*/ OutputFile);
  109. if (!OS)
  110. return nullptr;
  111. if (!CI.getFrontendOpts().RelocatablePCH)
  112. Sysroot.clear();
  113. const auto &FrontendOpts = CI.getFrontendOpts();
  114. auto Buffer = std::make_shared<PCHBuffer>();
  115. std::vector<std::unique_ptr<ASTConsumer>> Consumers;
  116. Consumers.push_back(std::make_unique<PCHGenerator>(
  117. CI.getPreprocessor(), CI.getModuleCache(), OutputFile, Sysroot, Buffer,
  118. FrontendOpts.ModuleFileExtensions,
  119. CI.getPreprocessorOpts().AllowPCHWithCompilerErrors,
  120. FrontendOpts.IncludeTimestamps, +CI.getLangOpts().CacheGeneratedPCH));
  121. Consumers.push_back(CI.getPCHContainerWriter().CreatePCHContainerGenerator(
  122. CI, std::string(InFile), OutputFile, std::move(OS), Buffer));
  123. return std::make_unique<MultiplexConsumer>(std::move(Consumers));
  124. }
  125. bool GeneratePCHAction::ComputeASTConsumerArguments(CompilerInstance &CI,
  126. std::string &Sysroot) {
  127. Sysroot = CI.getHeaderSearchOpts().Sysroot;
  128. if (CI.getFrontendOpts().RelocatablePCH && Sysroot.empty()) {
  129. CI.getDiagnostics().Report(diag::err_relocatable_without_isysroot);
  130. return false;
  131. }
  132. return true;
  133. }
  134. std::unique_ptr<llvm::raw_pwrite_stream>
  135. GeneratePCHAction::CreateOutputFile(CompilerInstance &CI, StringRef InFile,
  136. std::string &OutputFile) {
  137. // Because this is exposed via libclang we must disable RemoveFileOnSignal.
  138. std::unique_ptr<raw_pwrite_stream> OS = CI.createDefaultOutputFile(
  139. /*Binary=*/true, InFile, /*Extension=*/"", /*RemoveFileOnSignal=*/false);
  140. if (!OS)
  141. return nullptr;
  142. OutputFile = CI.getFrontendOpts().OutputFile;
  143. return OS;
  144. }
  145. bool GeneratePCHAction::shouldEraseOutputFiles() {
  146. if (getCompilerInstance().getPreprocessorOpts().AllowPCHWithCompilerErrors)
  147. return false;
  148. return ASTFrontendAction::shouldEraseOutputFiles();
  149. }
  150. bool GeneratePCHAction::BeginSourceFileAction(CompilerInstance &CI) {
  151. CI.getLangOpts().CompilingPCH = true;
  152. return true;
  153. }
  154. std::unique_ptr<ASTConsumer>
  155. GenerateModuleAction::CreateASTConsumer(CompilerInstance &CI,
  156. StringRef InFile) {
  157. std::unique_ptr<raw_pwrite_stream> OS = CreateOutputFile(CI, InFile);
  158. if (!OS)
  159. return nullptr;
  160. std::string OutputFile = CI.getFrontendOpts().OutputFile;
  161. std::string Sysroot;
  162. auto Buffer = std::make_shared<PCHBuffer>();
  163. std::vector<std::unique_ptr<ASTConsumer>> Consumers;
  164. Consumers.push_back(std::make_unique<PCHGenerator>(
  165. CI.getPreprocessor(), CI.getModuleCache(), OutputFile, Sysroot, Buffer,
  166. CI.getFrontendOpts().ModuleFileExtensions,
  167. /*AllowASTWithErrors=*/
  168. +CI.getFrontendOpts().AllowPCMWithCompilerErrors,
  169. /*IncludeTimestamps=*/
  170. +CI.getFrontendOpts().BuildingImplicitModule,
  171. /*ShouldCacheASTInMemory=*/
  172. +CI.getFrontendOpts().BuildingImplicitModule));
  173. Consumers.push_back(CI.getPCHContainerWriter().CreatePCHContainerGenerator(
  174. CI, std::string(InFile), OutputFile, std::move(OS), Buffer));
  175. return std::make_unique<MultiplexConsumer>(std::move(Consumers));
  176. }
  177. bool GenerateModuleAction::shouldEraseOutputFiles() {
  178. return !getCompilerInstance().getFrontendOpts().AllowPCMWithCompilerErrors &&
  179. ASTFrontendAction::shouldEraseOutputFiles();
  180. }
  181. bool GenerateModuleFromModuleMapAction::BeginSourceFileAction(
  182. CompilerInstance &CI) {
  183. if (!CI.getLangOpts().Modules) {
  184. CI.getDiagnostics().Report(diag::err_module_build_requires_fmodules);
  185. return false;
  186. }
  187. return GenerateModuleAction::BeginSourceFileAction(CI);
  188. }
  189. std::unique_ptr<raw_pwrite_stream>
  190. GenerateModuleFromModuleMapAction::CreateOutputFile(CompilerInstance &CI,
  191. StringRef InFile) {
  192. // If no output file was provided, figure out where this module would go
  193. // in the module cache.
  194. if (CI.getFrontendOpts().OutputFile.empty()) {
  195. StringRef ModuleMapFile = CI.getFrontendOpts().OriginalModuleMap;
  196. if (ModuleMapFile.empty())
  197. ModuleMapFile = InFile;
  198. HeaderSearch &HS = CI.getPreprocessor().getHeaderSearchInfo();
  199. CI.getFrontendOpts().OutputFile =
  200. HS.getCachedModuleFileName(CI.getLangOpts().CurrentModule,
  201. ModuleMapFile);
  202. }
  203. // Because this is exposed via libclang we must disable RemoveFileOnSignal.
  204. return CI.createDefaultOutputFile(/*Binary=*/true, InFile, /*Extension=*/"",
  205. /*RemoveFileOnSignal=*/false,
  206. /*CreateMissingDirectories=*/true,
  207. /*ForceUseTemporary=*/true);
  208. }
  209. bool GenerateModuleInterfaceAction::BeginSourceFileAction(
  210. CompilerInstance &CI) {
  211. if (!CI.getLangOpts().ModulesTS && !CI.getLangOpts().CPlusPlusModules) {
  212. CI.getDiagnostics().Report(diag::err_module_interface_requires_cpp_modules);
  213. return false;
  214. }
  215. CI.getLangOpts().setCompilingModule(LangOptions::CMK_ModuleInterface);
  216. return GenerateModuleAction::BeginSourceFileAction(CI);
  217. }
  218. std::unique_ptr<raw_pwrite_stream>
  219. GenerateModuleInterfaceAction::CreateOutputFile(CompilerInstance &CI,
  220. StringRef InFile) {
  221. return CI.createDefaultOutputFile(/*Binary=*/true, InFile, "pcm");
  222. }
  223. bool GenerateHeaderModuleAction::PrepareToExecuteAction(
  224. CompilerInstance &CI) {
  225. if (!CI.getLangOpts().Modules) {
  226. CI.getDiagnostics().Report(diag::err_header_module_requires_modules);
  227. return false;
  228. }
  229. auto &Inputs = CI.getFrontendOpts().Inputs;
  230. if (Inputs.empty())
  231. return GenerateModuleAction::BeginInvocation(CI);
  232. auto Kind = Inputs[0].getKind();
  233. // Convert the header file inputs into a single module input buffer.
  234. SmallString<256> HeaderContents;
  235. ModuleHeaders.reserve(Inputs.size());
  236. for (const FrontendInputFile &FIF : Inputs) {
  237. // FIXME: We should support re-compiling from an AST file.
  238. if (FIF.getKind().getFormat() != InputKind::Source || !FIF.isFile()) {
  239. CI.getDiagnostics().Report(diag::err_module_header_file_not_found)
  240. << (FIF.isFile() ? FIF.getFile()
  241. : FIF.getBuffer().getBufferIdentifier());
  242. return true;
  243. }
  244. HeaderContents += "#include \"";
  245. HeaderContents += FIF.getFile();
  246. HeaderContents += "\"\n";
  247. ModuleHeaders.push_back(std::string(FIF.getFile()));
  248. }
  249. Buffer = llvm::MemoryBuffer::getMemBufferCopy(
  250. HeaderContents, Module::getModuleInputBufferName());
  251. // Set that buffer up as our "real" input.
  252. Inputs.clear();
  253. Inputs.push_back(
  254. FrontendInputFile(Buffer->getMemBufferRef(), Kind, /*IsSystem*/ false));
  255. return GenerateModuleAction::PrepareToExecuteAction(CI);
  256. }
  257. bool GenerateHeaderModuleAction::BeginSourceFileAction(
  258. CompilerInstance &CI) {
  259. CI.getLangOpts().setCompilingModule(LangOptions::CMK_HeaderModule);
  260. // Synthesize a Module object for the given headers.
  261. auto &HS = CI.getPreprocessor().getHeaderSearchInfo();
  262. SmallVector<Module::Header, 16> Headers;
  263. for (StringRef Name : ModuleHeaders) {
  264. Optional<FileEntryRef> FE = HS.LookupFile(
  265. Name, SourceLocation(), /*Angled*/ false, nullptr, nullptr, None,
  266. nullptr, nullptr, nullptr, nullptr, nullptr, nullptr);
  267. if (!FE) {
  268. CI.getDiagnostics().Report(diag::err_module_header_file_not_found)
  269. << Name;
  270. continue;
  271. }
  272. Headers.push_back(
  273. {std::string(Name), std::string(Name), &FE->getFileEntry()});
  274. }
  275. HS.getModuleMap().createHeaderModule(CI.getLangOpts().CurrentModule, Headers);
  276. return GenerateModuleAction::BeginSourceFileAction(CI);
  277. }
  278. std::unique_ptr<raw_pwrite_stream>
  279. GenerateHeaderModuleAction::CreateOutputFile(CompilerInstance &CI,
  280. StringRef InFile) {
  281. return CI.createDefaultOutputFile(/*Binary=*/true, InFile, "pcm");
  282. }
  283. SyntaxOnlyAction::~SyntaxOnlyAction() {
  284. }
  285. std::unique_ptr<ASTConsumer>
  286. SyntaxOnlyAction::CreateASTConsumer(CompilerInstance &CI, StringRef InFile) {
  287. return std::make_unique<ASTConsumer>();
  288. }
  289. std::unique_ptr<ASTConsumer>
  290. DumpModuleInfoAction::CreateASTConsumer(CompilerInstance &CI,
  291. StringRef InFile) {
  292. return std::make_unique<ASTConsumer>();
  293. }
  294. std::unique_ptr<ASTConsumer>
  295. VerifyPCHAction::CreateASTConsumer(CompilerInstance &CI, StringRef InFile) {
  296. return std::make_unique<ASTConsumer>();
  297. }
  298. void VerifyPCHAction::ExecuteAction() {
  299. CompilerInstance &CI = getCompilerInstance();
  300. bool Preamble = CI.getPreprocessorOpts().PrecompiledPreambleBytes.first != 0;
  301. const std::string &Sysroot = CI.getHeaderSearchOpts().Sysroot;
  302. std::unique_ptr<ASTReader> Reader(new ASTReader(
  303. CI.getPreprocessor(), CI.getModuleCache(), &CI.getASTContext(),
  304. CI.getPCHContainerReader(), CI.getFrontendOpts().ModuleFileExtensions,
  305. Sysroot.empty() ? "" : Sysroot.c_str(),
  306. DisableValidationForModuleKind::None,
  307. /*AllowASTWithCompilerErrors*/ false,
  308. /*AllowConfigurationMismatch*/ true,
  309. /*ValidateSystemInputs*/ true));
  310. Reader->ReadAST(getCurrentFile(),
  311. Preamble ? serialization::MK_Preamble
  312. : serialization::MK_PCH,
  313. SourceLocation(),
  314. ASTReader::ARR_ConfigurationMismatch);
  315. }
  316. namespace {
  317. struct TemplightEntry {
  318. std::string Name;
  319. std::string Kind;
  320. std::string Event;
  321. std::string DefinitionLocation;
  322. std::string PointOfInstantiation;
  323. };
  324. } // namespace
  325. namespace llvm {
  326. namespace yaml {
  327. template <> struct MappingTraits<TemplightEntry> {
  328. static void mapping(IO &io, TemplightEntry &fields) {
  329. io.mapRequired("name", fields.Name);
  330. io.mapRequired("kind", fields.Kind);
  331. io.mapRequired("event", fields.Event);
  332. io.mapRequired("orig", fields.DefinitionLocation);
  333. io.mapRequired("poi", fields.PointOfInstantiation);
  334. }
  335. };
  336. } // namespace yaml
  337. } // namespace llvm
  338. namespace {
  339. class DefaultTemplateInstCallback : public TemplateInstantiationCallback {
  340. using CodeSynthesisContext = Sema::CodeSynthesisContext;
  341. public:
  342. void initialize(const Sema &) override {}
  343. void finalize(const Sema &) override {}
  344. void atTemplateBegin(const Sema &TheSema,
  345. const CodeSynthesisContext &Inst) override {
  346. displayTemplightEntry<true>(llvm::outs(), TheSema, Inst);
  347. }
  348. void atTemplateEnd(const Sema &TheSema,
  349. const CodeSynthesisContext &Inst) override {
  350. displayTemplightEntry<false>(llvm::outs(), TheSema, Inst);
  351. }
  352. private:
  353. static std::string toString(CodeSynthesisContext::SynthesisKind Kind) {
  354. switch (Kind) {
  355. case CodeSynthesisContext::TemplateInstantiation:
  356. return "TemplateInstantiation";
  357. case CodeSynthesisContext::DefaultTemplateArgumentInstantiation:
  358. return "DefaultTemplateArgumentInstantiation";
  359. case CodeSynthesisContext::DefaultFunctionArgumentInstantiation:
  360. return "DefaultFunctionArgumentInstantiation";
  361. case CodeSynthesisContext::ExplicitTemplateArgumentSubstitution:
  362. return "ExplicitTemplateArgumentSubstitution";
  363. case CodeSynthesisContext::DeducedTemplateArgumentSubstitution:
  364. return "DeducedTemplateArgumentSubstitution";
  365. case CodeSynthesisContext::PriorTemplateArgumentSubstitution:
  366. return "PriorTemplateArgumentSubstitution";
  367. case CodeSynthesisContext::DefaultTemplateArgumentChecking:
  368. return "DefaultTemplateArgumentChecking";
  369. case CodeSynthesisContext::ExceptionSpecEvaluation:
  370. return "ExceptionSpecEvaluation";
  371. case CodeSynthesisContext::ExceptionSpecInstantiation:
  372. return "ExceptionSpecInstantiation";
  373. case CodeSynthesisContext::DeclaringSpecialMember:
  374. return "DeclaringSpecialMember";
  375. case CodeSynthesisContext::DeclaringImplicitEqualityComparison:
  376. return "DeclaringImplicitEqualityComparison";
  377. case CodeSynthesisContext::DefiningSynthesizedFunction:
  378. return "DefiningSynthesizedFunction";
  379. case CodeSynthesisContext::RewritingOperatorAsSpaceship:
  380. return "RewritingOperatorAsSpaceship";
  381. case CodeSynthesisContext::Memoization:
  382. return "Memoization";
  383. case CodeSynthesisContext::ConstraintsCheck:
  384. return "ConstraintsCheck";
  385. case CodeSynthesisContext::ConstraintSubstitution:
  386. return "ConstraintSubstitution";
  387. case CodeSynthesisContext::ConstraintNormalization:
  388. return "ConstraintNormalization";
  389. case CodeSynthesisContext::ParameterMappingSubstitution:
  390. return "ParameterMappingSubstitution";
  391. case CodeSynthesisContext::RequirementInstantiation:
  392. return "RequirementInstantiation";
  393. case CodeSynthesisContext::NestedRequirementConstraintsCheck:
  394. return "NestedRequirementConstraintsCheck";
  395. case CodeSynthesisContext::InitializingStructuredBinding:
  396. return "InitializingStructuredBinding";
  397. case CodeSynthesisContext::MarkingClassDllexported:
  398. return "MarkingClassDllexported";
  399. }
  400. return "";
  401. }
  402. template <bool BeginInstantiation>
  403. static void displayTemplightEntry(llvm::raw_ostream &Out, const Sema &TheSema,
  404. const CodeSynthesisContext &Inst) {
  405. std::string YAML;
  406. {
  407. llvm::raw_string_ostream OS(YAML);
  408. llvm::yaml::Output YO(OS);
  409. TemplightEntry Entry =
  410. getTemplightEntry<BeginInstantiation>(TheSema, Inst);
  411. llvm::yaml::EmptyContext Context;
  412. llvm::yaml::yamlize(YO, Entry, true, Context);
  413. }
  414. Out << "---" << YAML << "\n";
  415. }
  416. static void printEntryName(const Sema &TheSema, const Decl *Entity,
  417. llvm::raw_string_ostream &OS) {
  418. auto *NamedTemplate = cast<NamedDecl>(Entity);
  419. PrintingPolicy Policy = TheSema.Context.getPrintingPolicy();
  420. // FIXME: Also ask for FullyQualifiedNames?
  421. Policy.SuppressDefaultTemplateArgs = false;
  422. NamedTemplate->getNameForDiagnostic(OS, Policy, true);
  423. if (!OS.str().empty())
  424. return;
  425. Decl *Ctx = Decl::castFromDeclContext(NamedTemplate->getDeclContext());
  426. NamedDecl *NamedCtx = dyn_cast_or_null<NamedDecl>(Ctx);
  427. if (const auto *Decl = dyn_cast<TagDecl>(NamedTemplate)) {
  428. if (const auto *R = dyn_cast<RecordDecl>(Decl)) {
  429. if (R->isLambda()) {
  430. OS << "lambda at ";
  431. Decl->getLocation().print(OS, TheSema.getSourceManager());
  432. return;
  433. }
  434. }
  435. OS << "unnamed " << Decl->getKindName();
  436. return;
  437. }
  438. if (const auto *Decl = dyn_cast<ParmVarDecl>(NamedTemplate)) {
  439. OS << "unnamed function parameter " << Decl->getFunctionScopeIndex()
  440. << " ";
  441. if (Decl->getFunctionScopeDepth() > 0)
  442. OS << "(at depth " << Decl->getFunctionScopeDepth() << ") ";
  443. OS << "of ";
  444. NamedCtx->getNameForDiagnostic(OS, TheSema.getLangOpts(), true);
  445. return;
  446. }
  447. if (const auto *Decl = dyn_cast<TemplateTypeParmDecl>(NamedTemplate)) {
  448. if (const Type *Ty = Decl->getTypeForDecl()) {
  449. if (const auto *TTPT = dyn_cast_or_null<TemplateTypeParmType>(Ty)) {
  450. OS << "unnamed template type parameter " << TTPT->getIndex() << " ";
  451. if (TTPT->getDepth() > 0)
  452. OS << "(at depth " << TTPT->getDepth() << ") ";
  453. OS << "of ";
  454. NamedCtx->getNameForDiagnostic(OS, TheSema.getLangOpts(), true);
  455. return;
  456. }
  457. }
  458. }
  459. if (const auto *Decl = dyn_cast<NonTypeTemplateParmDecl>(NamedTemplate)) {
  460. OS << "unnamed template non-type parameter " << Decl->getIndex() << " ";
  461. if (Decl->getDepth() > 0)
  462. OS << "(at depth " << Decl->getDepth() << ") ";
  463. OS << "of ";
  464. NamedCtx->getNameForDiagnostic(OS, TheSema.getLangOpts(), true);
  465. return;
  466. }
  467. if (const auto *Decl = dyn_cast<TemplateTemplateParmDecl>(NamedTemplate)) {
  468. OS << "unnamed template template parameter " << Decl->getIndex() << " ";
  469. if (Decl->getDepth() > 0)
  470. OS << "(at depth " << Decl->getDepth() << ") ";
  471. OS << "of ";
  472. NamedCtx->getNameForDiagnostic(OS, TheSema.getLangOpts(), true);
  473. return;
  474. }
  475. llvm_unreachable("Failed to retrieve a name for this entry!");
  476. OS << "unnamed identifier";
  477. }
  478. template <bool BeginInstantiation>
  479. static TemplightEntry getTemplightEntry(const Sema &TheSema,
  480. const CodeSynthesisContext &Inst) {
  481. TemplightEntry Entry;
  482. Entry.Kind = toString(Inst.Kind);
  483. Entry.Event = BeginInstantiation ? "Begin" : "End";
  484. llvm::raw_string_ostream OS(Entry.Name);
  485. printEntryName(TheSema, Inst.Entity, OS);
  486. const PresumedLoc DefLoc =
  487. TheSema.getSourceManager().getPresumedLoc(Inst.Entity->getLocation());
  488. if (!DefLoc.isInvalid())
  489. Entry.DefinitionLocation = std::string(DefLoc.getFilename()) + ":" +
  490. std::to_string(DefLoc.getLine()) + ":" +
  491. std::to_string(DefLoc.getColumn());
  492. const PresumedLoc PoiLoc =
  493. TheSema.getSourceManager().getPresumedLoc(Inst.PointOfInstantiation);
  494. if (!PoiLoc.isInvalid()) {
  495. Entry.PointOfInstantiation = std::string(PoiLoc.getFilename()) + ":" +
  496. std::to_string(PoiLoc.getLine()) + ":" +
  497. std::to_string(PoiLoc.getColumn());
  498. }
  499. return Entry;
  500. }
  501. };
  502. } // namespace
  503. std::unique_ptr<ASTConsumer>
  504. TemplightDumpAction::CreateASTConsumer(CompilerInstance &CI, StringRef InFile) {
  505. return std::make_unique<ASTConsumer>();
  506. }
  507. void TemplightDumpAction::ExecuteAction() {
  508. CompilerInstance &CI = getCompilerInstance();
  509. // This part is normally done by ASTFrontEndAction, but needs to happen
  510. // before Templight observers can be created
  511. // FIXME: Move the truncation aspect of this into Sema, we delayed this till
  512. // here so the source manager would be initialized.
  513. EnsureSemaIsCreated(CI, *this);
  514. CI.getSema().TemplateInstCallbacks.push_back(
  515. std::make_unique<DefaultTemplateInstCallback>());
  516. ASTFrontendAction::ExecuteAction();
  517. }
  518. namespace {
  519. /// AST reader listener that dumps module information for a module
  520. /// file.
  521. class DumpModuleInfoListener : public ASTReaderListener {
  522. llvm::raw_ostream &Out;
  523. public:
  524. DumpModuleInfoListener(llvm::raw_ostream &Out) : Out(Out) { }
  525. #define DUMP_BOOLEAN(Value, Text) \
  526. Out.indent(4) << Text << ": " << (Value? "Yes" : "No") << "\n"
  527. bool ReadFullVersionInformation(StringRef FullVersion) override {
  528. Out.indent(2)
  529. << "Generated by "
  530. << (FullVersion == getClangFullRepositoryVersion()? "this"
  531. : "a different")
  532. << " Clang: " << FullVersion << "\n";
  533. return ASTReaderListener::ReadFullVersionInformation(FullVersion);
  534. }
  535. void ReadModuleName(StringRef ModuleName) override {
  536. Out.indent(2) << "Module name: " << ModuleName << "\n";
  537. }
  538. void ReadModuleMapFile(StringRef ModuleMapPath) override {
  539. Out.indent(2) << "Module map file: " << ModuleMapPath << "\n";
  540. }
  541. bool ReadLanguageOptions(const LangOptions &LangOpts, bool Complain,
  542. bool AllowCompatibleDifferences) override {
  543. Out.indent(2) << "Language options:\n";
  544. #define LANGOPT(Name, Bits, Default, Description) \
  545. DUMP_BOOLEAN(LangOpts.Name, Description);
  546. #define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
  547. Out.indent(4) << Description << ": " \
  548. << static_cast<unsigned>(LangOpts.get##Name()) << "\n";
  549. #define VALUE_LANGOPT(Name, Bits, Default, Description) \
  550. Out.indent(4) << Description << ": " << LangOpts.Name << "\n";
  551. #define BENIGN_LANGOPT(Name, Bits, Default, Description)
  552. #define BENIGN_ENUM_LANGOPT(Name, Type, Bits, Default, Description)
  553. #include "clang/Basic/LangOptions.def"
  554. if (!LangOpts.ModuleFeatures.empty()) {
  555. Out.indent(4) << "Module features:\n";
  556. for (StringRef Feature : LangOpts.ModuleFeatures)
  557. Out.indent(6) << Feature << "\n";
  558. }
  559. return false;
  560. }
  561. bool ReadTargetOptions(const TargetOptions &TargetOpts, bool Complain,
  562. bool AllowCompatibleDifferences) override {
  563. Out.indent(2) << "Target options:\n";
  564. Out.indent(4) << " Triple: " << TargetOpts.Triple << "\n";
  565. Out.indent(4) << " CPU: " << TargetOpts.CPU << "\n";
  566. Out.indent(4) << " TuneCPU: " << TargetOpts.TuneCPU << "\n";
  567. Out.indent(4) << " ABI: " << TargetOpts.ABI << "\n";
  568. if (!TargetOpts.FeaturesAsWritten.empty()) {
  569. Out.indent(4) << "Target features:\n";
  570. for (unsigned I = 0, N = TargetOpts.FeaturesAsWritten.size();
  571. I != N; ++I) {
  572. Out.indent(6) << TargetOpts.FeaturesAsWritten[I] << "\n";
  573. }
  574. }
  575. return false;
  576. }
  577. bool ReadDiagnosticOptions(IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts,
  578. bool Complain) override {
  579. Out.indent(2) << "Diagnostic options:\n";
  580. #define DIAGOPT(Name, Bits, Default) DUMP_BOOLEAN(DiagOpts->Name, #Name);
  581. #define ENUM_DIAGOPT(Name, Type, Bits, Default) \
  582. Out.indent(4) << #Name << ": " << DiagOpts->get##Name() << "\n";
  583. #define VALUE_DIAGOPT(Name, Bits, Default) \
  584. Out.indent(4) << #Name << ": " << DiagOpts->Name << "\n";
  585. #include "clang/Basic/DiagnosticOptions.def"
  586. Out.indent(4) << "Diagnostic flags:\n";
  587. for (const std::string &Warning : DiagOpts->Warnings)
  588. Out.indent(6) << "-W" << Warning << "\n";
  589. for (const std::string &Remark : DiagOpts->Remarks)
  590. Out.indent(6) << "-R" << Remark << "\n";
  591. return false;
  592. }
  593. bool ReadHeaderSearchOptions(const HeaderSearchOptions &HSOpts,
  594. StringRef SpecificModuleCachePath,
  595. bool Complain) override {
  596. Out.indent(2) << "Header search options:\n";
  597. Out.indent(4) << "System root [-isysroot=]: '" << HSOpts.Sysroot << "'\n";
  598. Out.indent(4) << "Resource dir [ -resource-dir=]: '" << HSOpts.ResourceDir << "'\n";
  599. Out.indent(4) << "Module Cache: '" << SpecificModuleCachePath << "'\n";
  600. DUMP_BOOLEAN(HSOpts.UseBuiltinIncludes,
  601. "Use builtin include directories [-nobuiltininc]");
  602. DUMP_BOOLEAN(HSOpts.UseStandardSystemIncludes,
  603. "Use standard system include directories [-nostdinc]");
  604. DUMP_BOOLEAN(HSOpts.UseStandardCXXIncludes,
  605. "Use standard C++ include directories [-nostdinc++]");
  606. DUMP_BOOLEAN(HSOpts.UseLibcxx,
  607. "Use libc++ (rather than libstdc++) [-stdlib=]");
  608. return false;
  609. }
  610. bool ReadPreprocessorOptions(const PreprocessorOptions &PPOpts,
  611. bool Complain,
  612. std::string &SuggestedPredefines) override {
  613. Out.indent(2) << "Preprocessor options:\n";
  614. DUMP_BOOLEAN(PPOpts.UsePredefines,
  615. "Uses compiler/target-specific predefines [-undef]");
  616. DUMP_BOOLEAN(PPOpts.DetailedRecord,
  617. "Uses detailed preprocessing record (for indexing)");
  618. if (!PPOpts.Macros.empty()) {
  619. Out.indent(4) << "Predefined macros:\n";
  620. }
  621. for (std::vector<std::pair<std::string, bool/*isUndef*/> >::const_iterator
  622. I = PPOpts.Macros.begin(), IEnd = PPOpts.Macros.end();
  623. I != IEnd; ++I) {
  624. Out.indent(6);
  625. if (I->second)
  626. Out << "-U";
  627. else
  628. Out << "-D";
  629. Out << I->first << "\n";
  630. }
  631. return false;
  632. }
  633. /// Indicates that a particular module file extension has been read.
  634. void readModuleFileExtension(
  635. const ModuleFileExtensionMetadata &Metadata) override {
  636. Out.indent(2) << "Module file extension '"
  637. << Metadata.BlockName << "' " << Metadata.MajorVersion
  638. << "." << Metadata.MinorVersion;
  639. if (!Metadata.UserInfo.empty()) {
  640. Out << ": ";
  641. Out.write_escaped(Metadata.UserInfo);
  642. }
  643. Out << "\n";
  644. }
  645. /// Tells the \c ASTReaderListener that we want to receive the
  646. /// input files of the AST file via \c visitInputFile.
  647. bool needsInputFileVisitation() override { return true; }
  648. /// Tells the \c ASTReaderListener that we want to receive the
  649. /// input files of the AST file via \c visitInputFile.
  650. bool needsSystemInputFileVisitation() override { return true; }
  651. /// Indicates that the AST file contains particular input file.
  652. ///
  653. /// \returns true to continue receiving the next input file, false to stop.
  654. bool visitInputFile(StringRef Filename, bool isSystem,
  655. bool isOverridden, bool isExplicitModule) override {
  656. Out.indent(2) << "Input file: " << Filename;
  657. if (isSystem || isOverridden || isExplicitModule) {
  658. Out << " [";
  659. if (isSystem) {
  660. Out << "System";
  661. if (isOverridden || isExplicitModule)
  662. Out << ", ";
  663. }
  664. if (isOverridden) {
  665. Out << "Overridden";
  666. if (isExplicitModule)
  667. Out << ", ";
  668. }
  669. if (isExplicitModule)
  670. Out << "ExplicitModule";
  671. Out << "]";
  672. }
  673. Out << "\n";
  674. return true;
  675. }
  676. /// Returns true if this \c ASTReaderListener wants to receive the
  677. /// imports of the AST file via \c visitImport, false otherwise.
  678. bool needsImportVisitation() const override { return true; }
  679. /// If needsImportVisitation returns \c true, this is called for each
  680. /// AST file imported by this AST file.
  681. void visitImport(StringRef ModuleName, StringRef Filename) override {
  682. Out.indent(2) << "Imports module '" << ModuleName
  683. << "': " << Filename.str() << "\n";
  684. }
  685. #undef DUMP_BOOLEAN
  686. };
  687. }
  688. bool DumpModuleInfoAction::BeginInvocation(CompilerInstance &CI) {
  689. // The Object file reader also supports raw ast files and there is no point in
  690. // being strict about the module file format in -module-file-info mode.
  691. CI.getHeaderSearchOpts().ModuleFormat = "obj";
  692. return true;
  693. }
  694. void DumpModuleInfoAction::ExecuteAction() {
  695. // Set up the output file.
  696. std::unique_ptr<llvm::raw_fd_ostream> OutFile;
  697. StringRef OutputFileName = getCompilerInstance().getFrontendOpts().OutputFile;
  698. if (!OutputFileName.empty() && OutputFileName != "-") {
  699. std::error_code EC;
  700. OutFile.reset(new llvm::raw_fd_ostream(OutputFileName.str(), EC,
  701. llvm::sys::fs::OF_TextWithCRLF));
  702. }
  703. llvm::raw_ostream &Out = OutFile.get()? *OutFile.get() : llvm::outs();
  704. Out << "Information for module file '" << getCurrentFile() << "':\n";
  705. auto &FileMgr = getCompilerInstance().getFileManager();
  706. auto Buffer = FileMgr.getBufferForFile(getCurrentFile());
  707. StringRef Magic = (*Buffer)->getMemBufferRef().getBuffer();
  708. bool IsRaw = (Magic.size() >= 4 && Magic[0] == 'C' && Magic[1] == 'P' &&
  709. Magic[2] == 'C' && Magic[3] == 'H');
  710. Out << " Module format: " << (IsRaw ? "raw" : "obj") << "\n";
  711. Preprocessor &PP = getCompilerInstance().getPreprocessor();
  712. DumpModuleInfoListener Listener(Out);
  713. HeaderSearchOptions &HSOpts =
  714. PP.getHeaderSearchInfo().getHeaderSearchOpts();
  715. ASTReader::readASTFileControlBlock(
  716. getCurrentFile(), FileMgr, getCompilerInstance().getPCHContainerReader(),
  717. /*FindModuleFileExtensions=*/true, Listener,
  718. HSOpts.ModulesValidateDiagnosticOptions);
  719. }
  720. //===----------------------------------------------------------------------===//
  721. // Preprocessor Actions
  722. //===----------------------------------------------------------------------===//
  723. void DumpRawTokensAction::ExecuteAction() {
  724. Preprocessor &PP = getCompilerInstance().getPreprocessor();
  725. SourceManager &SM = PP.getSourceManager();
  726. // Start lexing the specified input file.
  727. llvm::MemoryBufferRef FromFile = SM.getBufferOrFake(SM.getMainFileID());
  728. Lexer RawLex(SM.getMainFileID(), FromFile, SM, PP.getLangOpts());
  729. RawLex.SetKeepWhitespaceMode(true);
  730. Token RawTok;
  731. RawLex.LexFromRawLexer(RawTok);
  732. while (RawTok.isNot(tok::eof)) {
  733. PP.DumpToken(RawTok, true);
  734. llvm::errs() << "\n";
  735. RawLex.LexFromRawLexer(RawTok);
  736. }
  737. }
  738. void DumpTokensAction::ExecuteAction() {
  739. Preprocessor &PP = getCompilerInstance().getPreprocessor();
  740. // Start preprocessing the specified input file.
  741. Token Tok;
  742. PP.EnterMainSourceFile();
  743. do {
  744. PP.Lex(Tok);
  745. PP.DumpToken(Tok, true);
  746. llvm::errs() << "\n";
  747. } while (Tok.isNot(tok::eof));
  748. }
  749. void PreprocessOnlyAction::ExecuteAction() {
  750. Preprocessor &PP = getCompilerInstance().getPreprocessor();
  751. // Ignore unknown pragmas.
  752. PP.IgnorePragmas();
  753. Token Tok;
  754. // Start parsing the specified input file.
  755. PP.EnterMainSourceFile();
  756. do {
  757. PP.Lex(Tok);
  758. } while (Tok.isNot(tok::eof));
  759. }
  760. void PrintPreprocessedAction::ExecuteAction() {
  761. CompilerInstance &CI = getCompilerInstance();
  762. // Output file may need to be set to 'Binary', to avoid converting Unix style
  763. // line feeds (<LF>) to Microsoft style line feeds (<CR><LF>) on Windows.
  764. //
  765. // Look to see what type of line endings the file uses. If there's a
  766. // CRLF, then we won't open the file up in binary mode. If there is
  767. // just an LF or CR, then we will open the file up in binary mode.
  768. // In this fashion, the output format should match the input format, unless
  769. // the input format has inconsistent line endings.
  770. //
  771. // This should be a relatively fast operation since most files won't have
  772. // all of their source code on a single line. However, that is still a
  773. // concern, so if we scan for too long, we'll just assume the file should
  774. // be opened in binary mode.
  775. bool BinaryMode = false;
  776. if (llvm::Triple(LLVM_HOST_TRIPLE).isOSWindows()) {
  777. BinaryMode = true;
  778. const SourceManager &SM = CI.getSourceManager();
  779. if (llvm::Optional<llvm::MemoryBufferRef> Buffer =
  780. SM.getBufferOrNone(SM.getMainFileID())) {
  781. const char *cur = Buffer->getBufferStart();
  782. const char *end = Buffer->getBufferEnd();
  783. const char *next = (cur != end) ? cur + 1 : end;
  784. // Limit ourselves to only scanning 256 characters into the source
  785. // file. This is mostly a check in case the file has no
  786. // newlines whatsoever.
  787. if (end - cur > 256)
  788. end = cur + 256;
  789. while (next < end) {
  790. if (*cur == 0x0D) { // CR
  791. if (*next == 0x0A) // CRLF
  792. BinaryMode = false;
  793. break;
  794. } else if (*cur == 0x0A) // LF
  795. break;
  796. ++cur;
  797. ++next;
  798. }
  799. }
  800. }
  801. std::unique_ptr<raw_ostream> OS =
  802. CI.createDefaultOutputFile(BinaryMode, getCurrentFileOrBufferName());
  803. if (!OS) return;
  804. // If we're preprocessing a module map, start by dumping the contents of the
  805. // module itself before switching to the input buffer.
  806. auto &Input = getCurrentInput();
  807. if (Input.getKind().getFormat() == InputKind::ModuleMap) {
  808. if (Input.isFile()) {
  809. (*OS) << "# 1 \"";
  810. OS->write_escaped(Input.getFile());
  811. (*OS) << "\"\n";
  812. }
  813. getCurrentModule()->print(*OS);
  814. (*OS) << "#pragma clang module contents\n";
  815. }
  816. DoPrintPreprocessedInput(CI.getPreprocessor(), OS.get(),
  817. CI.getPreprocessorOutputOpts());
  818. }
  819. void PrintPreambleAction::ExecuteAction() {
  820. switch (getCurrentFileKind().getLanguage()) {
  821. case Language::C:
  822. case Language::CXX:
  823. case Language::ObjC:
  824. case Language::ObjCXX:
  825. case Language::OpenCL:
  826. case Language::OpenCLCXX:
  827. case Language::CUDA:
  828. case Language::HIP:
  829. break;
  830. case Language::Unknown:
  831. case Language::Asm:
  832. case Language::LLVM_IR:
  833. case Language::RenderScript:
  834. // We can't do anything with these.
  835. return;
  836. }
  837. // We don't expect to find any #include directives in a preprocessed input.
  838. if (getCurrentFileKind().isPreprocessed())
  839. return;
  840. CompilerInstance &CI = getCompilerInstance();
  841. auto Buffer = CI.getFileManager().getBufferForFile(getCurrentFile());
  842. if (Buffer) {
  843. unsigned Preamble =
  844. Lexer::ComputePreamble((*Buffer)->getBuffer(), CI.getLangOpts()).Size;
  845. llvm::outs().write((*Buffer)->getBufferStart(), Preamble);
  846. }
  847. }
  848. void DumpCompilerOptionsAction::ExecuteAction() {
  849. CompilerInstance &CI = getCompilerInstance();
  850. std::unique_ptr<raw_ostream> OSP =
  851. CI.createDefaultOutputFile(false, getCurrentFile());
  852. if (!OSP)
  853. return;
  854. raw_ostream &OS = *OSP;
  855. const Preprocessor &PP = CI.getPreprocessor();
  856. const LangOptions &LangOpts = PP.getLangOpts();
  857. // FIXME: Rather than manually format the JSON (which is awkward due to
  858. // needing to remove trailing commas), this should make use of a JSON library.
  859. // FIXME: Instead of printing enums as an integral value and specifying the
  860. // type as a separate field, use introspection to print the enumerator.
  861. OS << "{\n";
  862. OS << "\n\"features\" : [\n";
  863. {
  864. llvm::SmallString<128> Str;
  865. #define FEATURE(Name, Predicate) \
  866. ("\t{\"" #Name "\" : " + llvm::Twine(Predicate ? "true" : "false") + "},\n") \
  867. .toVector(Str);
  868. #include "clang/Basic/Features.def"
  869. #undef FEATURE
  870. // Remove the newline and comma from the last entry to ensure this remains
  871. // valid JSON.
  872. OS << Str.substr(0, Str.size() - 2);
  873. }
  874. OS << "\n],\n";
  875. OS << "\n\"extensions\" : [\n";
  876. {
  877. llvm::SmallString<128> Str;
  878. #define EXTENSION(Name, Predicate) \
  879. ("\t{\"" #Name "\" : " + llvm::Twine(Predicate ? "true" : "false") + "},\n") \
  880. .toVector(Str);
  881. #include "clang/Basic/Features.def"
  882. #undef EXTENSION
  883. // Remove the newline and comma from the last entry to ensure this remains
  884. // valid JSON.
  885. OS << Str.substr(0, Str.size() - 2);
  886. }
  887. OS << "\n]\n";
  888. OS << "}";
  889. }
  890. void PrintDependencyDirectivesSourceMinimizerAction::ExecuteAction() {
  891. CompilerInstance &CI = getCompilerInstance();
  892. SourceManager &SM = CI.getPreprocessor().getSourceManager();
  893. llvm::MemoryBufferRef FromFile = SM.getBufferOrFake(SM.getMainFileID());
  894. llvm::SmallString<1024> Output;
  895. llvm::SmallVector<minimize_source_to_dependency_directives::Token, 32> Toks;
  896. if (minimizeSourceToDependencyDirectives(
  897. FromFile.getBuffer(), Output, Toks, &CI.getDiagnostics(),
  898. SM.getLocForStartOfFile(SM.getMainFileID()))) {
  899. assert(CI.getDiagnostics().hasErrorOccurred() &&
  900. "no errors reported for failure");
  901. // Preprocess the source when verifying the diagnostics to capture the
  902. // 'expected' comments.
  903. if (CI.getDiagnosticOpts().VerifyDiagnostics) {
  904. // Make sure we don't emit new diagnostics!
  905. CI.getDiagnostics().setSuppressAllDiagnostics(true);
  906. Preprocessor &PP = getCompilerInstance().getPreprocessor();
  907. PP.EnterMainSourceFile();
  908. Token Tok;
  909. do {
  910. PP.Lex(Tok);
  911. } while (Tok.isNot(tok::eof));
  912. }
  913. return;
  914. }
  915. llvm::outs() << Output;
  916. }
  917. void GetDependenciesByModuleNameAction::ExecuteAction() {
  918. CompilerInstance &CI = getCompilerInstance();
  919. Preprocessor &PP = CI.getPreprocessor();
  920. SourceManager &SM = PP.getSourceManager();
  921. FileID MainFileID = SM.getMainFileID();
  922. SourceLocation FileStart = SM.getLocForStartOfFile(MainFileID);
  923. SmallVector<std::pair<IdentifierInfo *, SourceLocation>, 2> Path;
  924. IdentifierInfo *ModuleID = PP.getIdentifierInfo(ModuleName);
  925. Path.push_back(std::make_pair(ModuleID, FileStart));
  926. auto ModResult = CI.loadModule(FileStart, Path, Module::Hidden, false);
  927. PPCallbacks *CB = PP.getPPCallbacks();
  928. CB->moduleImport(SourceLocation(), Path, ModResult);
  929. }