FrontendActions.cpp 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710
  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/ASTUnit.h"
  14. #include "clang/Frontend/CompilerInstance.h"
  15. #include "clang/Frontend/FrontendDiagnostic.h"
  16. #include "clang/Frontend/Utils.h"
  17. #include "clang/Lex/HeaderSearch.h"
  18. #include "clang/Lex/Pragma.h"
  19. #include "clang/Lex/Preprocessor.h"
  20. #include "clang/Parse/Parser.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/raw_ostream.h"
  26. #include <memory>
  27. #include <system_error>
  28. using namespace clang;
  29. //===----------------------------------------------------------------------===//
  30. // Custom Actions
  31. //===----------------------------------------------------------------------===//
  32. std::unique_ptr<ASTConsumer>
  33. InitOnlyAction::CreateASTConsumer(CompilerInstance &CI, StringRef InFile) {
  34. return llvm::make_unique<ASTConsumer>();
  35. }
  36. void InitOnlyAction::ExecuteAction() {
  37. }
  38. //===----------------------------------------------------------------------===//
  39. // AST Consumer Actions
  40. //===----------------------------------------------------------------------===//
  41. std::unique_ptr<ASTConsumer>
  42. ASTPrintAction::CreateASTConsumer(CompilerInstance &CI, StringRef InFile) {
  43. if (raw_ostream *OS = CI.createDefaultOutputFile(false, InFile))
  44. return CreateASTPrinter(OS, CI.getFrontendOpts().ASTDumpFilter);
  45. return nullptr;
  46. }
  47. std::unique_ptr<ASTConsumer>
  48. ASTDumpAction::CreateASTConsumer(CompilerInstance &CI, StringRef InFile) {
  49. return CreateASTDumper(CI.getFrontendOpts().ASTDumpFilter,
  50. CI.getFrontendOpts().ASTDumpDecls,
  51. CI.getFrontendOpts().ASTDumpLookups);
  52. }
  53. std::unique_ptr<ASTConsumer>
  54. ASTDeclListAction::CreateASTConsumer(CompilerInstance &CI, StringRef InFile) {
  55. return CreateASTDeclNodeLister();
  56. }
  57. std::unique_ptr<ASTConsumer>
  58. ASTViewAction::CreateASTConsumer(CompilerInstance &CI, StringRef InFile) {
  59. return CreateASTViewer();
  60. }
  61. std::unique_ptr<ASTConsumer>
  62. DeclContextPrintAction::CreateASTConsumer(CompilerInstance &CI,
  63. StringRef InFile) {
  64. return CreateDeclContextPrinter();
  65. }
  66. std::unique_ptr<ASTConsumer>
  67. GeneratePCHAction::CreateASTConsumer(CompilerInstance &CI, StringRef InFile) {
  68. std::string Sysroot;
  69. std::string OutputFile;
  70. raw_ostream *OS = nullptr;
  71. if (ComputeASTConsumerArguments(CI, InFile, Sysroot, OutputFile, OS))
  72. return nullptr;
  73. if (!CI.getFrontendOpts().RelocatablePCH)
  74. Sysroot.clear();
  75. return llvm::make_unique<PCHGenerator>(CI.getPreprocessor(), OutputFile,
  76. nullptr, Sysroot, OS);
  77. }
  78. bool GeneratePCHAction::ComputeASTConsumerArguments(CompilerInstance &CI,
  79. StringRef InFile,
  80. std::string &Sysroot,
  81. std::string &OutputFile,
  82. raw_ostream *&OS) {
  83. Sysroot = CI.getHeaderSearchOpts().Sysroot;
  84. if (CI.getFrontendOpts().RelocatablePCH && Sysroot.empty()) {
  85. CI.getDiagnostics().Report(diag::err_relocatable_without_isysroot);
  86. return true;
  87. }
  88. // We use createOutputFile here because this is exposed via libclang, and we
  89. // must disable the RemoveFileOnSignal behavior.
  90. // We use a temporary to avoid race conditions.
  91. OS = CI.createOutputFile(CI.getFrontendOpts().OutputFile, /*Binary=*/true,
  92. /*RemoveFileOnSignal=*/false, InFile,
  93. /*Extension=*/"", /*useTemporary=*/true);
  94. if (!OS)
  95. return true;
  96. OutputFile = CI.getFrontendOpts().OutputFile;
  97. return false;
  98. }
  99. std::unique_ptr<ASTConsumer>
  100. GenerateModuleAction::CreateASTConsumer(CompilerInstance &CI,
  101. StringRef InFile) {
  102. std::string Sysroot;
  103. std::string OutputFile;
  104. raw_ostream *OS = nullptr;
  105. if (ComputeASTConsumerArguments(CI, InFile, Sysroot, OutputFile, OS))
  106. return nullptr;
  107. return llvm::make_unique<PCHGenerator>(CI.getPreprocessor(), OutputFile,
  108. Module, Sysroot, OS);
  109. }
  110. static SmallVectorImpl<char> &
  111. operator+=(SmallVectorImpl<char> &Includes, StringRef RHS) {
  112. Includes.append(RHS.begin(), RHS.end());
  113. return Includes;
  114. }
  115. static std::error_code addHeaderInclude(StringRef HeaderName,
  116. SmallVectorImpl<char> &Includes,
  117. const LangOptions &LangOpts,
  118. bool IsExternC) {
  119. if (IsExternC && LangOpts.CPlusPlus)
  120. Includes += "extern \"C\" {\n";
  121. if (LangOpts.ObjC1)
  122. Includes += "#import \"";
  123. else
  124. Includes += "#include \"";
  125. Includes += HeaderName;
  126. Includes += "\"\n";
  127. if (IsExternC && LangOpts.CPlusPlus)
  128. Includes += "}\n";
  129. return std::error_code();
  130. }
  131. static std::error_code addHeaderInclude(const FileEntry *Header,
  132. SmallVectorImpl<char> &Includes,
  133. const LangOptions &LangOpts,
  134. bool IsExternC) {
  135. // Use an absolute path if we don't have a filename as written in the module
  136. // map file; this ensures that we will identify the right file independent of
  137. // header search paths.
  138. if (llvm::sys::path::is_absolute(Header->getName()))
  139. return addHeaderInclude(Header->getName(), Includes, LangOpts, IsExternC);
  140. SmallString<256> AbsName(Header->getName());
  141. if (std::error_code Err = llvm::sys::fs::make_absolute(AbsName))
  142. return Err;
  143. return addHeaderInclude(AbsName, Includes, LangOpts, IsExternC);
  144. }
  145. /// \brief Collect the set of header includes needed to construct the given
  146. /// module and update the TopHeaders file set of the module.
  147. ///
  148. /// \param Module The module we're collecting includes from.
  149. ///
  150. /// \param Includes Will be augmented with the set of \#includes or \#imports
  151. /// needed to load all of the named headers.
  152. static std::error_code
  153. collectModuleHeaderIncludes(const LangOptions &LangOpts, FileManager &FileMgr,
  154. ModuleMap &ModMap, clang::Module *Module,
  155. SmallVectorImpl<char> &Includes) {
  156. // Don't collect any headers for unavailable modules.
  157. if (!Module->isAvailable())
  158. return std::error_code();
  159. // Add includes for each of these headers.
  160. for (Module::Header &H : Module->Headers[Module::HK_Normal]) {
  161. Module->addTopHeader(H.Entry);
  162. // Use the path as specified in the module map file. We'll look for this
  163. // file relative to the module build directory (the directory containing
  164. // the module map file) so this will find the same file that we found
  165. // while parsing the module map.
  166. if (std::error_code Err = addHeaderInclude(H.NameAsWritten, Includes,
  167. LangOpts, Module->IsExternC))
  168. return Err;
  169. }
  170. // Note that Module->PrivateHeaders will not be a TopHeader.
  171. if (const FileEntry *UmbrellaHeader = Module->getUmbrellaHeader()) {
  172. // FIXME: Track the name as written here.
  173. Module->addTopHeader(UmbrellaHeader);
  174. if (Module->Parent) {
  175. // Include the umbrella header for submodules.
  176. if (std::error_code Err = addHeaderInclude(UmbrellaHeader, Includes,
  177. LangOpts, Module->IsExternC))
  178. return Err;
  179. }
  180. } else if (const DirectoryEntry *UmbrellaDir = Module->getUmbrellaDir()) {
  181. // Add all of the headers we find in this subdirectory.
  182. std::error_code EC;
  183. SmallString<128> DirNative;
  184. llvm::sys::path::native(UmbrellaDir->getName(), DirNative);
  185. for (llvm::sys::fs::recursive_directory_iterator Dir(DirNative, EC),
  186. DirEnd;
  187. Dir != DirEnd && !EC; Dir.increment(EC)) {
  188. // Check whether this entry has an extension typically associated with
  189. // headers.
  190. if (!llvm::StringSwitch<bool>(llvm::sys::path::extension(Dir->path()))
  191. .Cases(".h", ".H", ".hh", ".hpp", true)
  192. .Default(false))
  193. continue;
  194. const FileEntry *Header = FileMgr.getFile(Dir->path());
  195. // FIXME: This shouldn't happen unless there is a file system race. Is
  196. // that worth diagnosing?
  197. if (!Header)
  198. continue;
  199. // If this header is marked 'unavailable' in this module, don't include
  200. // it.
  201. if (ModMap.isHeaderUnavailableInModule(Header, Module))
  202. continue;
  203. // Include this header as part of the umbrella directory.
  204. // FIXME: Track the name as written through to here.
  205. Module->addTopHeader(Header);
  206. if (std::error_code Err =
  207. addHeaderInclude(Header, Includes, LangOpts, Module->IsExternC))
  208. return Err;
  209. }
  210. if (EC)
  211. return EC;
  212. }
  213. // Recurse into submodules.
  214. for (clang::Module::submodule_iterator Sub = Module->submodule_begin(),
  215. SubEnd = Module->submodule_end();
  216. Sub != SubEnd; ++Sub)
  217. if (std::error_code Err = collectModuleHeaderIncludes(
  218. LangOpts, FileMgr, ModMap, *Sub, Includes))
  219. return Err;
  220. return std::error_code();
  221. }
  222. bool GenerateModuleAction::BeginSourceFileAction(CompilerInstance &CI,
  223. StringRef Filename) {
  224. // Find the module map file.
  225. const FileEntry *ModuleMap = CI.getFileManager().getFile(Filename);
  226. if (!ModuleMap) {
  227. CI.getDiagnostics().Report(diag::err_module_map_not_found)
  228. << Filename;
  229. return false;
  230. }
  231. // Parse the module map file.
  232. HeaderSearch &HS = CI.getPreprocessor().getHeaderSearchInfo();
  233. if (HS.loadModuleMapFile(ModuleMap, IsSystem))
  234. return false;
  235. if (CI.getLangOpts().CurrentModule.empty()) {
  236. CI.getDiagnostics().Report(diag::err_missing_module_name);
  237. // FIXME: Eventually, we could consider asking whether there was just
  238. // a single module described in the module map, and use that as a
  239. // default. Then it would be fairly trivial to just "compile" a module
  240. // map with a single module (the common case).
  241. return false;
  242. }
  243. // If we're being run from the command-line, the module build stack will not
  244. // have been filled in yet, so complete it now in order to allow us to detect
  245. // module cycles.
  246. SourceManager &SourceMgr = CI.getSourceManager();
  247. if (SourceMgr.getModuleBuildStack().empty())
  248. SourceMgr.pushModuleBuildStack(CI.getLangOpts().CurrentModule,
  249. FullSourceLoc(SourceLocation(), SourceMgr));
  250. // Dig out the module definition.
  251. Module = HS.lookupModule(CI.getLangOpts().CurrentModule,
  252. /*AllowSearch=*/false);
  253. if (!Module) {
  254. CI.getDiagnostics().Report(diag::err_missing_module)
  255. << CI.getLangOpts().CurrentModule << Filename;
  256. return false;
  257. }
  258. // Check whether we can build this module at all.
  259. clang::Module::Requirement Requirement;
  260. clang::Module::UnresolvedHeaderDirective MissingHeader;
  261. if (!Module->isAvailable(CI.getLangOpts(), CI.getTarget(), Requirement,
  262. MissingHeader)) {
  263. if (MissingHeader.FileNameLoc.isValid()) {
  264. CI.getDiagnostics().Report(MissingHeader.FileNameLoc,
  265. diag::err_module_header_missing)
  266. << MissingHeader.IsUmbrella << MissingHeader.FileName;
  267. } else {
  268. CI.getDiagnostics().Report(diag::err_module_unavailable)
  269. << Module->getFullModuleName()
  270. << Requirement.second << Requirement.first;
  271. }
  272. return false;
  273. }
  274. if (ModuleMapForUniquing && ModuleMapForUniquing != ModuleMap) {
  275. Module->IsInferred = true;
  276. HS.getModuleMap().setInferredModuleAllowedBy(Module, ModuleMapForUniquing);
  277. } else {
  278. ModuleMapForUniquing = ModuleMap;
  279. }
  280. FileManager &FileMgr = CI.getFileManager();
  281. // Collect the set of #includes we need to build the module.
  282. SmallString<256> HeaderContents;
  283. std::error_code Err = std::error_code();
  284. if (const FileEntry *UmbrellaHeader = Module->getUmbrellaHeader())
  285. // FIXME: Track the file name as written.
  286. Err = addHeaderInclude(UmbrellaHeader, HeaderContents, CI.getLangOpts(),
  287. Module->IsExternC);
  288. if (!Err)
  289. Err = collectModuleHeaderIncludes(
  290. CI.getLangOpts(), FileMgr,
  291. CI.getPreprocessor().getHeaderSearchInfo().getModuleMap(), Module,
  292. HeaderContents);
  293. if (Err) {
  294. CI.getDiagnostics().Report(diag::err_module_cannot_create_includes)
  295. << Module->getFullModuleName() << Err.message();
  296. return false;
  297. }
  298. // Inform the preprocessor that includes from within the input buffer should
  299. // be resolved relative to the build directory of the module map file.
  300. CI.getPreprocessor().setMainFileDir(Module->Directory);
  301. std::unique_ptr<llvm::MemoryBuffer> InputBuffer =
  302. llvm::MemoryBuffer::getMemBufferCopy(HeaderContents,
  303. Module::getModuleInputBufferName());
  304. // Ownership of InputBuffer will be transferred to the SourceManager.
  305. setCurrentInput(FrontendInputFile(InputBuffer.release(), getCurrentFileKind(),
  306. Module->IsSystem));
  307. return true;
  308. }
  309. bool GenerateModuleAction::ComputeASTConsumerArguments(CompilerInstance &CI,
  310. StringRef InFile,
  311. std::string &Sysroot,
  312. std::string &OutputFile,
  313. raw_ostream *&OS) {
  314. // If no output file was provided, figure out where this module would go
  315. // in the module cache.
  316. if (CI.getFrontendOpts().OutputFile.empty()) {
  317. HeaderSearch &HS = CI.getPreprocessor().getHeaderSearchInfo();
  318. CI.getFrontendOpts().OutputFile =
  319. HS.getModuleFileName(CI.getLangOpts().CurrentModule,
  320. ModuleMapForUniquing->getName());
  321. }
  322. // We use createOutputFile here because this is exposed via libclang, and we
  323. // must disable the RemoveFileOnSignal behavior.
  324. // We use a temporary to avoid race conditions.
  325. OS = CI.createOutputFile(CI.getFrontendOpts().OutputFile, /*Binary=*/true,
  326. /*RemoveFileOnSignal=*/false, InFile,
  327. /*Extension=*/"", /*useTemporary=*/true,
  328. /*CreateMissingDirectories=*/true);
  329. if (!OS)
  330. return true;
  331. OutputFile = CI.getFrontendOpts().OutputFile;
  332. return false;
  333. }
  334. std::unique_ptr<ASTConsumer>
  335. SyntaxOnlyAction::CreateASTConsumer(CompilerInstance &CI, StringRef InFile) {
  336. return llvm::make_unique<ASTConsumer>();
  337. }
  338. std::unique_ptr<ASTConsumer>
  339. DumpModuleInfoAction::CreateASTConsumer(CompilerInstance &CI,
  340. StringRef InFile) {
  341. return llvm::make_unique<ASTConsumer>();
  342. }
  343. std::unique_ptr<ASTConsumer>
  344. VerifyPCHAction::CreateASTConsumer(CompilerInstance &CI, StringRef InFile) {
  345. return llvm::make_unique<ASTConsumer>();
  346. }
  347. void VerifyPCHAction::ExecuteAction() {
  348. CompilerInstance &CI = getCompilerInstance();
  349. bool Preamble = CI.getPreprocessorOpts().PrecompiledPreambleBytes.first != 0;
  350. const std::string &Sysroot = CI.getHeaderSearchOpts().Sysroot;
  351. std::unique_ptr<ASTReader> Reader(
  352. new ASTReader(CI.getPreprocessor(), CI.getASTContext(),
  353. Sysroot.empty() ? "" : Sysroot.c_str(),
  354. /*DisableValidation*/ false,
  355. /*AllowPCHWithCompilerErrors*/ false,
  356. /*AllowConfigurationMismatch*/ true,
  357. /*ValidateSystemInputs*/ true));
  358. Reader->ReadAST(getCurrentFile(),
  359. Preamble ? serialization::MK_Preamble
  360. : serialization::MK_PCH,
  361. SourceLocation(),
  362. ASTReader::ARR_ConfigurationMismatch);
  363. }
  364. namespace {
  365. /// \brief AST reader listener that dumps module information for a module
  366. /// file.
  367. class DumpModuleInfoListener : public ASTReaderListener {
  368. llvm::raw_ostream &Out;
  369. public:
  370. DumpModuleInfoListener(llvm::raw_ostream &Out) : Out(Out) { }
  371. #define DUMP_BOOLEAN(Value, Text) \
  372. Out.indent(4) << Text << ": " << (Value? "Yes" : "No") << "\n"
  373. bool ReadFullVersionInformation(StringRef FullVersion) override {
  374. Out.indent(2)
  375. << "Generated by "
  376. << (FullVersion == getClangFullRepositoryVersion()? "this"
  377. : "a different")
  378. << " Clang: " << FullVersion << "\n";
  379. return ASTReaderListener::ReadFullVersionInformation(FullVersion);
  380. }
  381. void ReadModuleName(StringRef ModuleName) override {
  382. Out.indent(2) << "Module name: " << ModuleName << "\n";
  383. }
  384. void ReadModuleMapFile(StringRef ModuleMapPath) override {
  385. Out.indent(2) << "Module map file: " << ModuleMapPath << "\n";
  386. }
  387. bool ReadLanguageOptions(const LangOptions &LangOpts, bool Complain,
  388. bool AllowCompatibleDifferences) override {
  389. Out.indent(2) << "Language options:\n";
  390. #define LANGOPT(Name, Bits, Default, Description) \
  391. DUMP_BOOLEAN(LangOpts.Name, Description);
  392. #define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
  393. Out.indent(4) << Description << ": " \
  394. << static_cast<unsigned>(LangOpts.get##Name()) << "\n";
  395. #define VALUE_LANGOPT(Name, Bits, Default, Description) \
  396. Out.indent(4) << Description << ": " << LangOpts.Name << "\n";
  397. #define BENIGN_LANGOPT(Name, Bits, Default, Description)
  398. #define BENIGN_ENUM_LANGOPT(Name, Type, Bits, Default, Description)
  399. #include "clang/Basic/LangOptions.def"
  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. virtual bool
  418. ReadDiagnosticOptions(IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts,
  419. bool Complain) override {
  420. Out.indent(2) << "Diagnostic options:\n";
  421. #define DIAGOPT(Name, Bits, Default) DUMP_BOOLEAN(DiagOpts->Name, #Name);
  422. #define ENUM_DIAGOPT(Name, Type, Bits, Default) \
  423. Out.indent(4) << #Name << ": " << DiagOpts->get##Name() << "\n";
  424. #define VALUE_DIAGOPT(Name, Bits, Default) \
  425. Out.indent(4) << #Name << ": " << DiagOpts->Name << "\n";
  426. #include "clang/Basic/DiagnosticOptions.def"
  427. Out.indent(4) << "Diagnostic flags:\n";
  428. for (const std::string &Warning : DiagOpts->Warnings)
  429. Out.indent(6) << "-W" << Warning << "\n";
  430. for (const std::string &Remark : DiagOpts->Remarks)
  431. Out.indent(6) << "-R" << Remark << "\n";
  432. return false;
  433. }
  434. bool ReadHeaderSearchOptions(const HeaderSearchOptions &HSOpts,
  435. StringRef SpecificModuleCachePath,
  436. bool Complain) override {
  437. Out.indent(2) << "Header search options:\n";
  438. Out.indent(4) << "System root [-isysroot=]: '" << HSOpts.Sysroot << "'\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. #undef DUMP_BOOLEAN
  474. };
  475. }
  476. void DumpModuleInfoAction::ExecuteAction() {
  477. // Set up the output file.
  478. std::unique_ptr<llvm::raw_fd_ostream> OutFile;
  479. StringRef OutputFileName = getCompilerInstance().getFrontendOpts().OutputFile;
  480. if (!OutputFileName.empty() && OutputFileName != "-") {
  481. std::error_code EC;
  482. OutFile.reset(new llvm::raw_fd_ostream(OutputFileName.str(), EC,
  483. llvm::sys::fs::F_Text));
  484. }
  485. llvm::raw_ostream &Out = OutFile.get()? *OutFile.get() : llvm::outs();
  486. Out << "Information for module file '" << getCurrentFile() << "':\n";
  487. DumpModuleInfoListener Listener(Out);
  488. ASTReader::readASTFileControlBlock(getCurrentFile(),
  489. getCompilerInstance().getFileManager(),
  490. Listener);
  491. }
  492. //===----------------------------------------------------------------------===//
  493. // Preprocessor Actions
  494. //===----------------------------------------------------------------------===//
  495. void DumpRawTokensAction::ExecuteAction() {
  496. Preprocessor &PP = getCompilerInstance().getPreprocessor();
  497. SourceManager &SM = PP.getSourceManager();
  498. // Start lexing the specified input file.
  499. const llvm::MemoryBuffer *FromFile = SM.getBuffer(SM.getMainFileID());
  500. Lexer RawLex(SM.getMainFileID(), FromFile, SM, PP.getLangOpts());
  501. RawLex.SetKeepWhitespaceMode(true);
  502. Token RawTok;
  503. RawLex.LexFromRawLexer(RawTok);
  504. while (RawTok.isNot(tok::eof)) {
  505. PP.DumpToken(RawTok, true);
  506. llvm::errs() << "\n";
  507. RawLex.LexFromRawLexer(RawTok);
  508. }
  509. }
  510. void DumpTokensAction::ExecuteAction() {
  511. Preprocessor &PP = getCompilerInstance().getPreprocessor();
  512. // Start preprocessing the specified input file.
  513. Token Tok;
  514. PP.EnterMainSourceFile();
  515. do {
  516. PP.Lex(Tok);
  517. PP.DumpToken(Tok, true);
  518. llvm::errs() << "\n";
  519. } while (Tok.isNot(tok::eof));
  520. }
  521. void GeneratePTHAction::ExecuteAction() {
  522. CompilerInstance &CI = getCompilerInstance();
  523. if (CI.getFrontendOpts().OutputFile.empty() ||
  524. CI.getFrontendOpts().OutputFile == "-") {
  525. // FIXME: Don't fail this way.
  526. // FIXME: Verify that we can actually seek in the given file.
  527. llvm::report_fatal_error("PTH requires a seekable file for output!");
  528. }
  529. llvm::raw_fd_ostream *OS =
  530. CI.createDefaultOutputFile(true, getCurrentFile());
  531. if (!OS) return;
  532. CacheTokens(CI.getPreprocessor(), OS);
  533. }
  534. void PreprocessOnlyAction::ExecuteAction() {
  535. Preprocessor &PP = getCompilerInstance().getPreprocessor();
  536. // Ignore unknown pragmas.
  537. PP.IgnorePragmas();
  538. Token Tok;
  539. // Start parsing the specified input file.
  540. PP.EnterMainSourceFile();
  541. do {
  542. PP.Lex(Tok);
  543. } while (Tok.isNot(tok::eof));
  544. }
  545. void PrintPreprocessedAction::ExecuteAction() {
  546. CompilerInstance &CI = getCompilerInstance();
  547. // Output file may need to be set to 'Binary', to avoid converting Unix style
  548. // line feeds (<LF>) to Microsoft style line feeds (<CR><LF>).
  549. //
  550. // Look to see what type of line endings the file uses. If there's a
  551. // CRLF, then we won't open the file up in binary mode. If there is
  552. // just an LF or CR, then we will open the file up in binary mode.
  553. // In this fashion, the output format should match the input format, unless
  554. // the input format has inconsistent line endings.
  555. //
  556. // This should be a relatively fast operation since most files won't have
  557. // all of their source code on a single line. However, that is still a
  558. // concern, so if we scan for too long, we'll just assume the file should
  559. // be opened in binary mode.
  560. bool BinaryMode = true;
  561. bool InvalidFile = false;
  562. const SourceManager& SM = CI.getSourceManager();
  563. const llvm::MemoryBuffer *Buffer = SM.getBuffer(SM.getMainFileID(),
  564. &InvalidFile);
  565. if (!InvalidFile) {
  566. const char *cur = Buffer->getBufferStart();
  567. const char *end = Buffer->getBufferEnd();
  568. const char *next = (cur != end) ? cur + 1 : end;
  569. // Limit ourselves to only scanning 256 characters into the source
  570. // file. This is mostly a sanity check in case the file has no
  571. // newlines whatsoever.
  572. if (end - cur > 256) end = cur + 256;
  573. while (next < end) {
  574. if (*cur == 0x0D) { // CR
  575. if (*next == 0x0A) // CRLF
  576. BinaryMode = false;
  577. break;
  578. } else if (*cur == 0x0A) // LF
  579. break;
  580. ++cur, ++next;
  581. }
  582. }
  583. raw_ostream *OS = CI.createDefaultOutputFile(BinaryMode, getCurrentFile());
  584. if (!OS) return;
  585. DoPrintPreprocessedInput(CI.getPreprocessor(), OS,
  586. CI.getPreprocessorOutputOpts());
  587. }
  588. void PrintPreambleAction::ExecuteAction() {
  589. switch (getCurrentFileKind()) {
  590. case IK_C:
  591. case IK_CXX:
  592. case IK_ObjC:
  593. case IK_ObjCXX:
  594. case IK_OpenCL:
  595. case IK_CUDA:
  596. break;
  597. case IK_None:
  598. case IK_Asm:
  599. case IK_PreprocessedC:
  600. case IK_PreprocessedCuda:
  601. case IK_PreprocessedCXX:
  602. case IK_PreprocessedObjC:
  603. case IK_PreprocessedObjCXX:
  604. case IK_AST:
  605. case IK_LLVM_IR:
  606. // We can't do anything with these.
  607. return;
  608. }
  609. CompilerInstance &CI = getCompilerInstance();
  610. auto Buffer = CI.getFileManager().getBufferForFile(getCurrentFile());
  611. if (Buffer) {
  612. unsigned Preamble =
  613. Lexer::ComputePreamble((*Buffer)->getBuffer(), CI.getLangOpts()).first;
  614. llvm::outs().write((*Buffer)->getBufferStart(), Preamble);
  615. }
  616. }