FrontendActions.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439
  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/Lex/HeaderSearch.h"
  12. #include "clang/Lex/Pragma.h"
  13. #include "clang/Lex/Preprocessor.h"
  14. #include "clang/Parse/Parser.h"
  15. #include "clang/Basic/FileManager.h"
  16. #include "clang/Frontend/ASTConsumers.h"
  17. #include "clang/Frontend/ASTUnit.h"
  18. #include "clang/Frontend/CompilerInstance.h"
  19. #include "clang/Frontend/FrontendDiagnostic.h"
  20. #include "clang/Frontend/Utils.h"
  21. #include "clang/Serialization/ASTWriter.h"
  22. #include "llvm/ADT/OwningPtr.h"
  23. #include "llvm/Support/MemoryBuffer.h"
  24. #include "llvm/Support/raw_ostream.h"
  25. #include "llvm/Support/system_error.h"
  26. using namespace clang;
  27. //===----------------------------------------------------------------------===//
  28. // Custom Actions
  29. //===----------------------------------------------------------------------===//
  30. ASTConsumer *InitOnlyAction::CreateASTConsumer(CompilerInstance &CI,
  31. StringRef InFile) {
  32. return new ASTConsumer();
  33. }
  34. void InitOnlyAction::ExecuteAction() {
  35. }
  36. //===----------------------------------------------------------------------===//
  37. // AST Consumer Actions
  38. //===----------------------------------------------------------------------===//
  39. ASTConsumer *ASTPrintAction::CreateASTConsumer(CompilerInstance &CI,
  40. StringRef InFile) {
  41. if (raw_ostream *OS = CI.createDefaultOutputFile(false, InFile))
  42. return CreateASTPrinter(OS);
  43. return 0;
  44. }
  45. ASTConsumer *ASTDumpAction::CreateASTConsumer(CompilerInstance &CI,
  46. StringRef InFile) {
  47. return CreateASTDumper();
  48. }
  49. ASTConsumer *ASTDumpXMLAction::CreateASTConsumer(CompilerInstance &CI,
  50. StringRef InFile) {
  51. raw_ostream *OS;
  52. if (CI.getFrontendOpts().OutputFile.empty())
  53. OS = &llvm::outs();
  54. else
  55. OS = CI.createDefaultOutputFile(false, InFile);
  56. if (!OS) return 0;
  57. return CreateASTDumperXML(*OS);
  58. }
  59. ASTConsumer *ASTViewAction::CreateASTConsumer(CompilerInstance &CI,
  60. StringRef InFile) {
  61. return CreateASTViewer();
  62. }
  63. ASTConsumer *DeclContextPrintAction::CreateASTConsumer(CompilerInstance &CI,
  64. StringRef InFile) {
  65. return CreateDeclContextPrinter();
  66. }
  67. ASTConsumer *GeneratePCHAction::CreateASTConsumer(CompilerInstance &CI,
  68. StringRef InFile) {
  69. std::string Sysroot;
  70. std::string OutputFile;
  71. raw_ostream *OS = 0;
  72. if (ComputeASTConsumerArguments(CI, InFile, Sysroot, OutputFile, OS))
  73. return 0;
  74. if (!CI.getFrontendOpts().RelocatablePCH)
  75. Sysroot.clear();
  76. return new PCHGenerator(CI.getPreprocessor(), OutputFile, 0, Sysroot, OS);
  77. }
  78. bool GeneratePCHAction::ComputeASTConsumerArguments(CompilerInstance &CI,
  79. StringRef InFile,
  80. std::string &Sysroot,
  81. std::string &OutputFile,
  82. raw_ostream *&OS) {
  83. Sysroot = CI.getHeaderSearchOpts().Sysroot;
  84. if (CI.getFrontendOpts().RelocatablePCH && Sysroot.empty()) {
  85. CI.getDiagnostics().Report(diag::err_relocatable_without_isysroot);
  86. return true;
  87. }
  88. // We use createOutputFile here because this is exposed via libclang, and we
  89. // must disable the RemoveFileOnSignal behavior.
  90. // We use a temporary to avoid race conditions.
  91. OS = CI.createOutputFile(CI.getFrontendOpts().OutputFile, /*Binary=*/true,
  92. /*RemoveFileOnSignal=*/false, InFile,
  93. /*Extension=*/"", /*useTemporary=*/true);
  94. if (!OS)
  95. return true;
  96. OutputFile = CI.getFrontendOpts().OutputFile;
  97. return false;
  98. }
  99. ASTConsumer *GenerateModuleAction::CreateASTConsumer(CompilerInstance &CI,
  100. StringRef InFile) {
  101. std::string Sysroot;
  102. std::string OutputFile;
  103. raw_ostream *OS = 0;
  104. if (ComputeASTConsumerArguments(CI, InFile, Sysroot, OutputFile, OS))
  105. return 0;
  106. return new PCHGenerator(CI.getPreprocessor(), OutputFile, Module,
  107. Sysroot, OS);
  108. }
  109. /// \brief Collect the set of header includes needed to construct the given
  110. /// module.
  111. ///
  112. /// \param Module The module we're collecting includes from.
  113. /// \param ExplicitOnly Whether we should only add headers from explicit
  114. static void collectModuleHeaderIncludes(const LangOptions &LangOpts,
  115. clang::Module *Module,
  116. bool ExplicitOnly,
  117. llvm::SmallString<256> &Includes) {
  118. if (!ExplicitOnly || Module->IsExplicit) {
  119. // Add includes for each of these headers.
  120. for (unsigned I = 0, N = Module->Headers.size(); I != N; ++I) {
  121. if (LangOpts.ObjC1)
  122. Includes += "#import \"";
  123. else
  124. Includes += "#include \"";
  125. Includes += Module->Headers[I]->getName();
  126. Includes += "\"\n";
  127. }
  128. }
  129. // Recurse into submodules.
  130. for (llvm::StringMap<clang::Module *>::iterator
  131. Sub = Module->SubModules.begin(),
  132. SubEnd = Module->SubModules.end();
  133. Sub != SubEnd; ++Sub) {
  134. collectModuleHeaderIncludes(LangOpts, Sub->getValue(),
  135. ExplicitOnly && !Module->IsExplicit,
  136. Includes);
  137. }
  138. }
  139. bool GenerateModuleAction::BeginSourceFileAction(CompilerInstance &CI,
  140. StringRef Filename) {
  141. // Find the module map file.
  142. const FileEntry *ModuleMap = CI.getFileManager().getFile(Filename);
  143. if (!ModuleMap) {
  144. CI.getDiagnostics().Report(diag::err_module_map_not_found)
  145. << Filename;
  146. return false;
  147. }
  148. // Parse the module map file.
  149. HeaderSearch &HS = CI.getPreprocessor().getHeaderSearchInfo();
  150. if (HS.loadModuleMapFile(ModuleMap))
  151. return false;
  152. if (CI.getLangOpts().CurrentModule.empty()) {
  153. CI.getDiagnostics().Report(diag::err_missing_module_name);
  154. // FIXME: Eventually, we could consider asking whether there was just
  155. // a single module described in the module map, and use that as a
  156. // default. Then it would be fairly trivial to just "compile" a module
  157. // map with a single module (the common case).
  158. return false;
  159. }
  160. // Dig out the module definition.
  161. Module = HS.getModule(CI.getLangOpts().CurrentModule, /*AllowSearch=*/false);
  162. if (!Module) {
  163. CI.getDiagnostics().Report(diag::err_missing_module)
  164. << CI.getLangOpts().CurrentModule << Filename;
  165. return false;
  166. }
  167. // Collect the set of #includes we need to build the module.
  168. llvm::SmallString<256> HeaderContents;
  169. collectModuleHeaderIncludes(CI.getLangOpts(), Module,
  170. Module->UmbrellaHeader != 0, HeaderContents);
  171. if (Module->UmbrellaHeader && HeaderContents.empty()) {
  172. // Simple case: we have an umbrella header and there are no additional
  173. // includes, we can just parse the umbrella header directly.
  174. setCurrentFile(Module->UmbrellaHeader->getName(), getCurrentFileKind());
  175. return true;
  176. }
  177. FileManager &FileMgr = CI.getFileManager();
  178. llvm::SmallString<128> HeaderName;
  179. time_t ModTime;
  180. if (Module->UmbrellaHeader) {
  181. // Read in the umbrella header.
  182. // FIXME: Go through the source manager; the umbrella header may have
  183. // been overridden.
  184. std::string ErrorStr;
  185. llvm::MemoryBuffer *UmbrellaContents
  186. = FileMgr.getBufferForFile(Module->UmbrellaHeader, &ErrorStr);
  187. if (!UmbrellaContents) {
  188. CI.getDiagnostics().Report(diag::err_missing_umbrella_header)
  189. << Module->UmbrellaHeader->getName() << ErrorStr;
  190. return false;
  191. }
  192. // Combine the contents of the umbrella header with the automatically-
  193. // generated includes.
  194. llvm::SmallString<256> OldContents = HeaderContents;
  195. HeaderContents = UmbrellaContents->getBuffer();
  196. HeaderContents += "\n\n";
  197. HeaderContents += "/* Module includes */\n";
  198. HeaderContents += OldContents;
  199. // Pretend that we're parsing the umbrella header.
  200. HeaderName = Module->UmbrellaHeader->getName();
  201. ModTime = Module->UmbrellaHeader->getModificationTime();
  202. delete UmbrellaContents;
  203. } else {
  204. // Pick an innocuous-sounding name for the umbrella header.
  205. HeaderName = Module->Name + ".h";
  206. if (FileMgr.getFile(HeaderName, /*OpenFile=*/false,
  207. /*CacheFailure=*/false)) {
  208. // Try again!
  209. HeaderName = Module->Name + "-module.h";
  210. if (FileMgr.getFile(HeaderName, /*OpenFile=*/false,
  211. /*CacheFailure=*/false)) {
  212. // Pick something ridiculous and go with it.
  213. HeaderName = Module->Name + "-module.hmod";
  214. }
  215. }
  216. ModTime = time(0);
  217. }
  218. // Remap the contents of the header name we're using to our synthesized
  219. // buffer.
  220. const FileEntry *HeaderFile = FileMgr.getVirtualFile(HeaderName,
  221. HeaderContents.size(),
  222. ModTime);
  223. llvm::MemoryBuffer *HeaderContentsBuf
  224. = llvm::MemoryBuffer::getMemBufferCopy(HeaderContents);
  225. CI.getSourceManager().overrideFileContents(HeaderFile, HeaderContentsBuf);
  226. setCurrentFile(HeaderName, getCurrentFileKind());
  227. return true;
  228. }
  229. bool GenerateModuleAction::ComputeASTConsumerArguments(CompilerInstance &CI,
  230. StringRef InFile,
  231. std::string &Sysroot,
  232. std::string &OutputFile,
  233. raw_ostream *&OS) {
  234. // If no output file was provided, figure out where this module would go
  235. // in the module cache.
  236. if (CI.getFrontendOpts().OutputFile.empty()) {
  237. HeaderSearch &HS = CI.getPreprocessor().getHeaderSearchInfo();
  238. llvm::SmallString<256> ModuleFileName(HS.getModuleCachePath());
  239. llvm::sys::path::append(ModuleFileName,
  240. CI.getLangOpts().CurrentModule + ".pcm");
  241. CI.getFrontendOpts().OutputFile = ModuleFileName.str();
  242. }
  243. // We use createOutputFile here because this is exposed via libclang, and we
  244. // must disable the RemoveFileOnSignal behavior.
  245. // We use a temporary to avoid race conditions.
  246. OS = CI.createOutputFile(CI.getFrontendOpts().OutputFile, /*Binary=*/true,
  247. /*RemoveFileOnSignal=*/false, InFile,
  248. /*Extension=*/"", /*useTemporary=*/true);
  249. if (!OS)
  250. return true;
  251. OutputFile = CI.getFrontendOpts().OutputFile;
  252. return false;
  253. }
  254. ASTConsumer *SyntaxOnlyAction::CreateASTConsumer(CompilerInstance &CI,
  255. StringRef InFile) {
  256. return new ASTConsumer();
  257. }
  258. //===----------------------------------------------------------------------===//
  259. // Preprocessor Actions
  260. //===----------------------------------------------------------------------===//
  261. void DumpRawTokensAction::ExecuteAction() {
  262. Preprocessor &PP = getCompilerInstance().getPreprocessor();
  263. SourceManager &SM = PP.getSourceManager();
  264. // Start lexing the specified input file.
  265. const llvm::MemoryBuffer *FromFile = SM.getBuffer(SM.getMainFileID());
  266. Lexer RawLex(SM.getMainFileID(), FromFile, SM, PP.getLangOptions());
  267. RawLex.SetKeepWhitespaceMode(true);
  268. Token RawTok;
  269. RawLex.LexFromRawLexer(RawTok);
  270. while (RawTok.isNot(tok::eof)) {
  271. PP.DumpToken(RawTok, true);
  272. llvm::errs() << "\n";
  273. RawLex.LexFromRawLexer(RawTok);
  274. }
  275. }
  276. void DumpTokensAction::ExecuteAction() {
  277. Preprocessor &PP = getCompilerInstance().getPreprocessor();
  278. // Start preprocessing the specified input file.
  279. Token Tok;
  280. PP.EnterMainSourceFile();
  281. do {
  282. PP.Lex(Tok);
  283. PP.DumpToken(Tok, true);
  284. llvm::errs() << "\n";
  285. } while (Tok.isNot(tok::eof));
  286. }
  287. void GeneratePTHAction::ExecuteAction() {
  288. CompilerInstance &CI = getCompilerInstance();
  289. if (CI.getFrontendOpts().OutputFile.empty() ||
  290. CI.getFrontendOpts().OutputFile == "-") {
  291. // FIXME: Don't fail this way.
  292. // FIXME: Verify that we can actually seek in the given file.
  293. llvm::report_fatal_error("PTH requires a seekable file for output!");
  294. }
  295. llvm::raw_fd_ostream *OS =
  296. CI.createDefaultOutputFile(true, getCurrentFile());
  297. if (!OS) return;
  298. CacheTokens(CI.getPreprocessor(), OS);
  299. }
  300. void PreprocessOnlyAction::ExecuteAction() {
  301. Preprocessor &PP = getCompilerInstance().getPreprocessor();
  302. // Ignore unknown pragmas.
  303. PP.AddPragmaHandler(new EmptyPragmaHandler());
  304. Token Tok;
  305. // Start parsing the specified input file.
  306. PP.EnterMainSourceFile();
  307. do {
  308. PP.Lex(Tok);
  309. } while (Tok.isNot(tok::eof));
  310. }
  311. void PrintPreprocessedAction::ExecuteAction() {
  312. CompilerInstance &CI = getCompilerInstance();
  313. // Output file may need to be set to 'Binary', to avoid converting Unix style
  314. // line feeds (<LF>) to Microsoft style line feeds (<CR><LF>).
  315. //
  316. // Look to see what type of line endings the file uses. If there's a
  317. // CRLF, then we won't open the file up in binary mode. If there is
  318. // just an LF or CR, then we will open the file up in binary mode.
  319. // In this fashion, the output format should match the input format, unless
  320. // the input format has inconsistent line endings.
  321. //
  322. // This should be a relatively fast operation since most files won't have
  323. // all of their source code on a single line. However, that is still a
  324. // concern, so if we scan for too long, we'll just assume the file should
  325. // be opened in binary mode.
  326. bool BinaryMode = true;
  327. bool InvalidFile = false;
  328. const SourceManager& SM = CI.getSourceManager();
  329. const llvm::MemoryBuffer *Buffer = SM.getBuffer(SM.getMainFileID(),
  330. &InvalidFile);
  331. if (!InvalidFile) {
  332. const char *cur = Buffer->getBufferStart();
  333. const char *end = Buffer->getBufferEnd();
  334. const char *next = (cur != end) ? cur + 1 : end;
  335. // Limit ourselves to only scanning 256 characters into the source
  336. // file. This is mostly a sanity check in case the file has no
  337. // newlines whatsoever.
  338. if (end - cur > 256) end = cur + 256;
  339. while (next < end) {
  340. if (*cur == 0x0D) { // CR
  341. if (*next == 0x0A) // CRLF
  342. BinaryMode = false;
  343. break;
  344. } else if (*cur == 0x0A) // LF
  345. break;
  346. ++cur, ++next;
  347. }
  348. }
  349. raw_ostream *OS = CI.createDefaultOutputFile(BinaryMode, getCurrentFile());
  350. if (!OS) return;
  351. DoPrintPreprocessedInput(CI.getPreprocessor(), OS,
  352. CI.getPreprocessorOutputOpts());
  353. }
  354. void PrintPreambleAction::ExecuteAction() {
  355. switch (getCurrentFileKind()) {
  356. case IK_C:
  357. case IK_CXX:
  358. case IK_ObjC:
  359. case IK_ObjCXX:
  360. case IK_OpenCL:
  361. case IK_CUDA:
  362. break;
  363. case IK_None:
  364. case IK_Asm:
  365. case IK_PreprocessedC:
  366. case IK_PreprocessedCXX:
  367. case IK_PreprocessedObjC:
  368. case IK_PreprocessedObjCXX:
  369. case IK_AST:
  370. case IK_LLVM_IR:
  371. // We can't do anything with these.
  372. return;
  373. }
  374. CompilerInstance &CI = getCompilerInstance();
  375. llvm::MemoryBuffer *Buffer
  376. = CI.getFileManager().getBufferForFile(getCurrentFile());
  377. if (Buffer) {
  378. unsigned Preamble = Lexer::ComputePreamble(Buffer, CI.getLangOpts()).first;
  379. llvm::outs().write(Buffer->getBufferStart(), Preamble);
  380. delete Buffer;
  381. }
  382. }