FrontendActions.cpp 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806
  1. //===--- FrontendActions.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/FrontendActions.h"
  10. #include "clang/AST/ASTConsumer.h"
  11. #include "clang/Basic/FileManager.h"
  12. #include "clang/Frontend/ASTConsumers.h"
  13. #include "clang/Frontend/CompilerInstance.h"
  14. #include "clang/Frontend/FrontendDiagnostic.h"
  15. #include "clang/Frontend/MultiplexConsumer.h"
  16. #include "clang/Frontend/Utils.h"
  17. #include "clang/Lex/HeaderSearch.h"
  18. #include "clang/Lex/Preprocessor.h"
  19. #include "clang/Lex/PreprocessorOptions.h"
  20. #include "clang/Sema/TemplateInstCallback.h"
  21. #include "clang/Serialization/ASTReader.h"
  22. #include "clang/Serialization/ASTWriter.h"
  23. #include "llvm/Support/FileSystem.h"
  24. #include "llvm/Support/MemoryBuffer.h"
  25. #include "llvm/Support/Path.h"
  26. #include "llvm/Support/raw_ostream.h"
  27. #include "llvm/Support/YAMLTraits.h"
  28. #include <memory>
  29. #include <system_error>
  30. using namespace clang;
  31. namespace {
  32. CodeCompleteConsumer *GetCodeCompletionConsumer(CompilerInstance &CI) {
  33. return CI.hasCodeCompletionConsumer() ? &CI.getCodeCompletionConsumer()
  34. : nullptr;
  35. }
  36. void EnsureSemaIsCreated(CompilerInstance &CI, FrontendAction &Action) {
  37. if (Action.hasCodeCompletionSupport() &&
  38. !CI.getFrontendOpts().CodeCompletionAt.FileName.empty())
  39. CI.createCodeCompletionConsumer();
  40. if (!CI.hasSema())
  41. CI.createSema(Action.getTranslationUnitKind(),
  42. GetCodeCompletionConsumer(CI));
  43. }
  44. } // namespace
  45. //===----------------------------------------------------------------------===//
  46. // Custom Actions
  47. //===----------------------------------------------------------------------===//
  48. std::unique_ptr<ASTConsumer>
  49. InitOnlyAction::CreateASTConsumer(CompilerInstance &CI, StringRef InFile) {
  50. return llvm::make_unique<ASTConsumer>();
  51. }
  52. void InitOnlyAction::ExecuteAction() {
  53. }
  54. //===----------------------------------------------------------------------===//
  55. // AST Consumer Actions
  56. //===----------------------------------------------------------------------===//
  57. std::unique_ptr<ASTConsumer>
  58. ASTPrintAction::CreateASTConsumer(CompilerInstance &CI, StringRef InFile) {
  59. if (std::unique_ptr<raw_ostream> OS =
  60. CI.createDefaultOutputFile(false, InFile))
  61. return CreateASTPrinter(std::move(OS), CI.getFrontendOpts().ASTDumpFilter);
  62. return nullptr;
  63. }
  64. std::unique_ptr<ASTConsumer>
  65. ASTDumpAction::CreateASTConsumer(CompilerInstance &CI, StringRef InFile) {
  66. return CreateASTDumper(nullptr /*Dump to stdout.*/,
  67. CI.getFrontendOpts().ASTDumpFilter,
  68. CI.getFrontendOpts().ASTDumpDecls,
  69. CI.getFrontendOpts().ASTDumpAll,
  70. CI.getFrontendOpts().ASTDumpLookups);
  71. }
  72. std::unique_ptr<ASTConsumer>
  73. ASTDeclListAction::CreateASTConsumer(CompilerInstance &CI, StringRef InFile) {
  74. return CreateASTDeclNodeLister();
  75. }
  76. std::unique_ptr<ASTConsumer>
  77. ASTViewAction::CreateASTConsumer(CompilerInstance &CI, StringRef InFile) {
  78. return CreateASTViewer();
  79. }
  80. std::unique_ptr<ASTConsumer>
  81. DeclContextPrintAction::CreateASTConsumer(CompilerInstance &CI,
  82. StringRef InFile) {
  83. return CreateDeclContextPrinter();
  84. }
  85. std::unique_ptr<ASTConsumer>
  86. GeneratePCHAction::CreateASTConsumer(CompilerInstance &CI, StringRef InFile) {
  87. std::string Sysroot;
  88. if (!ComputeASTConsumerArguments(CI, /*ref*/ Sysroot))
  89. return nullptr;
  90. std::string OutputFile;
  91. std::unique_ptr<raw_pwrite_stream> OS =
  92. CreateOutputFile(CI, InFile, /*ref*/ OutputFile);
  93. if (!OS)
  94. return nullptr;
  95. if (!CI.getFrontendOpts().RelocatablePCH)
  96. Sysroot.clear();
  97. auto Buffer = std::make_shared<PCHBuffer>();
  98. std::vector<std::unique_ptr<ASTConsumer>> Consumers;
  99. Consumers.push_back(llvm::make_unique<PCHGenerator>(
  100. CI.getPreprocessor(), OutputFile, Sysroot,
  101. Buffer, CI.getFrontendOpts().ModuleFileExtensions,
  102. /*AllowASTWithErrors*/CI.getPreprocessorOpts().AllowPCHWithCompilerErrors,
  103. /*IncludeTimestamps*/
  104. +CI.getFrontendOpts().IncludeTimestamps));
  105. Consumers.push_back(CI.getPCHContainerWriter().CreatePCHContainerGenerator(
  106. CI, InFile, OutputFile, std::move(OS), Buffer));
  107. return llvm::make_unique<MultiplexConsumer>(std::move(Consumers));
  108. }
  109. bool GeneratePCHAction::ComputeASTConsumerArguments(CompilerInstance &CI,
  110. std::string &Sysroot) {
  111. Sysroot = CI.getHeaderSearchOpts().Sysroot;
  112. if (CI.getFrontendOpts().RelocatablePCH && Sysroot.empty()) {
  113. CI.getDiagnostics().Report(diag::err_relocatable_without_isysroot);
  114. return false;
  115. }
  116. return true;
  117. }
  118. std::unique_ptr<llvm::raw_pwrite_stream>
  119. GeneratePCHAction::CreateOutputFile(CompilerInstance &CI, StringRef InFile,
  120. std::string &OutputFile) {
  121. // We use createOutputFile here because this is exposed via libclang, and we
  122. // must disable the RemoveFileOnSignal behavior.
  123. // We use a temporary to avoid race conditions.
  124. std::unique_ptr<raw_pwrite_stream> OS =
  125. CI.createOutputFile(CI.getFrontendOpts().OutputFile, /*Binary=*/true,
  126. /*RemoveFileOnSignal=*/false, InFile,
  127. /*Extension=*/"", /*useTemporary=*/true);
  128. if (!OS)
  129. return nullptr;
  130. OutputFile = CI.getFrontendOpts().OutputFile;
  131. return OS;
  132. }
  133. bool GeneratePCHAction::shouldEraseOutputFiles() {
  134. if (getCompilerInstance().getPreprocessorOpts().AllowPCHWithCompilerErrors)
  135. return false;
  136. return ASTFrontendAction::shouldEraseOutputFiles();
  137. }
  138. bool GeneratePCHAction::BeginSourceFileAction(CompilerInstance &CI) {
  139. CI.getLangOpts().CompilingPCH = true;
  140. return true;
  141. }
  142. std::unique_ptr<ASTConsumer>
  143. GenerateModuleAction::CreateASTConsumer(CompilerInstance &CI,
  144. StringRef InFile) {
  145. std::unique_ptr<raw_pwrite_stream> OS = CreateOutputFile(CI, InFile);
  146. if (!OS)
  147. return nullptr;
  148. std::string OutputFile = CI.getFrontendOpts().OutputFile;
  149. std::string Sysroot;
  150. auto Buffer = std::make_shared<PCHBuffer>();
  151. std::vector<std::unique_ptr<ASTConsumer>> Consumers;
  152. Consumers.push_back(llvm::make_unique<PCHGenerator>(
  153. CI.getPreprocessor(), OutputFile, Sysroot,
  154. Buffer, CI.getFrontendOpts().ModuleFileExtensions,
  155. /*AllowASTWithErrors=*/false,
  156. /*IncludeTimestamps=*/
  157. +CI.getFrontendOpts().BuildingImplicitModule));
  158. Consumers.push_back(CI.getPCHContainerWriter().CreatePCHContainerGenerator(
  159. CI, InFile, OutputFile, std::move(OS), Buffer));
  160. return llvm::make_unique<MultiplexConsumer>(std::move(Consumers));
  161. }
  162. bool GenerateModuleFromModuleMapAction::BeginSourceFileAction(
  163. CompilerInstance &CI) {
  164. if (!CI.getLangOpts().Modules) {
  165. CI.getDiagnostics().Report(diag::err_module_build_requires_fmodules);
  166. return false;
  167. }
  168. return GenerateModuleAction::BeginSourceFileAction(CI);
  169. }
  170. std::unique_ptr<raw_pwrite_stream>
  171. GenerateModuleFromModuleMapAction::CreateOutputFile(CompilerInstance &CI,
  172. StringRef InFile) {
  173. // If no output file was provided, figure out where this module would go
  174. // in the module cache.
  175. if (CI.getFrontendOpts().OutputFile.empty()) {
  176. StringRef ModuleMapFile = CI.getFrontendOpts().OriginalModuleMap;
  177. if (ModuleMapFile.empty())
  178. ModuleMapFile = InFile;
  179. HeaderSearch &HS = CI.getPreprocessor().getHeaderSearchInfo();
  180. CI.getFrontendOpts().OutputFile =
  181. HS.getCachedModuleFileName(CI.getLangOpts().CurrentModule,
  182. ModuleMapFile);
  183. }
  184. // We use createOutputFile here because this is exposed via libclang, and we
  185. // must disable the RemoveFileOnSignal behavior.
  186. // We use a temporary to avoid race conditions.
  187. return CI.createOutputFile(CI.getFrontendOpts().OutputFile, /*Binary=*/true,
  188. /*RemoveFileOnSignal=*/false, InFile,
  189. /*Extension=*/"", /*useTemporary=*/true,
  190. /*CreateMissingDirectories=*/true);
  191. }
  192. bool GenerateModuleInterfaceAction::BeginSourceFileAction(
  193. CompilerInstance &CI) {
  194. if (!CI.getLangOpts().ModulesTS) {
  195. CI.getDiagnostics().Report(diag::err_module_interface_requires_modules_ts);
  196. return false;
  197. }
  198. CI.getLangOpts().setCompilingModule(LangOptions::CMK_ModuleInterface);
  199. return GenerateModuleAction::BeginSourceFileAction(CI);
  200. }
  201. std::unique_ptr<raw_pwrite_stream>
  202. GenerateModuleInterfaceAction::CreateOutputFile(CompilerInstance &CI,
  203. StringRef InFile) {
  204. return CI.createDefaultOutputFile(/*Binary=*/true, InFile, "pcm");
  205. }
  206. SyntaxOnlyAction::~SyntaxOnlyAction() {
  207. }
  208. std::unique_ptr<ASTConsumer>
  209. SyntaxOnlyAction::CreateASTConsumer(CompilerInstance &CI, StringRef InFile) {
  210. return llvm::make_unique<ASTConsumer>();
  211. }
  212. std::unique_ptr<ASTConsumer>
  213. DumpModuleInfoAction::CreateASTConsumer(CompilerInstance &CI,
  214. StringRef InFile) {
  215. return llvm::make_unique<ASTConsumer>();
  216. }
  217. std::unique_ptr<ASTConsumer>
  218. VerifyPCHAction::CreateASTConsumer(CompilerInstance &CI, StringRef InFile) {
  219. return llvm::make_unique<ASTConsumer>();
  220. }
  221. void VerifyPCHAction::ExecuteAction() {
  222. CompilerInstance &CI = getCompilerInstance();
  223. bool Preamble = CI.getPreprocessorOpts().PrecompiledPreambleBytes.first != 0;
  224. const std::string &Sysroot = CI.getHeaderSearchOpts().Sysroot;
  225. std::unique_ptr<ASTReader> Reader(new ASTReader(
  226. CI.getPreprocessor(), &CI.getASTContext(), CI.getPCHContainerReader(),
  227. CI.getFrontendOpts().ModuleFileExtensions,
  228. Sysroot.empty() ? "" : Sysroot.c_str(),
  229. /*DisableValidation*/ false,
  230. /*AllowPCHWithCompilerErrors*/ false,
  231. /*AllowConfigurationMismatch*/ true,
  232. /*ValidateSystemInputs*/ true));
  233. Reader->ReadAST(getCurrentFile(),
  234. Preamble ? serialization::MK_Preamble
  235. : serialization::MK_PCH,
  236. SourceLocation(),
  237. ASTReader::ARR_ConfigurationMismatch);
  238. }
  239. namespace {
  240. struct TemplightEntry {
  241. std::string Name;
  242. std::string Kind;
  243. std::string Event;
  244. std::string DefinitionLocation;
  245. std::string PointOfInstantiation;
  246. };
  247. } // namespace
  248. namespace llvm {
  249. namespace yaml {
  250. template <> struct MappingTraits<TemplightEntry> {
  251. static void mapping(IO &io, TemplightEntry &fields) {
  252. io.mapRequired("name", fields.Name);
  253. io.mapRequired("kind", fields.Kind);
  254. io.mapRequired("event", fields.Event);
  255. io.mapRequired("orig", fields.DefinitionLocation);
  256. io.mapRequired("poi", fields.PointOfInstantiation);
  257. }
  258. };
  259. } // namespace yaml
  260. } // namespace llvm
  261. namespace {
  262. class DefaultTemplateInstCallback : public TemplateInstantiationCallback {
  263. using CodeSynthesisContext = Sema::CodeSynthesisContext;
  264. public:
  265. void initialize(const Sema &) override {}
  266. void finalize(const Sema &) override {}
  267. void atTemplateBegin(const Sema &TheSema,
  268. const CodeSynthesisContext &Inst) override {
  269. displayTemplightEntry<true>(llvm::outs(), TheSema, Inst);
  270. }
  271. void atTemplateEnd(const Sema &TheSema,
  272. const CodeSynthesisContext &Inst) override {
  273. displayTemplightEntry<false>(llvm::outs(), TheSema, Inst);
  274. }
  275. private:
  276. static std::string toString(CodeSynthesisContext::SynthesisKind Kind) {
  277. switch (Kind) {
  278. case CodeSynthesisContext::TemplateInstantiation:
  279. return "TemplateInstantiation";
  280. case CodeSynthesisContext::DefaultTemplateArgumentInstantiation:
  281. return "DefaultTemplateArgumentInstantiation";
  282. case CodeSynthesisContext::DefaultFunctionArgumentInstantiation:
  283. return "DefaultFunctionArgumentInstantiation";
  284. case CodeSynthesisContext::ExplicitTemplateArgumentSubstitution:
  285. return "ExplicitTemplateArgumentSubstitution";
  286. case CodeSynthesisContext::DeducedTemplateArgumentSubstitution:
  287. return "DeducedTemplateArgumentSubstitution";
  288. case CodeSynthesisContext::PriorTemplateArgumentSubstitution:
  289. return "PriorTemplateArgumentSubstitution";
  290. case CodeSynthesisContext::DefaultTemplateArgumentChecking:
  291. return "DefaultTemplateArgumentChecking";
  292. case CodeSynthesisContext::ExceptionSpecInstantiation:
  293. return "ExceptionSpecInstantiation";
  294. case CodeSynthesisContext::DeclaringSpecialMember:
  295. return "DeclaringSpecialMember";
  296. case CodeSynthesisContext::DefiningSynthesizedFunction:
  297. return "DefiningSynthesizedFunction";
  298. case CodeSynthesisContext::Memoization:
  299. return "Memoization";
  300. }
  301. return "";
  302. }
  303. template <bool BeginInstantiation>
  304. static void displayTemplightEntry(llvm::raw_ostream &Out, const Sema &TheSema,
  305. const CodeSynthesisContext &Inst) {
  306. std::string YAML;
  307. {
  308. llvm::raw_string_ostream OS(YAML);
  309. llvm::yaml::Output YO(OS);
  310. TemplightEntry Entry =
  311. getTemplightEntry<BeginInstantiation>(TheSema, Inst);
  312. llvm::yaml::EmptyContext Context;
  313. llvm::yaml::yamlize(YO, Entry, true, Context);
  314. }
  315. Out << "---" << YAML << "\n";
  316. }
  317. template <bool BeginInstantiation>
  318. static TemplightEntry getTemplightEntry(const Sema &TheSema,
  319. const CodeSynthesisContext &Inst) {
  320. TemplightEntry Entry;
  321. Entry.Kind = toString(Inst.Kind);
  322. Entry.Event = BeginInstantiation ? "Begin" : "End";
  323. if (auto *NamedTemplate = dyn_cast_or_null<NamedDecl>(Inst.Entity)) {
  324. llvm::raw_string_ostream OS(Entry.Name);
  325. NamedTemplate->getNameForDiagnostic(OS, TheSema.getLangOpts(), true);
  326. const PresumedLoc DefLoc =
  327. TheSema.getSourceManager().getPresumedLoc(Inst.Entity->getLocation());
  328. if(!DefLoc.isInvalid())
  329. Entry.DefinitionLocation = std::string(DefLoc.getFilename()) + ":" +
  330. std::to_string(DefLoc.getLine()) + ":" +
  331. std::to_string(DefLoc.getColumn());
  332. }
  333. const PresumedLoc PoiLoc =
  334. TheSema.getSourceManager().getPresumedLoc(Inst.PointOfInstantiation);
  335. if (!PoiLoc.isInvalid()) {
  336. Entry.PointOfInstantiation = std::string(PoiLoc.getFilename()) + ":" +
  337. std::to_string(PoiLoc.getLine()) + ":" +
  338. std::to_string(PoiLoc.getColumn());
  339. }
  340. return Entry;
  341. }
  342. };
  343. } // namespace
  344. std::unique_ptr<ASTConsumer>
  345. TemplightDumpAction::CreateASTConsumer(CompilerInstance &CI, StringRef InFile) {
  346. return llvm::make_unique<ASTConsumer>();
  347. }
  348. void TemplightDumpAction::ExecuteAction() {
  349. CompilerInstance &CI = getCompilerInstance();
  350. // This part is normally done by ASTFrontEndAction, but needs to happen
  351. // before Templight observers can be created
  352. // FIXME: Move the truncation aspect of this into Sema, we delayed this till
  353. // here so the source manager would be initialized.
  354. EnsureSemaIsCreated(CI, *this);
  355. CI.getSema().TemplateInstCallbacks.push_back(
  356. llvm::make_unique<DefaultTemplateInstCallback>());
  357. ASTFrontendAction::ExecuteAction();
  358. }
  359. namespace {
  360. /// AST reader listener that dumps module information for a module
  361. /// file.
  362. class DumpModuleInfoListener : public ASTReaderListener {
  363. llvm::raw_ostream &Out;
  364. public:
  365. DumpModuleInfoListener(llvm::raw_ostream &Out) : Out(Out) { }
  366. #define DUMP_BOOLEAN(Value, Text) \
  367. Out.indent(4) << Text << ": " << (Value? "Yes" : "No") << "\n"
  368. bool ReadFullVersionInformation(StringRef FullVersion) override {
  369. Out.indent(2)
  370. << "Generated by "
  371. << (FullVersion == getClangFullRepositoryVersion()? "this"
  372. : "a different")
  373. << " Clang: " << FullVersion << "\n";
  374. return ASTReaderListener::ReadFullVersionInformation(FullVersion);
  375. }
  376. void ReadModuleName(StringRef ModuleName) override {
  377. Out.indent(2) << "Module name: " << ModuleName << "\n";
  378. }
  379. void ReadModuleMapFile(StringRef ModuleMapPath) override {
  380. Out.indent(2) << "Module map file: " << ModuleMapPath << "\n";
  381. }
  382. bool ReadLanguageOptions(const LangOptions &LangOpts, bool Complain,
  383. bool AllowCompatibleDifferences) override {
  384. Out.indent(2) << "Language options:\n";
  385. #define LANGOPT(Name, Bits, Default, Description) \
  386. DUMP_BOOLEAN(LangOpts.Name, Description);
  387. #define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
  388. Out.indent(4) << Description << ": " \
  389. << static_cast<unsigned>(LangOpts.get##Name()) << "\n";
  390. #define VALUE_LANGOPT(Name, Bits, Default, Description) \
  391. Out.indent(4) << Description << ": " << LangOpts.Name << "\n";
  392. #define BENIGN_LANGOPT(Name, Bits, Default, Description)
  393. #define BENIGN_ENUM_LANGOPT(Name, Type, Bits, Default, Description)
  394. #include "clang/Basic/LangOptions.def"
  395. if (!LangOpts.ModuleFeatures.empty()) {
  396. Out.indent(4) << "Module features:\n";
  397. for (StringRef Feature : LangOpts.ModuleFeatures)
  398. Out.indent(6) << Feature << "\n";
  399. }
  400. return false;
  401. }
  402. bool ReadTargetOptions(const TargetOptions &TargetOpts, bool Complain,
  403. bool AllowCompatibleDifferences) override {
  404. Out.indent(2) << "Target options:\n";
  405. Out.indent(4) << " Triple: " << TargetOpts.Triple << "\n";
  406. Out.indent(4) << " CPU: " << TargetOpts.CPU << "\n";
  407. Out.indent(4) << " ABI: " << TargetOpts.ABI << "\n";
  408. if (!TargetOpts.FeaturesAsWritten.empty()) {
  409. Out.indent(4) << "Target features:\n";
  410. for (unsigned I = 0, N = TargetOpts.FeaturesAsWritten.size();
  411. I != N; ++I) {
  412. Out.indent(6) << TargetOpts.FeaturesAsWritten[I] << "\n";
  413. }
  414. }
  415. return false;
  416. }
  417. bool ReadDiagnosticOptions(IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts,
  418. bool Complain) override {
  419. Out.indent(2) << "Diagnostic options:\n";
  420. #define DIAGOPT(Name, Bits, Default) DUMP_BOOLEAN(DiagOpts->Name, #Name);
  421. #define ENUM_DIAGOPT(Name, Type, Bits, Default) \
  422. Out.indent(4) << #Name << ": " << DiagOpts->get##Name() << "\n";
  423. #define VALUE_DIAGOPT(Name, Bits, Default) \
  424. Out.indent(4) << #Name << ": " << DiagOpts->Name << "\n";
  425. #include "clang/Basic/DiagnosticOptions.def"
  426. Out.indent(4) << "Diagnostic flags:\n";
  427. for (const std::string &Warning : DiagOpts->Warnings)
  428. Out.indent(6) << "-W" << Warning << "\n";
  429. for (const std::string &Remark : DiagOpts->Remarks)
  430. Out.indent(6) << "-R" << Remark << "\n";
  431. return false;
  432. }
  433. bool ReadHeaderSearchOptions(const HeaderSearchOptions &HSOpts,
  434. StringRef SpecificModuleCachePath,
  435. bool Complain) override {
  436. Out.indent(2) << "Header search options:\n";
  437. Out.indent(4) << "System root [-isysroot=]: '" << HSOpts.Sysroot << "'\n";
  438. Out.indent(4) << "Resource dir [ -resource-dir=]: '" << HSOpts.ResourceDir << "'\n";
  439. Out.indent(4) << "Module Cache: '" << SpecificModuleCachePath << "'\n";
  440. DUMP_BOOLEAN(HSOpts.UseBuiltinIncludes,
  441. "Use builtin include directories [-nobuiltininc]");
  442. DUMP_BOOLEAN(HSOpts.UseStandardSystemIncludes,
  443. "Use standard system include directories [-nostdinc]");
  444. DUMP_BOOLEAN(HSOpts.UseStandardCXXIncludes,
  445. "Use standard C++ include directories [-nostdinc++]");
  446. DUMP_BOOLEAN(HSOpts.UseLibcxx,
  447. "Use libc++ (rather than libstdc++) [-stdlib=]");
  448. return false;
  449. }
  450. bool ReadPreprocessorOptions(const PreprocessorOptions &PPOpts,
  451. bool Complain,
  452. std::string &SuggestedPredefines) override {
  453. Out.indent(2) << "Preprocessor options:\n";
  454. DUMP_BOOLEAN(PPOpts.UsePredefines,
  455. "Uses compiler/target-specific predefines [-undef]");
  456. DUMP_BOOLEAN(PPOpts.DetailedRecord,
  457. "Uses detailed preprocessing record (for indexing)");
  458. if (!PPOpts.Macros.empty()) {
  459. Out.indent(4) << "Predefined macros:\n";
  460. }
  461. for (std::vector<std::pair<std::string, bool/*isUndef*/> >::const_iterator
  462. I = PPOpts.Macros.begin(), IEnd = PPOpts.Macros.end();
  463. I != IEnd; ++I) {
  464. Out.indent(6);
  465. if (I->second)
  466. Out << "-U";
  467. else
  468. Out << "-D";
  469. Out << I->first << "\n";
  470. }
  471. return false;
  472. }
  473. /// Indicates that a particular module file extension has been read.
  474. void readModuleFileExtension(
  475. const ModuleFileExtensionMetadata &Metadata) override {
  476. Out.indent(2) << "Module file extension '"
  477. << Metadata.BlockName << "' " << Metadata.MajorVersion
  478. << "." << Metadata.MinorVersion;
  479. if (!Metadata.UserInfo.empty()) {
  480. Out << ": ";
  481. Out.write_escaped(Metadata.UserInfo);
  482. }
  483. Out << "\n";
  484. }
  485. #undef DUMP_BOOLEAN
  486. };
  487. }
  488. bool DumpModuleInfoAction::BeginInvocation(CompilerInstance &CI) {
  489. // The Object file reader also supports raw ast files and there is no point in
  490. // being strict about the module file format in -module-file-info mode.
  491. CI.getHeaderSearchOpts().ModuleFormat = "obj";
  492. return true;
  493. }
  494. void DumpModuleInfoAction::ExecuteAction() {
  495. // Set up the output file.
  496. std::unique_ptr<llvm::raw_fd_ostream> OutFile;
  497. StringRef OutputFileName = getCompilerInstance().getFrontendOpts().OutputFile;
  498. if (!OutputFileName.empty() && OutputFileName != "-") {
  499. std::error_code EC;
  500. OutFile.reset(new llvm::raw_fd_ostream(OutputFileName.str(), EC,
  501. llvm::sys::fs::F_Text));
  502. }
  503. llvm::raw_ostream &Out = OutFile.get()? *OutFile.get() : llvm::outs();
  504. Out << "Information for module file '" << getCurrentFile() << "':\n";
  505. auto &FileMgr = getCompilerInstance().getFileManager();
  506. auto Buffer = FileMgr.getBufferForFile(getCurrentFile());
  507. StringRef Magic = (*Buffer)->getMemBufferRef().getBuffer();
  508. bool IsRaw = (Magic.size() >= 4 && Magic[0] == 'C' && Magic[1] == 'P' &&
  509. Magic[2] == 'C' && Magic[3] == 'H');
  510. Out << " Module format: " << (IsRaw ? "raw" : "obj") << "\n";
  511. Preprocessor &PP = getCompilerInstance().getPreprocessor();
  512. DumpModuleInfoListener Listener(Out);
  513. HeaderSearchOptions &HSOpts =
  514. PP.getHeaderSearchInfo().getHeaderSearchOpts();
  515. ASTReader::readASTFileControlBlock(
  516. getCurrentFile(), FileMgr, getCompilerInstance().getPCHContainerReader(),
  517. /*FindModuleFileExtensions=*/true, Listener,
  518. HSOpts.ModulesValidateDiagnosticOptions);
  519. }
  520. //===----------------------------------------------------------------------===//
  521. // Preprocessor Actions
  522. //===----------------------------------------------------------------------===//
  523. void DumpRawTokensAction::ExecuteAction() {
  524. Preprocessor &PP = getCompilerInstance().getPreprocessor();
  525. SourceManager &SM = PP.getSourceManager();
  526. // Start lexing the specified input file.
  527. const llvm::MemoryBuffer *FromFile = SM.getBuffer(SM.getMainFileID());
  528. Lexer RawLex(SM.getMainFileID(), FromFile, SM, PP.getLangOpts());
  529. RawLex.SetKeepWhitespaceMode(true);
  530. Token RawTok;
  531. RawLex.LexFromRawLexer(RawTok);
  532. while (RawTok.isNot(tok::eof)) {
  533. PP.DumpToken(RawTok, true);
  534. llvm::errs() << "\n";
  535. RawLex.LexFromRawLexer(RawTok);
  536. }
  537. }
  538. void DumpTokensAction::ExecuteAction() {
  539. Preprocessor &PP = getCompilerInstance().getPreprocessor();
  540. // Start preprocessing the specified input file.
  541. Token Tok;
  542. PP.EnterMainSourceFile();
  543. do {
  544. PP.Lex(Tok);
  545. PP.DumpToken(Tok, true);
  546. llvm::errs() << "\n";
  547. } while (Tok.isNot(tok::eof));
  548. }
  549. void GeneratePTHAction::ExecuteAction() {
  550. CompilerInstance &CI = getCompilerInstance();
  551. std::unique_ptr<raw_pwrite_stream> OS =
  552. CI.createDefaultOutputFile(true, getCurrentFile());
  553. if (!OS)
  554. return;
  555. CacheTokens(CI.getPreprocessor(), OS.get());
  556. }
  557. void PreprocessOnlyAction::ExecuteAction() {
  558. Preprocessor &PP = getCompilerInstance().getPreprocessor();
  559. // Ignore unknown pragmas.
  560. PP.IgnorePragmas();
  561. Token Tok;
  562. // Start parsing the specified input file.
  563. PP.EnterMainSourceFile();
  564. do {
  565. PP.Lex(Tok);
  566. } while (Tok.isNot(tok::eof));
  567. }
  568. void PrintPreprocessedAction::ExecuteAction() {
  569. CompilerInstance &CI = getCompilerInstance();
  570. // Output file may need to be set to 'Binary', to avoid converting Unix style
  571. // line feeds (<LF>) to Microsoft style line feeds (<CR><LF>).
  572. //
  573. // Look to see what type of line endings the file uses. If there's a
  574. // CRLF, then we won't open the file up in binary mode. If there is
  575. // just an LF or CR, then we will open the file up in binary mode.
  576. // In this fashion, the output format should match the input format, unless
  577. // the input format has inconsistent line endings.
  578. //
  579. // This should be a relatively fast operation since most files won't have
  580. // all of their source code on a single line. However, that is still a
  581. // concern, so if we scan for too long, we'll just assume the file should
  582. // be opened in binary mode.
  583. bool BinaryMode = true;
  584. bool InvalidFile = false;
  585. const SourceManager& SM = CI.getSourceManager();
  586. const llvm::MemoryBuffer *Buffer = SM.getBuffer(SM.getMainFileID(),
  587. &InvalidFile);
  588. if (!InvalidFile) {
  589. const char *cur = Buffer->getBufferStart();
  590. const char *end = Buffer->getBufferEnd();
  591. const char *next = (cur != end) ? cur + 1 : end;
  592. // Limit ourselves to only scanning 256 characters into the source
  593. // file. This is mostly a sanity check in case the file has no
  594. // newlines whatsoever.
  595. if (end - cur > 256) end = cur + 256;
  596. while (next < end) {
  597. if (*cur == 0x0D) { // CR
  598. if (*next == 0x0A) // CRLF
  599. BinaryMode = false;
  600. break;
  601. } else if (*cur == 0x0A) // LF
  602. break;
  603. ++cur;
  604. ++next;
  605. }
  606. }
  607. std::unique_ptr<raw_ostream> OS =
  608. CI.createDefaultOutputFile(BinaryMode, getCurrentFile());
  609. if (!OS) return;
  610. // If we're preprocessing a module map, start by dumping the contents of the
  611. // module itself before switching to the input buffer.
  612. auto &Input = getCurrentInput();
  613. if (Input.getKind().getFormat() == InputKind::ModuleMap) {
  614. if (Input.isFile()) {
  615. (*OS) << "# 1 \"";
  616. OS->write_escaped(Input.getFile());
  617. (*OS) << "\"\n";
  618. }
  619. // FIXME: Include additional information here so that we don't need the
  620. // original source files to exist on disk.
  621. getCurrentModule()->print(*OS);
  622. (*OS) << "#pragma clang module contents\n";
  623. }
  624. DoPrintPreprocessedInput(CI.getPreprocessor(), OS.get(),
  625. CI.getPreprocessorOutputOpts());
  626. }
  627. void PrintPreambleAction::ExecuteAction() {
  628. switch (getCurrentFileKind().getLanguage()) {
  629. case InputKind::C:
  630. case InputKind::CXX:
  631. case InputKind::ObjC:
  632. case InputKind::ObjCXX:
  633. case InputKind::OpenCL:
  634. case InputKind::CUDA:
  635. case InputKind::HIP:
  636. break;
  637. case InputKind::Unknown:
  638. case InputKind::Asm:
  639. case InputKind::LLVM_IR:
  640. case InputKind::RenderScript:
  641. // We can't do anything with these.
  642. return;
  643. }
  644. // We don't expect to find any #include directives in a preprocessed input.
  645. if (getCurrentFileKind().isPreprocessed())
  646. return;
  647. CompilerInstance &CI = getCompilerInstance();
  648. auto Buffer = CI.getFileManager().getBufferForFile(getCurrentFile());
  649. if (Buffer) {
  650. unsigned Preamble =
  651. Lexer::ComputePreamble((*Buffer)->getBuffer(), CI.getLangOpts()).Size;
  652. llvm::outs().write((*Buffer)->getBufferStart(), Preamble);
  653. }
  654. }
  655. void DumpCompilerOptionsAction::ExecuteAction() {
  656. CompilerInstance &CI = getCompilerInstance();
  657. std::unique_ptr<raw_ostream> OSP =
  658. CI.createDefaultOutputFile(false, getCurrentFile());
  659. if (!OSP)
  660. return;
  661. raw_ostream &OS = *OSP;
  662. const Preprocessor &PP = CI.getPreprocessor();
  663. const LangOptions &LangOpts = PP.getLangOpts();
  664. // FIXME: Rather than manually format the JSON (which is awkward due to
  665. // needing to remove trailing commas), this should make use of a JSON library.
  666. // FIXME: Instead of printing enums as an integral value and specifying the
  667. // type as a separate field, use introspection to print the enumerator.
  668. OS << "{\n";
  669. OS << "\n\"features\" : [\n";
  670. {
  671. llvm::SmallString<128> Str;
  672. #define FEATURE(Name, Predicate) \
  673. ("\t{\"" #Name "\" : " + llvm::Twine(Predicate ? "true" : "false") + "},\n") \
  674. .toVector(Str);
  675. #include "clang/Basic/Features.def"
  676. #undef FEATURE
  677. // Remove the newline and comma from the last entry to ensure this remains
  678. // valid JSON.
  679. OS << Str.substr(0, Str.size() - 2);
  680. }
  681. OS << "\n],\n";
  682. OS << "\n\"extensions\" : [\n";
  683. {
  684. llvm::SmallString<128> Str;
  685. #define EXTENSION(Name, Predicate) \
  686. ("\t{\"" #Name "\" : " + llvm::Twine(Predicate ? "true" : "false") + "},\n") \
  687. .toVector(Str);
  688. #include "clang/Basic/Features.def"
  689. #undef EXTENSION
  690. // Remove the newline and comma from the last entry to ensure this remains
  691. // valid JSON.
  692. OS << Str.substr(0, Str.size() - 2);
  693. }
  694. OS << "\n]\n";
  695. OS << "}";
  696. }