CompilerInstance.cpp 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775
  1. //===--- CompilerInstance.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/CompilerInstance.h"
  10. #include "clang/Sema/Sema.h"
  11. #include "clang/AST/ASTConsumer.h"
  12. #include "clang/AST/ASTContext.h"
  13. #include "clang/Basic/Diagnostic.h"
  14. #include "clang/Basic/FileManager.h"
  15. #include "clang/Basic/SourceManager.h"
  16. #include "clang/Basic/TargetInfo.h"
  17. #include "clang/Basic/Version.h"
  18. #include "clang/Lex/HeaderSearch.h"
  19. #include "clang/Lex/Preprocessor.h"
  20. #include "clang/Lex/PTHManager.h"
  21. #include "clang/Frontend/ChainedDiagnosticClient.h"
  22. #include "clang/Frontend/FrontendAction.h"
  23. #include "clang/Frontend/FrontendActions.h"
  24. #include "clang/Frontend/FrontendDiagnostic.h"
  25. #include "clang/Frontend/LogDiagnosticPrinter.h"
  26. #include "clang/Frontend/TextDiagnosticPrinter.h"
  27. #include "clang/Frontend/VerifyDiagnosticsClient.h"
  28. #include "clang/Frontend/Utils.h"
  29. #include "clang/Serialization/ASTReader.h"
  30. #include "clang/Sema/CodeCompleteConsumer.h"
  31. #include "llvm/Support/FileSystem.h"
  32. #include "llvm/Support/MemoryBuffer.h"
  33. #include "llvm/Support/raw_ostream.h"
  34. #include "llvm/ADT/Statistic.h"
  35. #include "llvm/Support/Timer.h"
  36. #include "llvm/Support/Host.h"
  37. #include "llvm/Support/Path.h"
  38. #include "llvm/Support/Program.h"
  39. #include "llvm/Support/Signals.h"
  40. #include "llvm/Support/system_error.h"
  41. #include "llvm/Config/config.h"
  42. using namespace clang;
  43. CompilerInstance::CompilerInstance()
  44. : Invocation(new CompilerInvocation()), ModuleManager(0) {
  45. }
  46. CompilerInstance::~CompilerInstance() {
  47. }
  48. void CompilerInstance::setInvocation(CompilerInvocation *Value) {
  49. Invocation = Value;
  50. }
  51. void CompilerInstance::setDiagnostics(Diagnostic *Value) {
  52. Diagnostics = Value;
  53. }
  54. void CompilerInstance::setTarget(TargetInfo *Value) {
  55. Target = Value;
  56. }
  57. void CompilerInstance::setFileManager(FileManager *Value) {
  58. FileMgr = Value;
  59. }
  60. void CompilerInstance::setSourceManager(SourceManager *Value) {
  61. SourceMgr = Value;
  62. }
  63. void CompilerInstance::setPreprocessor(Preprocessor *Value) { PP = Value; }
  64. void CompilerInstance::setASTContext(ASTContext *Value) { Context = Value; }
  65. void CompilerInstance::setSema(Sema *S) {
  66. TheSema.reset(S);
  67. }
  68. void CompilerInstance::setASTConsumer(ASTConsumer *Value) {
  69. Consumer.reset(Value);
  70. }
  71. void CompilerInstance::setCodeCompletionConsumer(CodeCompleteConsumer *Value) {
  72. CompletionConsumer.reset(Value);
  73. }
  74. // Diagnostics
  75. static void SetUpBuildDumpLog(const DiagnosticOptions &DiagOpts,
  76. unsigned argc, const char* const *argv,
  77. Diagnostic &Diags) {
  78. std::string ErrorInfo;
  79. llvm::OwningPtr<raw_ostream> OS(
  80. new llvm::raw_fd_ostream(DiagOpts.DumpBuildInformation.c_str(), ErrorInfo));
  81. if (!ErrorInfo.empty()) {
  82. Diags.Report(diag::err_fe_unable_to_open_logfile)
  83. << DiagOpts.DumpBuildInformation << ErrorInfo;
  84. return;
  85. }
  86. (*OS) << "clang -cc1 command line arguments: ";
  87. for (unsigned i = 0; i != argc; ++i)
  88. (*OS) << argv[i] << ' ';
  89. (*OS) << '\n';
  90. // Chain in a diagnostic client which will log the diagnostics.
  91. DiagnosticClient *Logger =
  92. new TextDiagnosticPrinter(*OS.take(), DiagOpts, /*OwnsOutputStream=*/true);
  93. Diags.setClient(new ChainedDiagnosticClient(Diags.takeClient(), Logger));
  94. }
  95. static void SetUpDiagnosticLog(const DiagnosticOptions &DiagOpts,
  96. const CodeGenOptions *CodeGenOpts,
  97. Diagnostic &Diags) {
  98. std::string ErrorInfo;
  99. bool OwnsStream = false;
  100. raw_ostream *OS = &llvm::errs();
  101. if (DiagOpts.DiagnosticLogFile != "-") {
  102. // Create the output stream.
  103. llvm::raw_fd_ostream *FileOS(
  104. new llvm::raw_fd_ostream(DiagOpts.DiagnosticLogFile.c_str(),
  105. ErrorInfo, llvm::raw_fd_ostream::F_Append));
  106. if (!ErrorInfo.empty()) {
  107. Diags.Report(diag::warn_fe_cc_log_diagnostics_failure)
  108. << DiagOpts.DumpBuildInformation << ErrorInfo;
  109. } else {
  110. FileOS->SetUnbuffered();
  111. FileOS->SetUseAtomicWrites(true);
  112. OS = FileOS;
  113. OwnsStream = true;
  114. }
  115. }
  116. // Chain in the diagnostic client which will log the diagnostics.
  117. LogDiagnosticPrinter *Logger = new LogDiagnosticPrinter(*OS, DiagOpts,
  118. OwnsStream);
  119. if (CodeGenOpts)
  120. Logger->setDwarfDebugFlags(CodeGenOpts->DwarfDebugFlags);
  121. Diags.setClient(new ChainedDiagnosticClient(Diags.takeClient(), Logger));
  122. }
  123. void CompilerInstance::createDiagnostics(int Argc, const char* const *Argv,
  124. DiagnosticClient *Client,
  125. bool ShouldOwnClient) {
  126. Diagnostics = createDiagnostics(getDiagnosticOpts(), Argc, Argv, Client,
  127. ShouldOwnClient, &getCodeGenOpts());
  128. }
  129. llvm::IntrusiveRefCntPtr<Diagnostic>
  130. CompilerInstance::createDiagnostics(const DiagnosticOptions &Opts,
  131. int Argc, const char* const *Argv,
  132. DiagnosticClient *Client,
  133. bool ShouldOwnClient,
  134. const CodeGenOptions *CodeGenOpts) {
  135. llvm::IntrusiveRefCntPtr<DiagnosticIDs> DiagID(new DiagnosticIDs());
  136. llvm::IntrusiveRefCntPtr<Diagnostic> Diags(new Diagnostic(DiagID));
  137. // Create the diagnostic client for reporting errors or for
  138. // implementing -verify.
  139. if (Client)
  140. Diags->setClient(Client, ShouldOwnClient);
  141. else
  142. Diags->setClient(new TextDiagnosticPrinter(llvm::errs(), Opts));
  143. // Chain in -verify checker, if requested.
  144. if (Opts.VerifyDiagnostics)
  145. Diags->setClient(new VerifyDiagnosticsClient(*Diags));
  146. // Chain in -diagnostic-log-file dumper, if requested.
  147. if (!Opts.DiagnosticLogFile.empty())
  148. SetUpDiagnosticLog(Opts, CodeGenOpts, *Diags);
  149. if (!Opts.DumpBuildInformation.empty())
  150. SetUpBuildDumpLog(Opts, Argc, Argv, *Diags);
  151. // Configure our handling of diagnostics.
  152. ProcessWarningOptions(*Diags, Opts);
  153. return Diags;
  154. }
  155. // File Manager
  156. void CompilerInstance::createFileManager() {
  157. FileMgr = new FileManager(getFileSystemOpts());
  158. }
  159. // Source Manager
  160. void CompilerInstance::createSourceManager(FileManager &FileMgr) {
  161. SourceMgr = new SourceManager(getDiagnostics(), FileMgr);
  162. }
  163. // Preprocessor
  164. void CompilerInstance::createPreprocessor() {
  165. const PreprocessorOptions &PPOpts = getPreprocessorOpts();
  166. // Create a PTH manager if we are using some form of a token cache.
  167. PTHManager *PTHMgr = 0;
  168. if (!PPOpts.TokenCache.empty())
  169. PTHMgr = PTHManager::Create(PPOpts.TokenCache, getDiagnostics());
  170. // Create the Preprocessor.
  171. HeaderSearch *HeaderInfo = new HeaderSearch(getFileManager());
  172. PP = new Preprocessor(getDiagnostics(), getLangOpts(), &getTarget(),
  173. getSourceManager(), *HeaderInfo, *this, PTHMgr,
  174. /*OwnsHeaderSearch=*/true);
  175. // Note that this is different then passing PTHMgr to Preprocessor's ctor.
  176. // That argument is used as the IdentifierInfoLookup argument to
  177. // IdentifierTable's ctor.
  178. if (PTHMgr) {
  179. PTHMgr->setPreprocessor(&*PP);
  180. PP->setPTHManager(PTHMgr);
  181. }
  182. if (PPOpts.DetailedRecord)
  183. PP->createPreprocessingRecord(
  184. PPOpts.DetailedRecordIncludesNestedMacroExpansions);
  185. InitializePreprocessor(*PP, PPOpts, getHeaderSearchOpts(), getFrontendOpts());
  186. // Set up the module path, including the hash for the
  187. // module-creation options.
  188. llvm::SmallString<256> SpecificModuleCache(
  189. getHeaderSearchOpts().ModuleCachePath);
  190. if (!getHeaderSearchOpts().DisableModuleHash)
  191. llvm::sys::path::append(SpecificModuleCache,
  192. getInvocation().getModuleHash());
  193. PP->getHeaderSearchInfo().setModuleCachePath(SpecificModuleCache);
  194. // Handle generating dependencies, if requested.
  195. const DependencyOutputOptions &DepOpts = getDependencyOutputOpts();
  196. if (!DepOpts.OutputFile.empty())
  197. AttachDependencyFileGen(*PP, DepOpts);
  198. // Handle generating header include information, if requested.
  199. if (DepOpts.ShowHeaderIncludes)
  200. AttachHeaderIncludeGen(*PP);
  201. if (!DepOpts.HeaderIncludeOutputFile.empty()) {
  202. StringRef OutputPath = DepOpts.HeaderIncludeOutputFile;
  203. if (OutputPath == "-")
  204. OutputPath = "";
  205. AttachHeaderIncludeGen(*PP, /*ShowAllHeaders=*/true, OutputPath,
  206. /*ShowDepth=*/false);
  207. }
  208. }
  209. // ASTContext
  210. void CompilerInstance::createASTContext() {
  211. Preprocessor &PP = getPreprocessor();
  212. Context = new ASTContext(getLangOpts(), PP.getSourceManager(),
  213. &getTarget(), PP.getIdentifierTable(),
  214. PP.getSelectorTable(), PP.getBuiltinInfo(),
  215. /*size_reserve=*/ 0);
  216. }
  217. // ExternalASTSource
  218. void CompilerInstance::createPCHExternalASTSource(StringRef Path,
  219. bool DisablePCHValidation,
  220. bool DisableStatCache,
  221. void *DeserializationListener){
  222. llvm::OwningPtr<ExternalASTSource> Source;
  223. bool Preamble = getPreprocessorOpts().PrecompiledPreambleBytes.first != 0;
  224. Source.reset(createPCHExternalASTSource(Path, getHeaderSearchOpts().Sysroot,
  225. DisablePCHValidation,
  226. DisableStatCache,
  227. getPreprocessor(), getASTContext(),
  228. DeserializationListener,
  229. Preamble));
  230. ModuleManager = static_cast<ASTReader*>(Source.get());
  231. getASTContext().setExternalSource(Source);
  232. }
  233. ExternalASTSource *
  234. CompilerInstance::createPCHExternalASTSource(StringRef Path,
  235. const std::string &Sysroot,
  236. bool DisablePCHValidation,
  237. bool DisableStatCache,
  238. Preprocessor &PP,
  239. ASTContext &Context,
  240. void *DeserializationListener,
  241. bool Preamble) {
  242. llvm::OwningPtr<ASTReader> Reader;
  243. Reader.reset(new ASTReader(PP, Context,
  244. Sysroot.empty() ? "" : Sysroot.c_str(),
  245. DisablePCHValidation, DisableStatCache));
  246. Reader->setDeserializationListener(
  247. static_cast<ASTDeserializationListener *>(DeserializationListener));
  248. switch (Reader->ReadAST(Path,
  249. Preamble ? serialization::MK_Preamble
  250. : serialization::MK_PCH)) {
  251. case ASTReader::Success:
  252. // Set the predefines buffer as suggested by the PCH reader. Typically, the
  253. // predefines buffer will be empty.
  254. PP.setPredefines(Reader->getSuggestedPredefines());
  255. return Reader.take();
  256. case ASTReader::Failure:
  257. // Unrecoverable failure: don't even try to process the input file.
  258. break;
  259. case ASTReader::IgnorePCH:
  260. // No suitable PCH file could be found. Return an error.
  261. break;
  262. }
  263. return 0;
  264. }
  265. // Code Completion
  266. static bool EnableCodeCompletion(Preprocessor &PP,
  267. const std::string &Filename,
  268. unsigned Line,
  269. unsigned Column) {
  270. // Tell the source manager to chop off the given file at a specific
  271. // line and column.
  272. const FileEntry *Entry = PP.getFileManager().getFile(Filename);
  273. if (!Entry) {
  274. PP.getDiagnostics().Report(diag::err_fe_invalid_code_complete_file)
  275. << Filename;
  276. return true;
  277. }
  278. // Truncate the named file at the given line/column.
  279. PP.SetCodeCompletionPoint(Entry, Line, Column);
  280. return false;
  281. }
  282. void CompilerInstance::createCodeCompletionConsumer() {
  283. const ParsedSourceLocation &Loc = getFrontendOpts().CodeCompletionAt;
  284. if (!CompletionConsumer) {
  285. CompletionConsumer.reset(
  286. createCodeCompletionConsumer(getPreprocessor(),
  287. Loc.FileName, Loc.Line, Loc.Column,
  288. getFrontendOpts().ShowMacrosInCodeCompletion,
  289. getFrontendOpts().ShowCodePatternsInCodeCompletion,
  290. getFrontendOpts().ShowGlobalSymbolsInCodeCompletion,
  291. llvm::outs()));
  292. if (!CompletionConsumer)
  293. return;
  294. } else if (EnableCodeCompletion(getPreprocessor(), Loc.FileName,
  295. Loc.Line, Loc.Column)) {
  296. CompletionConsumer.reset();
  297. return;
  298. }
  299. if (CompletionConsumer->isOutputBinary() &&
  300. llvm::sys::Program::ChangeStdoutToBinary()) {
  301. getPreprocessor().getDiagnostics().Report(diag::err_fe_stdout_binary);
  302. CompletionConsumer.reset();
  303. }
  304. }
  305. void CompilerInstance::createFrontendTimer() {
  306. FrontendTimer.reset(new llvm::Timer("Clang front-end timer"));
  307. }
  308. CodeCompleteConsumer *
  309. CompilerInstance::createCodeCompletionConsumer(Preprocessor &PP,
  310. const std::string &Filename,
  311. unsigned Line,
  312. unsigned Column,
  313. bool ShowMacros,
  314. bool ShowCodePatterns,
  315. bool ShowGlobals,
  316. raw_ostream &OS) {
  317. if (EnableCodeCompletion(PP, Filename, Line, Column))
  318. return 0;
  319. // Set up the creation routine for code-completion.
  320. return new PrintingCodeCompleteConsumer(ShowMacros, ShowCodePatterns,
  321. ShowGlobals, OS);
  322. }
  323. void CompilerInstance::createSema(TranslationUnitKind TUKind,
  324. CodeCompleteConsumer *CompletionConsumer) {
  325. TheSema.reset(new Sema(getPreprocessor(), getASTContext(), getASTConsumer(),
  326. TUKind, CompletionConsumer));
  327. }
  328. // Output Files
  329. void CompilerInstance::addOutputFile(const OutputFile &OutFile) {
  330. assert(OutFile.OS && "Attempt to add empty stream to output list!");
  331. OutputFiles.push_back(OutFile);
  332. }
  333. void CompilerInstance::clearOutputFiles(bool EraseFiles) {
  334. for (std::list<OutputFile>::iterator
  335. it = OutputFiles.begin(), ie = OutputFiles.end(); it != ie; ++it) {
  336. delete it->OS;
  337. if (!it->TempFilename.empty()) {
  338. if (EraseFiles) {
  339. bool existed;
  340. llvm::sys::fs::remove(it->TempFilename, existed);
  341. } else {
  342. llvm::SmallString<128> NewOutFile(it->Filename);
  343. // If '-working-directory' was passed, the output filename should be
  344. // relative to that.
  345. FileMgr->FixupRelativePath(NewOutFile);
  346. if (llvm::error_code ec = llvm::sys::fs::rename(it->TempFilename,
  347. NewOutFile.str())) {
  348. getDiagnostics().Report(diag::err_fe_unable_to_rename_temp)
  349. << it->TempFilename << it->Filename << ec.message();
  350. bool existed;
  351. llvm::sys::fs::remove(it->TempFilename, existed);
  352. }
  353. }
  354. } else if (!it->Filename.empty() && EraseFiles)
  355. llvm::sys::Path(it->Filename).eraseFromDisk();
  356. }
  357. OutputFiles.clear();
  358. }
  359. llvm::raw_fd_ostream *
  360. CompilerInstance::createDefaultOutputFile(bool Binary,
  361. StringRef InFile,
  362. StringRef Extension) {
  363. return createOutputFile(getFrontendOpts().OutputFile, Binary,
  364. /*RemoveFileOnSignal=*/true, InFile, Extension);
  365. }
  366. llvm::raw_fd_ostream *
  367. CompilerInstance::createOutputFile(StringRef OutputPath,
  368. bool Binary, bool RemoveFileOnSignal,
  369. StringRef InFile,
  370. StringRef Extension,
  371. bool UseTemporary) {
  372. std::string Error, OutputPathName, TempPathName;
  373. llvm::raw_fd_ostream *OS = createOutputFile(OutputPath, Error, Binary,
  374. RemoveFileOnSignal,
  375. InFile, Extension,
  376. UseTemporary,
  377. &OutputPathName,
  378. &TempPathName);
  379. if (!OS) {
  380. getDiagnostics().Report(diag::err_fe_unable_to_open_output)
  381. << OutputPath << Error;
  382. return 0;
  383. }
  384. // Add the output file -- but don't try to remove "-", since this means we are
  385. // using stdin.
  386. addOutputFile(OutputFile((OutputPathName != "-") ? OutputPathName : "",
  387. TempPathName, OS));
  388. return OS;
  389. }
  390. llvm::raw_fd_ostream *
  391. CompilerInstance::createOutputFile(StringRef OutputPath,
  392. std::string &Error,
  393. bool Binary,
  394. bool RemoveFileOnSignal,
  395. StringRef InFile,
  396. StringRef Extension,
  397. bool UseTemporary,
  398. std::string *ResultPathName,
  399. std::string *TempPathName) {
  400. std::string OutFile, TempFile;
  401. if (!OutputPath.empty()) {
  402. OutFile = OutputPath;
  403. } else if (InFile == "-") {
  404. OutFile = "-";
  405. } else if (!Extension.empty()) {
  406. llvm::sys::Path Path(InFile);
  407. Path.eraseSuffix();
  408. Path.appendSuffix(Extension);
  409. OutFile = Path.str();
  410. } else {
  411. OutFile = "-";
  412. }
  413. llvm::OwningPtr<llvm::raw_fd_ostream> OS;
  414. std::string OSFile;
  415. if (UseTemporary && OutFile != "-") {
  416. llvm::sys::Path OutPath(OutFile);
  417. // Only create the temporary if we can actually write to OutPath, otherwise
  418. // we want to fail early.
  419. bool Exists;
  420. if ((llvm::sys::fs::exists(OutPath.str(), Exists) || !Exists) ||
  421. (OutPath.isRegularFile() && OutPath.canWrite())) {
  422. // Create a temporary file.
  423. llvm::SmallString<128> TempPath;
  424. TempPath = OutFile;
  425. TempPath += "-%%%%%%%%";
  426. int fd;
  427. if (llvm::sys::fs::unique_file(TempPath.str(), fd, TempPath,
  428. /*makeAbsolute=*/false) == llvm::errc::success) {
  429. OS.reset(new llvm::raw_fd_ostream(fd, /*shouldClose=*/true));
  430. OSFile = TempFile = TempPath.str();
  431. }
  432. }
  433. }
  434. if (!OS) {
  435. OSFile = OutFile;
  436. OS.reset(
  437. new llvm::raw_fd_ostream(OSFile.c_str(), Error,
  438. (Binary ? llvm::raw_fd_ostream::F_Binary : 0)));
  439. if (!Error.empty())
  440. return 0;
  441. }
  442. // Make sure the out stream file gets removed if we crash.
  443. if (RemoveFileOnSignal)
  444. llvm::sys::RemoveFileOnSignal(llvm::sys::Path(OSFile));
  445. if (ResultPathName)
  446. *ResultPathName = OutFile;
  447. if (TempPathName)
  448. *TempPathName = TempFile;
  449. return OS.take();
  450. }
  451. // Initialization Utilities
  452. bool CompilerInstance::InitializeSourceManager(StringRef InputFile) {
  453. return InitializeSourceManager(InputFile, getDiagnostics(), getFileManager(),
  454. getSourceManager(), getFrontendOpts());
  455. }
  456. bool CompilerInstance::InitializeSourceManager(StringRef InputFile,
  457. Diagnostic &Diags,
  458. FileManager &FileMgr,
  459. SourceManager &SourceMgr,
  460. const FrontendOptions &Opts) {
  461. // Figure out where to get and map in the main file, unless it's already
  462. // been created (e.g., by a precompiled preamble).
  463. if (!SourceMgr.getMainFileID().isInvalid()) {
  464. // Do nothing: the main file has already been set.
  465. } else if (InputFile != "-") {
  466. const FileEntry *File = FileMgr.getFile(InputFile);
  467. if (!File) {
  468. Diags.Report(diag::err_fe_error_reading) << InputFile;
  469. return false;
  470. }
  471. SourceMgr.createMainFileID(File);
  472. } else {
  473. llvm::OwningPtr<llvm::MemoryBuffer> SB;
  474. if (llvm::MemoryBuffer::getSTDIN(SB)) {
  475. // FIXME: Give ec.message() in this diag.
  476. Diags.Report(diag::err_fe_error_reading_stdin);
  477. return false;
  478. }
  479. const FileEntry *File = FileMgr.getVirtualFile(SB->getBufferIdentifier(),
  480. SB->getBufferSize(), 0);
  481. SourceMgr.createMainFileID(File);
  482. SourceMgr.overrideFileContents(File, SB.take());
  483. }
  484. assert(!SourceMgr.getMainFileID().isInvalid() &&
  485. "Couldn't establish MainFileID!");
  486. return true;
  487. }
  488. // High-Level Operations
  489. bool CompilerInstance::ExecuteAction(FrontendAction &Act) {
  490. assert(hasDiagnostics() && "Diagnostics engine is not initialized!");
  491. assert(!getFrontendOpts().ShowHelp && "Client must handle '-help'!");
  492. assert(!getFrontendOpts().ShowVersion && "Client must handle '-version'!");
  493. // FIXME: Take this as an argument, once all the APIs we used have moved to
  494. // taking it as an input instead of hard-coding llvm::errs.
  495. raw_ostream &OS = llvm::errs();
  496. // Create the target instance.
  497. setTarget(TargetInfo::CreateTargetInfo(getDiagnostics(), getTargetOpts()));
  498. if (!hasTarget())
  499. return false;
  500. // Inform the target of the language options.
  501. //
  502. // FIXME: We shouldn't need to do this, the target should be immutable once
  503. // created. This complexity should be lifted elsewhere.
  504. getTarget().setForcedLangOptions(getLangOpts());
  505. // Validate/process some options.
  506. if (getHeaderSearchOpts().Verbose)
  507. OS << "clang -cc1 version " CLANG_VERSION_STRING
  508. << " based upon " << PACKAGE_STRING
  509. << " hosted on " << llvm::sys::getHostTriple() << "\n";
  510. if (getFrontendOpts().ShowTimers)
  511. createFrontendTimer();
  512. if (getFrontendOpts().ShowStats)
  513. llvm::EnableStatistics();
  514. for (unsigned i = 0, e = getFrontendOpts().Inputs.size(); i != e; ++i) {
  515. const std::string &InFile = getFrontendOpts().Inputs[i].second;
  516. // Reset the ID tables if we are reusing the SourceManager.
  517. if (hasSourceManager())
  518. getSourceManager().clearIDTables();
  519. if (Act.BeginSourceFile(*this, InFile, getFrontendOpts().Inputs[i].first)) {
  520. Act.Execute();
  521. Act.EndSourceFile();
  522. }
  523. }
  524. if (getDiagnosticOpts().ShowCarets) {
  525. // We can have multiple diagnostics sharing one diagnostic client.
  526. // Get the total number of warnings/errors from the client.
  527. unsigned NumWarnings = getDiagnostics().getClient()->getNumWarnings();
  528. unsigned NumErrors = getDiagnostics().getClient()->getNumErrors();
  529. if (NumWarnings)
  530. OS << NumWarnings << " warning" << (NumWarnings == 1 ? "" : "s");
  531. if (NumWarnings && NumErrors)
  532. OS << " and ";
  533. if (NumErrors)
  534. OS << NumErrors << " error" << (NumErrors == 1 ? "" : "s");
  535. if (NumWarnings || NumErrors)
  536. OS << " generated.\n";
  537. }
  538. if (getFrontendOpts().ShowStats && hasFileManager()) {
  539. getFileManager().PrintStats();
  540. OS << "\n";
  541. }
  542. return !getDiagnostics().getClient()->getNumErrors();
  543. }
  544. /// \brief Determine the appropriate source input kind based on language
  545. /// options.
  546. static InputKind getSourceInputKindFromOptions(const LangOptions &LangOpts) {
  547. if (LangOpts.OpenCL)
  548. return IK_OpenCL;
  549. if (LangOpts.CUDA)
  550. return IK_CUDA;
  551. if (LangOpts.ObjC1)
  552. return LangOpts.CPlusPlus? IK_ObjCXX : IK_ObjC;
  553. return LangOpts.CPlusPlus? IK_CXX : IK_C;
  554. }
  555. /// \brief Compile a module file for the given module name with the given
  556. /// umbrella header, using the options provided by the importing compiler
  557. /// instance.
  558. static void compileModule(CompilerInstance &ImportingInstance,
  559. StringRef ModuleName,
  560. StringRef ModuleFileName,
  561. StringRef UmbrellaHeader) {
  562. // Construct a compiler invocation for creating this module.
  563. llvm::IntrusiveRefCntPtr<CompilerInvocation> Invocation
  564. (new CompilerInvocation(ImportingInstance.getInvocation()));
  565. Invocation->getLangOpts().resetNonModularOptions();
  566. Invocation->getPreprocessorOpts().resetNonModularOptions();
  567. FrontendOptions &FrontendOpts = Invocation->getFrontendOpts();
  568. FrontendOpts.OutputFile = ModuleFileName.str();
  569. FrontendOpts.DisableFree = false;
  570. FrontendOpts.Inputs.clear();
  571. FrontendOpts.Inputs.push_back(
  572. std::make_pair(getSourceInputKindFromOptions(Invocation->getLangOpts()),
  573. UmbrellaHeader));
  574. Invocation->getDiagnosticOpts().VerifyDiagnostics = 0;
  575. // FIXME: Strip away all of the compilation options that won't be transferred
  576. // down to the module. This presumably includes -D flags, optimization
  577. // settings, etc.
  578. // Construct a compiler instance that will be used to actually create the
  579. // module.
  580. CompilerInstance Instance;
  581. Instance.setInvocation(&*Invocation);
  582. Instance.createDiagnostics(/*argc=*/0, /*argv=*/0,
  583. &ImportingInstance.getDiagnosticClient(),
  584. /*ShouldOwnClient=*/false);
  585. // Construct a module-generating action.
  586. GeneratePCHAction CreateModuleAction(true);
  587. // Execute the action to actually build the module in-place.
  588. // FIXME: Need to synchronize when multiple processes do this.
  589. Instance.ExecuteAction(CreateModuleAction);
  590. // Tell the diagnostic client that it's (re-)starting to process a source
  591. // file.
  592. ImportingInstance.getDiagnosticClient()
  593. .BeginSourceFile(ImportingInstance.getLangOpts(),
  594. &ImportingInstance.getPreprocessor());
  595. }
  596. ModuleKey CompilerInstance::loadModule(SourceLocation ImportLoc,
  597. IdentifierInfo &ModuleName,
  598. SourceLocation ModuleNameLoc) {
  599. // Determine what file we're searching from.
  600. SourceManager &SourceMgr = getSourceManager();
  601. SourceLocation ExpandedImportLoc = SourceMgr.getExpansionLoc(ImportLoc);
  602. const FileEntry *CurFile
  603. = SourceMgr.getFileEntryForID(SourceMgr.getFileID(ExpandedImportLoc));
  604. if (!CurFile)
  605. CurFile = SourceMgr.getFileEntryForID(SourceMgr.getMainFileID());
  606. // Search for a module with the given name.
  607. std::string UmbrellaHeader;
  608. std::string ModuleFileName;
  609. const FileEntry *ModuleFile
  610. = PP->getHeaderSearchInfo().lookupModule(ModuleName.getName(),
  611. &ModuleFileName,
  612. &UmbrellaHeader);
  613. bool BuildingModule = false;
  614. if (!ModuleFile && !UmbrellaHeader.empty()) {
  615. // We didn't find the module, but there is an umbrella header that
  616. // can be used to create the module file. Create a separate compilation
  617. // module to do so.
  618. BuildingModule = true;
  619. compileModule(*this, ModuleName.getName(), ModuleFileName, UmbrellaHeader);
  620. ModuleFile = PP->getHeaderSearchInfo().lookupModule(ModuleName.getName());
  621. }
  622. if (!ModuleFile) {
  623. getDiagnostics().Report(ModuleNameLoc,
  624. BuildingModule? diag::err_module_not_built
  625. : diag::err_module_not_found)
  626. << ModuleName.getName()
  627. << SourceRange(ImportLoc, ModuleNameLoc);
  628. return 0;
  629. }
  630. // If we don't already have an ASTReader, create one now.
  631. if (!ModuleManager) {
  632. std::string Sysroot = getHeaderSearchOpts().Sysroot;
  633. const PreprocessorOptions &PPOpts = getPreprocessorOpts();
  634. ModuleManager = new ASTReader(getPreprocessor(), *Context,
  635. Sysroot.empty() ? "" : Sysroot.c_str(),
  636. PPOpts.DisablePCHValidation,
  637. PPOpts.DisableStatCache);
  638. ModuleManager->setDeserializationListener(
  639. getASTConsumer().GetASTDeserializationListener());
  640. getASTContext().setASTMutationListener(
  641. getASTConsumer().GetASTMutationListener());
  642. llvm::OwningPtr<ExternalASTSource> Source;
  643. Source.reset(ModuleManager);
  644. getASTContext().setExternalSource(Source);
  645. ModuleManager->InitializeSema(getSema());
  646. }
  647. // Try to load the module we found.
  648. switch (ModuleManager->ReadAST(ModuleFile->getName(),
  649. serialization::MK_Module)) {
  650. case ASTReader::Success:
  651. break;
  652. case ASTReader::IgnorePCH:
  653. // FIXME: The ASTReader will already have complained, but can we showhorn
  654. // that diagnostic information into a more useful form?
  655. return 0;
  656. case ASTReader::Failure:
  657. // Already complained.
  658. return 0;
  659. }
  660. // FIXME: The module file's FileEntry makes a poor key indeed!
  661. return (ModuleKey)ModuleFile;
  662. }