FrontendActions.cpp 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703
  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 =
  71. ComputeASTConsumerArguments(CI, InFile, Sysroot, OutputFile);
  72. if (!OS)
  73. return nullptr;
  74. if (!CI.getFrontendOpts().RelocatablePCH)
  75. Sysroot.clear();
  76. return llvm::make_unique<PCHGenerator>(CI.getPreprocessor(), OutputFile,
  77. nullptr, Sysroot, OS);
  78. }
  79. raw_ostream *GeneratePCHAction::ComputeASTConsumerArguments(
  80. CompilerInstance &CI, StringRef InFile, std::string &Sysroot,
  81. std::string &OutputFile) {
  82. Sysroot = CI.getHeaderSearchOpts().Sysroot;
  83. if (CI.getFrontendOpts().RelocatablePCH && Sysroot.empty()) {
  84. CI.getDiagnostics().Report(diag::err_relocatable_without_isysroot);
  85. return nullptr;
  86. }
  87. // We use createOutputFile here because this is exposed via libclang, and we
  88. // must disable the RemoveFileOnSignal behavior.
  89. // We use a temporary to avoid race conditions.
  90. raw_ostream *OS =
  91. CI.createOutputFile(CI.getFrontendOpts().OutputFile, /*Binary=*/true,
  92. /*RemoveFileOnSignal=*/false, InFile,
  93. /*Extension=*/"", /*useTemporary=*/true);
  94. if (!OS)
  95. return nullptr;
  96. OutputFile = CI.getFrontendOpts().OutputFile;
  97. return OS;
  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 =
  105. ComputeASTConsumerArguments(CI, InFile, Sysroot, OutputFile);
  106. if (!OS)
  107. return nullptr;
  108. return llvm::make_unique<PCHGenerator>(CI.getPreprocessor(), OutputFile,
  109. Module, Sysroot, OS);
  110. }
  111. static SmallVectorImpl<char> &
  112. operator+=(SmallVectorImpl<char> &Includes, StringRef RHS) {
  113. Includes.append(RHS.begin(), RHS.end());
  114. return Includes;
  115. }
  116. static std::error_code addHeaderInclude(StringRef HeaderName,
  117. SmallVectorImpl<char> &Includes,
  118. const LangOptions &LangOpts,
  119. bool IsExternC) {
  120. if (IsExternC && LangOpts.CPlusPlus)
  121. Includes += "extern \"C\" {\n";
  122. if (LangOpts.ObjC1)
  123. Includes += "#import \"";
  124. else
  125. Includes += "#include \"";
  126. Includes += HeaderName;
  127. Includes += "\"\n";
  128. if (IsExternC && LangOpts.CPlusPlus)
  129. Includes += "}\n";
  130. return std::error_code();
  131. }
  132. static std::error_code addHeaderInclude(const FileEntry *Header,
  133. SmallVectorImpl<char> &Includes,
  134. const LangOptions &LangOpts,
  135. bool IsExternC) {
  136. // Use an absolute path if we don't have a filename as written in the module
  137. // map file; this ensures that we will identify the right file independent of
  138. // header search paths.
  139. if (llvm::sys::path::is_absolute(Header->getName()))
  140. return addHeaderInclude(Header->getName(), Includes, LangOpts, IsExternC);
  141. SmallString<256> AbsName(Header->getName());
  142. if (std::error_code Err = llvm::sys::fs::make_absolute(AbsName))
  143. return Err;
  144. return addHeaderInclude(AbsName, Includes, LangOpts, IsExternC);
  145. }
  146. /// \brief Collect the set of header includes needed to construct the given
  147. /// module and update the TopHeaders file set of the module.
  148. ///
  149. /// \param Module The module we're collecting includes from.
  150. ///
  151. /// \param Includes Will be augmented with the set of \#includes or \#imports
  152. /// needed to load all of the named headers.
  153. static std::error_code
  154. collectModuleHeaderIncludes(const LangOptions &LangOpts, FileManager &FileMgr,
  155. ModuleMap &ModMap, clang::Module *Module,
  156. SmallVectorImpl<char> &Includes) {
  157. // Don't collect any headers for unavailable modules.
  158. if (!Module->isAvailable())
  159. return std::error_code();
  160. // Add includes for each of these headers.
  161. for (Module::Header &H : Module->Headers[Module::HK_Normal]) {
  162. Module->addTopHeader(H.Entry);
  163. // Use the path as specified in the module map file. We'll look for this
  164. // file relative to the module build directory (the directory containing
  165. // the module map file) so this will find the same file that we found
  166. // while parsing the module map.
  167. if (std::error_code Err = addHeaderInclude(H.NameAsWritten, Includes,
  168. LangOpts, Module->IsExternC))
  169. return Err;
  170. }
  171. // Note that Module->PrivateHeaders will not be a TopHeader.
  172. if (const FileEntry *UmbrellaHeader = Module->getUmbrellaHeader()) {
  173. // FIXME: Track the name as written here.
  174. Module->addTopHeader(UmbrellaHeader);
  175. if (Module->Parent) {
  176. // Include the umbrella header for submodules.
  177. if (std::error_code Err = addHeaderInclude(UmbrellaHeader, Includes,
  178. LangOpts, Module->IsExternC))
  179. return Err;
  180. }
  181. } else if (const DirectoryEntry *UmbrellaDir = Module->getUmbrellaDir()) {
  182. // Add all of the headers we find in this subdirectory.
  183. std::error_code EC;
  184. SmallString<128> DirNative;
  185. llvm::sys::path::native(UmbrellaDir->getName(), DirNative);
  186. for (llvm::sys::fs::recursive_directory_iterator Dir(DirNative, EC),
  187. DirEnd;
  188. Dir != DirEnd && !EC; Dir.increment(EC)) {
  189. // Check whether this entry has an extension typically associated with
  190. // headers.
  191. if (!llvm::StringSwitch<bool>(llvm::sys::path::extension(Dir->path()))
  192. .Cases(".h", ".H", ".hh", ".hpp", true)
  193. .Default(false))
  194. continue;
  195. const FileEntry *Header = FileMgr.getFile(Dir->path());
  196. // FIXME: This shouldn't happen unless there is a file system race. Is
  197. // that worth diagnosing?
  198. if (!Header)
  199. continue;
  200. // If this header is marked 'unavailable' in this module, don't include
  201. // it.
  202. if (ModMap.isHeaderUnavailableInModule(Header, Module))
  203. continue;
  204. // Include this header as part of the umbrella directory.
  205. // FIXME: Track the name as written through to here.
  206. Module->addTopHeader(Header);
  207. if (std::error_code Err =
  208. addHeaderInclude(Header, Includes, LangOpts, Module->IsExternC))
  209. return Err;
  210. }
  211. if (EC)
  212. return EC;
  213. }
  214. // Recurse into submodules.
  215. for (clang::Module::submodule_iterator Sub = Module->submodule_begin(),
  216. SubEnd = Module->submodule_end();
  217. Sub != SubEnd; ++Sub)
  218. if (std::error_code Err = collectModuleHeaderIncludes(
  219. LangOpts, FileMgr, ModMap, *Sub, Includes))
  220. return Err;
  221. return std::error_code();
  222. }
  223. bool GenerateModuleAction::BeginSourceFileAction(CompilerInstance &CI,
  224. StringRef Filename) {
  225. // Find the module map file.
  226. const FileEntry *ModuleMap = CI.getFileManager().getFile(Filename);
  227. if (!ModuleMap) {
  228. CI.getDiagnostics().Report(diag::err_module_map_not_found)
  229. << Filename;
  230. return false;
  231. }
  232. // Parse the module map file.
  233. HeaderSearch &HS = CI.getPreprocessor().getHeaderSearchInfo();
  234. if (HS.loadModuleMapFile(ModuleMap, IsSystem))
  235. return false;
  236. if (CI.getLangOpts().CurrentModule.empty()) {
  237. CI.getDiagnostics().Report(diag::err_missing_module_name);
  238. // FIXME: Eventually, we could consider asking whether there was just
  239. // a single module described in the module map, and use that as a
  240. // default. Then it would be fairly trivial to just "compile" a module
  241. // map with a single module (the common case).
  242. return false;
  243. }
  244. // If we're being run from the command-line, the module build stack will not
  245. // have been filled in yet, so complete it now in order to allow us to detect
  246. // module cycles.
  247. SourceManager &SourceMgr = CI.getSourceManager();
  248. if (SourceMgr.getModuleBuildStack().empty())
  249. SourceMgr.pushModuleBuildStack(CI.getLangOpts().CurrentModule,
  250. FullSourceLoc(SourceLocation(), SourceMgr));
  251. // Dig out the module definition.
  252. Module = HS.lookupModule(CI.getLangOpts().CurrentModule,
  253. /*AllowSearch=*/false);
  254. if (!Module) {
  255. CI.getDiagnostics().Report(diag::err_missing_module)
  256. << CI.getLangOpts().CurrentModule << Filename;
  257. return false;
  258. }
  259. // Check whether we can build this module at all.
  260. clang::Module::Requirement Requirement;
  261. clang::Module::UnresolvedHeaderDirective MissingHeader;
  262. if (!Module->isAvailable(CI.getLangOpts(), CI.getTarget(), Requirement,
  263. MissingHeader)) {
  264. if (MissingHeader.FileNameLoc.isValid()) {
  265. CI.getDiagnostics().Report(MissingHeader.FileNameLoc,
  266. diag::err_module_header_missing)
  267. << MissingHeader.IsUmbrella << MissingHeader.FileName;
  268. } else {
  269. CI.getDiagnostics().Report(diag::err_module_unavailable)
  270. << Module->getFullModuleName()
  271. << Requirement.second << Requirement.first;
  272. }
  273. return false;
  274. }
  275. if (ModuleMapForUniquing && ModuleMapForUniquing != ModuleMap) {
  276. Module->IsInferred = true;
  277. HS.getModuleMap().setInferredModuleAllowedBy(Module, ModuleMapForUniquing);
  278. } else {
  279. ModuleMapForUniquing = ModuleMap;
  280. }
  281. FileManager &FileMgr = CI.getFileManager();
  282. // Collect the set of #includes we need to build the module.
  283. SmallString<256> HeaderContents;
  284. std::error_code Err = std::error_code();
  285. if (const FileEntry *UmbrellaHeader = Module->getUmbrellaHeader())
  286. // FIXME: Track the file name as written.
  287. Err = addHeaderInclude(UmbrellaHeader, HeaderContents, CI.getLangOpts(),
  288. Module->IsExternC);
  289. if (!Err)
  290. Err = collectModuleHeaderIncludes(
  291. CI.getLangOpts(), FileMgr,
  292. CI.getPreprocessor().getHeaderSearchInfo().getModuleMap(), Module,
  293. HeaderContents);
  294. if (Err) {
  295. CI.getDiagnostics().Report(diag::err_module_cannot_create_includes)
  296. << Module->getFullModuleName() << Err.message();
  297. return false;
  298. }
  299. // Inform the preprocessor that includes from within the input buffer should
  300. // be resolved relative to the build directory of the module map file.
  301. CI.getPreprocessor().setMainFileDir(Module->Directory);
  302. std::unique_ptr<llvm::MemoryBuffer> InputBuffer =
  303. llvm::MemoryBuffer::getMemBufferCopy(HeaderContents,
  304. Module::getModuleInputBufferName());
  305. // Ownership of InputBuffer will be transferred to the SourceManager.
  306. setCurrentInput(FrontendInputFile(InputBuffer.release(), getCurrentFileKind(),
  307. Module->IsSystem));
  308. return true;
  309. }
  310. raw_ostream *GenerateModuleAction::ComputeASTConsumerArguments(
  311. CompilerInstance &CI, StringRef InFile, std::string &Sysroot,
  312. std::string &OutputFile) {
  313. // If no output file was provided, figure out where this module would go
  314. // in the module cache.
  315. if (CI.getFrontendOpts().OutputFile.empty()) {
  316. HeaderSearch &HS = CI.getPreprocessor().getHeaderSearchInfo();
  317. CI.getFrontendOpts().OutputFile =
  318. HS.getModuleFileName(CI.getLangOpts().CurrentModule,
  319. ModuleMapForUniquing->getName());
  320. }
  321. // We use createOutputFile here because this is exposed via libclang, and we
  322. // must disable the RemoveFileOnSignal behavior.
  323. // We use a temporary to avoid race conditions.
  324. raw_ostream *OS =
  325. CI.createOutputFile(CI.getFrontendOpts().OutputFile, /*Binary=*/true,
  326. /*RemoveFileOnSignal=*/false, InFile,
  327. /*Extension=*/"", /*useTemporary=*/true,
  328. /*CreateMissingDirectories=*/true);
  329. if (!OS)
  330. return nullptr;
  331. OutputFile = CI.getFrontendOpts().OutputFile;
  332. return OS;
  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. 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) << "Module Cache: '" << SpecificModuleCachePath << "'\n";
  439. DUMP_BOOLEAN(HSOpts.UseBuiltinIncludes,
  440. "Use builtin include directories [-nobuiltininc]");
  441. DUMP_BOOLEAN(HSOpts.UseStandardSystemIncludes,
  442. "Use standard system include directories [-nostdinc]");
  443. DUMP_BOOLEAN(HSOpts.UseStandardCXXIncludes,
  444. "Use standard C++ include directories [-nostdinc++]");
  445. DUMP_BOOLEAN(HSOpts.UseLibcxx,
  446. "Use libc++ (rather than libstdc++) [-stdlib=]");
  447. return false;
  448. }
  449. bool ReadPreprocessorOptions(const PreprocessorOptions &PPOpts,
  450. bool Complain,
  451. std::string &SuggestedPredefines) override {
  452. Out.indent(2) << "Preprocessor options:\n";
  453. DUMP_BOOLEAN(PPOpts.UsePredefines,
  454. "Uses compiler/target-specific predefines [-undef]");
  455. DUMP_BOOLEAN(PPOpts.DetailedRecord,
  456. "Uses detailed preprocessing record (for indexing)");
  457. if (!PPOpts.Macros.empty()) {
  458. Out.indent(4) << "Predefined macros:\n";
  459. }
  460. for (std::vector<std::pair<std::string, bool/*isUndef*/> >::const_iterator
  461. I = PPOpts.Macros.begin(), IEnd = PPOpts.Macros.end();
  462. I != IEnd; ++I) {
  463. Out.indent(6);
  464. if (I->second)
  465. Out << "-U";
  466. else
  467. Out << "-D";
  468. Out << I->first << "\n";
  469. }
  470. return false;
  471. }
  472. #undef DUMP_BOOLEAN
  473. };
  474. }
  475. void DumpModuleInfoAction::ExecuteAction() {
  476. // Set up the output file.
  477. std::unique_ptr<llvm::raw_fd_ostream> OutFile;
  478. StringRef OutputFileName = getCompilerInstance().getFrontendOpts().OutputFile;
  479. if (!OutputFileName.empty() && OutputFileName != "-") {
  480. std::error_code EC;
  481. OutFile.reset(new llvm::raw_fd_ostream(OutputFileName.str(), EC,
  482. llvm::sys::fs::F_Text));
  483. }
  484. llvm::raw_ostream &Out = OutFile.get()? *OutFile.get() : llvm::outs();
  485. Out << "Information for module file '" << getCurrentFile() << "':\n";
  486. DumpModuleInfoListener Listener(Out);
  487. ASTReader::readASTFileControlBlock(getCurrentFile(),
  488. getCompilerInstance().getFileManager(),
  489. Listener);
  490. }
  491. //===----------------------------------------------------------------------===//
  492. // Preprocessor Actions
  493. //===----------------------------------------------------------------------===//
  494. void DumpRawTokensAction::ExecuteAction() {
  495. Preprocessor &PP = getCompilerInstance().getPreprocessor();
  496. SourceManager &SM = PP.getSourceManager();
  497. // Start lexing the specified input file.
  498. const llvm::MemoryBuffer *FromFile = SM.getBuffer(SM.getMainFileID());
  499. Lexer RawLex(SM.getMainFileID(), FromFile, SM, PP.getLangOpts());
  500. RawLex.SetKeepWhitespaceMode(true);
  501. Token RawTok;
  502. RawLex.LexFromRawLexer(RawTok);
  503. while (RawTok.isNot(tok::eof)) {
  504. PP.DumpToken(RawTok, true);
  505. llvm::errs() << "\n";
  506. RawLex.LexFromRawLexer(RawTok);
  507. }
  508. }
  509. void DumpTokensAction::ExecuteAction() {
  510. Preprocessor &PP = getCompilerInstance().getPreprocessor();
  511. // Start preprocessing the specified input file.
  512. Token Tok;
  513. PP.EnterMainSourceFile();
  514. do {
  515. PP.Lex(Tok);
  516. PP.DumpToken(Tok, true);
  517. llvm::errs() << "\n";
  518. } while (Tok.isNot(tok::eof));
  519. }
  520. void GeneratePTHAction::ExecuteAction() {
  521. CompilerInstance &CI = getCompilerInstance();
  522. raw_pwrite_stream *OS = CI.createDefaultOutputFile(true, getCurrentFile());
  523. if (!OS)
  524. return;
  525. CacheTokens(CI.getPreprocessor(), OS);
  526. }
  527. void PreprocessOnlyAction::ExecuteAction() {
  528. Preprocessor &PP = getCompilerInstance().getPreprocessor();
  529. // Ignore unknown pragmas.
  530. PP.IgnorePragmas();
  531. Token Tok;
  532. // Start parsing the specified input file.
  533. PP.EnterMainSourceFile();
  534. do {
  535. PP.Lex(Tok);
  536. } while (Tok.isNot(tok::eof));
  537. }
  538. void PrintPreprocessedAction::ExecuteAction() {
  539. CompilerInstance &CI = getCompilerInstance();
  540. // Output file may need to be set to 'Binary', to avoid converting Unix style
  541. // line feeds (<LF>) to Microsoft style line feeds (<CR><LF>).
  542. //
  543. // Look to see what type of line endings the file uses. If there's a
  544. // CRLF, then we won't open the file up in binary mode. If there is
  545. // just an LF or CR, then we will open the file up in binary mode.
  546. // In this fashion, the output format should match the input format, unless
  547. // the input format has inconsistent line endings.
  548. //
  549. // This should be a relatively fast operation since most files won't have
  550. // all of their source code on a single line. However, that is still a
  551. // concern, so if we scan for too long, we'll just assume the file should
  552. // be opened in binary mode.
  553. bool BinaryMode = true;
  554. bool InvalidFile = false;
  555. const SourceManager& SM = CI.getSourceManager();
  556. const llvm::MemoryBuffer *Buffer = SM.getBuffer(SM.getMainFileID(),
  557. &InvalidFile);
  558. if (!InvalidFile) {
  559. const char *cur = Buffer->getBufferStart();
  560. const char *end = Buffer->getBufferEnd();
  561. const char *next = (cur != end) ? cur + 1 : end;
  562. // Limit ourselves to only scanning 256 characters into the source
  563. // file. This is mostly a sanity check in case the file has no
  564. // newlines whatsoever.
  565. if (end - cur > 256) end = cur + 256;
  566. while (next < end) {
  567. if (*cur == 0x0D) { // CR
  568. if (*next == 0x0A) // CRLF
  569. BinaryMode = false;
  570. break;
  571. } else if (*cur == 0x0A) // LF
  572. break;
  573. ++cur, ++next;
  574. }
  575. }
  576. raw_ostream *OS = CI.createDefaultOutputFile(BinaryMode, getCurrentFile());
  577. if (!OS) return;
  578. DoPrintPreprocessedInput(CI.getPreprocessor(), OS,
  579. CI.getPreprocessorOutputOpts());
  580. }
  581. void PrintPreambleAction::ExecuteAction() {
  582. switch (getCurrentFileKind()) {
  583. case IK_C:
  584. case IK_CXX:
  585. case IK_ObjC:
  586. case IK_ObjCXX:
  587. case IK_OpenCL:
  588. case IK_CUDA:
  589. break;
  590. case IK_None:
  591. case IK_Asm:
  592. case IK_PreprocessedC:
  593. case IK_PreprocessedCuda:
  594. case IK_PreprocessedCXX:
  595. case IK_PreprocessedObjC:
  596. case IK_PreprocessedObjCXX:
  597. case IK_AST:
  598. case IK_LLVM_IR:
  599. // We can't do anything with these.
  600. return;
  601. }
  602. CompilerInstance &CI = getCompilerInstance();
  603. auto Buffer = CI.getFileManager().getBufferForFile(getCurrentFile());
  604. if (Buffer) {
  605. unsigned Preamble =
  606. Lexer::ComputePreamble((*Buffer)->getBuffer(), CI.getLangOpts()).first;
  607. llvm::outs().write((*Buffer)->getBufferStart(), Preamble);
  608. }
  609. }