FrontendActions.cpp 25 KB

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