FrontendActions.cpp 25 KB

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