FrontendActions.cpp 25 KB

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