FrontendActions.cpp 18 KB

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