CompilerInstance.cpp 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578
  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/FrontendDiagnostic.h"
  24. #include "clang/Frontend/TextDiagnosticPrinter.h"
  25. #include "clang/Frontend/VerifyDiagnosticsClient.h"
  26. #include "clang/Frontend/Utils.h"
  27. #include "clang/Serialization/ASTReader.h"
  28. #include "clang/Sema/CodeCompleteConsumer.h"
  29. #include "llvm/LLVMContext.h"
  30. #include "llvm/Support/MemoryBuffer.h"
  31. #include "llvm/Support/raw_ostream.h"
  32. #include "llvm/ADT/Statistic.h"
  33. #include "llvm/Support/Timer.h"
  34. #include "llvm/Support/Host.h"
  35. #include "llvm/Support/Path.h"
  36. #include "llvm/Support/Program.h"
  37. #include "llvm/Support/Signals.h"
  38. #include "llvm/Support/system_error.h"
  39. using namespace clang;
  40. CompilerInstance::CompilerInstance()
  41. : Invocation(new CompilerInvocation()) {
  42. }
  43. CompilerInstance::~CompilerInstance() {
  44. }
  45. void CompilerInstance::setLLVMContext(llvm::LLVMContext *Value) {
  46. LLVMContext.reset(Value);
  47. }
  48. void CompilerInstance::setInvocation(CompilerInvocation *Value) {
  49. Invocation.reset(Value);
  50. }
  51. void CompilerInstance::setDiagnostics(Diagnostic *Value) {
  52. Diagnostics = Value;
  53. }
  54. void CompilerInstance::setTarget(TargetInfo *Value) {
  55. Target.reset(Value);
  56. }
  57. void CompilerInstance::setFileManager(FileManager *Value) {
  58. FileMgr.reset(Value);
  59. }
  60. void CompilerInstance::setSourceManager(SourceManager *Value) {
  61. SourceMgr.reset(Value);
  62. }
  63. void CompilerInstance::setPreprocessor(Preprocessor *Value) {
  64. PP.reset(Value);
  65. }
  66. void CompilerInstance::setASTContext(ASTContext *Value) {
  67. Context.reset(Value);
  68. }
  69. void CompilerInstance::setSema(Sema *S) {
  70. TheSema.reset(S);
  71. }
  72. void CompilerInstance::setASTConsumer(ASTConsumer *Value) {
  73. Consumer.reset(Value);
  74. }
  75. void CompilerInstance::setCodeCompletionConsumer(CodeCompleteConsumer *Value) {
  76. CompletionConsumer.reset(Value);
  77. }
  78. // Diagnostics
  79. static void SetUpBuildDumpLog(const DiagnosticOptions &DiagOpts,
  80. unsigned argc, const char* const *argv,
  81. Diagnostic &Diags) {
  82. std::string ErrorInfo;
  83. llvm::OwningPtr<llvm::raw_ostream> OS(
  84. new llvm::raw_fd_ostream(DiagOpts.DumpBuildInformation.c_str(), ErrorInfo));
  85. if (!ErrorInfo.empty()) {
  86. Diags.Report(diag::err_fe_unable_to_open_logfile)
  87. << DiagOpts.DumpBuildInformation << ErrorInfo;
  88. return;
  89. }
  90. (*OS) << "clang -cc1 command line arguments: ";
  91. for (unsigned i = 0; i != argc; ++i)
  92. (*OS) << argv[i] << ' ';
  93. (*OS) << '\n';
  94. // Chain in a diagnostic client which will log the diagnostics.
  95. DiagnosticClient *Logger =
  96. new TextDiagnosticPrinter(*OS.take(), DiagOpts, /*OwnsOutputStream=*/true);
  97. Diags.setClient(new ChainedDiagnosticClient(Diags.takeClient(), Logger));
  98. }
  99. void CompilerInstance::createDiagnostics(int Argc, const char* const *Argv,
  100. DiagnosticClient *Client) {
  101. Diagnostics = createDiagnostics(getDiagnosticOpts(), Argc, Argv, Client);
  102. }
  103. llvm::IntrusiveRefCntPtr<Diagnostic>
  104. CompilerInstance::createDiagnostics(const DiagnosticOptions &Opts,
  105. int Argc, const char* const *Argv,
  106. DiagnosticClient *Client) {
  107. llvm::IntrusiveRefCntPtr<DiagnosticIDs> DiagID(new DiagnosticIDs());
  108. llvm::IntrusiveRefCntPtr<Diagnostic> Diags(new Diagnostic(DiagID));
  109. // Create the diagnostic client for reporting errors or for
  110. // implementing -verify.
  111. if (Client)
  112. Diags->setClient(Client);
  113. else
  114. Diags->setClient(new TextDiagnosticPrinter(llvm::errs(), Opts));
  115. // Chain in -verify checker, if requested.
  116. if (Opts.VerifyDiagnostics)
  117. Diags->setClient(new VerifyDiagnosticsClient(*Diags, Diags->takeClient()));
  118. if (!Opts.DumpBuildInformation.empty())
  119. SetUpBuildDumpLog(Opts, Argc, Argv, *Diags);
  120. // Configure our handling of diagnostics.
  121. ProcessWarningOptions(*Diags, Opts);
  122. return Diags;
  123. }
  124. // File Manager
  125. void CompilerInstance::createFileManager() {
  126. FileMgr.reset(new FileManager(getFileSystemOpts()));
  127. }
  128. // Source Manager
  129. void CompilerInstance::createSourceManager(FileManager &FileMgr) {
  130. SourceMgr.reset(new SourceManager(getDiagnostics(), FileMgr));
  131. }
  132. // Preprocessor
  133. void CompilerInstance::createPreprocessor() {
  134. PP.reset(createPreprocessor(getDiagnostics(), getLangOpts(),
  135. getPreprocessorOpts(), getHeaderSearchOpts(),
  136. getDependencyOutputOpts(), getTarget(),
  137. getFrontendOpts(), getSourceManager(),
  138. getFileManager()));
  139. }
  140. Preprocessor *
  141. CompilerInstance::createPreprocessor(Diagnostic &Diags,
  142. const LangOptions &LangInfo,
  143. const PreprocessorOptions &PPOpts,
  144. const HeaderSearchOptions &HSOpts,
  145. const DependencyOutputOptions &DepOpts,
  146. const TargetInfo &Target,
  147. const FrontendOptions &FEOpts,
  148. SourceManager &SourceMgr,
  149. FileManager &FileMgr) {
  150. // Create a PTH manager if we are using some form of a token cache.
  151. PTHManager *PTHMgr = 0;
  152. if (!PPOpts.TokenCache.empty())
  153. PTHMgr = PTHManager::Create(PPOpts.TokenCache, Diags);
  154. // Create the Preprocessor.
  155. HeaderSearch *HeaderInfo = new HeaderSearch(FileMgr);
  156. Preprocessor *PP = new Preprocessor(Diags, LangInfo, Target,
  157. SourceMgr, *HeaderInfo, PTHMgr,
  158. /*OwnsHeaderSearch=*/true);
  159. // Note that this is different then passing PTHMgr to Preprocessor's ctor.
  160. // That argument is used as the IdentifierInfoLookup argument to
  161. // IdentifierTable's ctor.
  162. if (PTHMgr) {
  163. PTHMgr->setPreprocessor(PP);
  164. PP->setPTHManager(PTHMgr);
  165. }
  166. if (PPOpts.DetailedRecord)
  167. PP->createPreprocessingRecord();
  168. InitializePreprocessor(*PP, PPOpts, HSOpts, FEOpts);
  169. // Handle generating dependencies, if requested.
  170. if (!DepOpts.OutputFile.empty())
  171. AttachDependencyFileGen(*PP, DepOpts);
  172. return PP;
  173. }
  174. // ASTContext
  175. void CompilerInstance::createASTContext() {
  176. Preprocessor &PP = getPreprocessor();
  177. Context.reset(new ASTContext(getLangOpts(), PP.getSourceManager(),
  178. getTarget(), PP.getIdentifierTable(),
  179. PP.getSelectorTable(), PP.getBuiltinInfo(),
  180. /*size_reserve=*/ 0));
  181. }
  182. // ExternalASTSource
  183. void CompilerInstance::createPCHExternalASTSource(llvm::StringRef Path,
  184. bool DisablePCHValidation,
  185. void *DeserializationListener){
  186. llvm::OwningPtr<ExternalASTSource> Source;
  187. bool Preamble = getPreprocessorOpts().PrecompiledPreambleBytes.first != 0;
  188. Source.reset(createPCHExternalASTSource(Path, getHeaderSearchOpts().Sysroot,
  189. DisablePCHValidation,
  190. getPreprocessor(), getASTContext(),
  191. DeserializationListener,
  192. Preamble));
  193. getASTContext().setExternalSource(Source);
  194. }
  195. ExternalASTSource *
  196. CompilerInstance::createPCHExternalASTSource(llvm::StringRef Path,
  197. const std::string &Sysroot,
  198. bool DisablePCHValidation,
  199. Preprocessor &PP,
  200. ASTContext &Context,
  201. void *DeserializationListener,
  202. bool Preamble) {
  203. llvm::OwningPtr<ASTReader> Reader;
  204. Reader.reset(new ASTReader(PP, &Context,
  205. Sysroot.empty() ? 0 : Sysroot.c_str(),
  206. DisablePCHValidation));
  207. Reader->setDeserializationListener(
  208. static_cast<ASTDeserializationListener *>(DeserializationListener));
  209. switch (Reader->ReadAST(Path,
  210. Preamble ? ASTReader::Preamble : ASTReader::PCH)) {
  211. case ASTReader::Success:
  212. // Set the predefines buffer as suggested by the PCH reader. Typically, the
  213. // predefines buffer will be empty.
  214. PP.setPredefines(Reader->getSuggestedPredefines());
  215. return Reader.take();
  216. case ASTReader::Failure:
  217. // Unrecoverable failure: don't even try to process the input file.
  218. break;
  219. case ASTReader::IgnorePCH:
  220. // No suitable PCH file could be found. Return an error.
  221. break;
  222. }
  223. return 0;
  224. }
  225. // Code Completion
  226. static bool EnableCodeCompletion(Preprocessor &PP,
  227. const std::string &Filename,
  228. unsigned Line,
  229. unsigned Column) {
  230. // Tell the source manager to chop off the given file at a specific
  231. // line and column.
  232. const FileEntry *Entry = PP.getFileManager().getFile(Filename);
  233. if (!Entry) {
  234. PP.getDiagnostics().Report(diag::err_fe_invalid_code_complete_file)
  235. << Filename;
  236. return true;
  237. }
  238. // Truncate the named file at the given line/column.
  239. PP.SetCodeCompletionPoint(Entry, Line, Column);
  240. return false;
  241. }
  242. void CompilerInstance::createCodeCompletionConsumer() {
  243. const ParsedSourceLocation &Loc = getFrontendOpts().CodeCompletionAt;
  244. if (!CompletionConsumer) {
  245. CompletionConsumer.reset(
  246. createCodeCompletionConsumer(getPreprocessor(),
  247. Loc.FileName, Loc.Line, Loc.Column,
  248. getFrontendOpts().ShowMacrosInCodeCompletion,
  249. getFrontendOpts().ShowCodePatternsInCodeCompletion,
  250. getFrontendOpts().ShowGlobalSymbolsInCodeCompletion,
  251. llvm::outs()));
  252. if (!CompletionConsumer)
  253. return;
  254. } else if (EnableCodeCompletion(getPreprocessor(), Loc.FileName,
  255. Loc.Line, Loc.Column)) {
  256. CompletionConsumer.reset();
  257. return;
  258. }
  259. if (CompletionConsumer->isOutputBinary() &&
  260. llvm::sys::Program::ChangeStdoutToBinary()) {
  261. getPreprocessor().getDiagnostics().Report(diag::err_fe_stdout_binary);
  262. CompletionConsumer.reset();
  263. }
  264. }
  265. void CompilerInstance::createFrontendTimer() {
  266. FrontendTimer.reset(new llvm::Timer("Clang front-end timer"));
  267. }
  268. CodeCompleteConsumer *
  269. CompilerInstance::createCodeCompletionConsumer(Preprocessor &PP,
  270. const std::string &Filename,
  271. unsigned Line,
  272. unsigned Column,
  273. bool ShowMacros,
  274. bool ShowCodePatterns,
  275. bool ShowGlobals,
  276. llvm::raw_ostream &OS) {
  277. if (EnableCodeCompletion(PP, Filename, Line, Column))
  278. return 0;
  279. // Set up the creation routine for code-completion.
  280. return new PrintingCodeCompleteConsumer(ShowMacros, ShowCodePatterns,
  281. ShowGlobals, OS);
  282. }
  283. void CompilerInstance::createSema(bool CompleteTranslationUnit,
  284. CodeCompleteConsumer *CompletionConsumer) {
  285. TheSema.reset(new Sema(getPreprocessor(), getASTContext(), getASTConsumer(),
  286. CompleteTranslationUnit, CompletionConsumer));
  287. }
  288. // Output Files
  289. void CompilerInstance::addOutputFile(const OutputFile &OutFile) {
  290. assert(OutFile.OS && "Attempt to add empty stream to output list!");
  291. OutputFiles.push_back(OutFile);
  292. }
  293. void CompilerInstance::clearOutputFiles(bool EraseFiles) {
  294. for (std::list<OutputFile>::iterator
  295. it = OutputFiles.begin(), ie = OutputFiles.end(); it != ie; ++it) {
  296. delete it->OS;
  297. if (!it->TempFilename.empty()) {
  298. llvm::sys::Path TempPath(it->TempFilename);
  299. if (EraseFiles)
  300. TempPath.eraseFromDisk();
  301. else {
  302. std::string Error;
  303. llvm::sys::Path NewOutFile(it->Filename);
  304. // If '-working-directory' was passed, the output filename should be
  305. // relative to that.
  306. FileManager::FixupRelativePath(NewOutFile, getFileSystemOpts());
  307. if (TempPath.renamePathOnDisk(NewOutFile, &Error)) {
  308. getDiagnostics().Report(diag::err_fe_unable_to_rename_temp)
  309. << it->TempFilename << it->Filename << Error;
  310. TempPath.eraseFromDisk();
  311. }
  312. }
  313. } else if (!it->Filename.empty() && EraseFiles)
  314. llvm::sys::Path(it->Filename).eraseFromDisk();
  315. }
  316. OutputFiles.clear();
  317. }
  318. llvm::raw_fd_ostream *
  319. CompilerInstance::createDefaultOutputFile(bool Binary,
  320. llvm::StringRef InFile,
  321. llvm::StringRef Extension) {
  322. return createOutputFile(getFrontendOpts().OutputFile, Binary,
  323. InFile, Extension);
  324. }
  325. llvm::raw_fd_ostream *
  326. CompilerInstance::createOutputFile(llvm::StringRef OutputPath,
  327. bool Binary,
  328. llvm::StringRef InFile,
  329. llvm::StringRef Extension) {
  330. std::string Error, OutputPathName, TempPathName;
  331. llvm::raw_fd_ostream *OS = createOutputFile(OutputPath, Error, Binary,
  332. InFile, Extension,
  333. &OutputPathName,
  334. &TempPathName);
  335. if (!OS) {
  336. getDiagnostics().Report(diag::err_fe_unable_to_open_output)
  337. << OutputPath << Error;
  338. return 0;
  339. }
  340. // Add the output file -- but don't try to remove "-", since this means we are
  341. // using stdin.
  342. addOutputFile(OutputFile((OutputPathName != "-") ? OutputPathName : "",
  343. TempPathName, OS));
  344. return OS;
  345. }
  346. llvm::raw_fd_ostream *
  347. CompilerInstance::createOutputFile(llvm::StringRef OutputPath,
  348. std::string &Error,
  349. bool Binary,
  350. llvm::StringRef InFile,
  351. llvm::StringRef Extension,
  352. std::string *ResultPathName,
  353. std::string *TempPathName) {
  354. std::string OutFile, TempFile;
  355. if (!OutputPath.empty()) {
  356. OutFile = OutputPath;
  357. } else if (InFile == "-") {
  358. OutFile = "-";
  359. } else if (!Extension.empty()) {
  360. llvm::sys::Path Path(InFile);
  361. Path.eraseSuffix();
  362. Path.appendSuffix(Extension);
  363. OutFile = Path.str();
  364. } else {
  365. OutFile = "-";
  366. }
  367. if (OutFile != "-") {
  368. llvm::sys::Path OutPath(OutFile);
  369. // Only create the temporary if we can actually write to OutPath, otherwise
  370. // we want to fail early.
  371. if (!OutPath.exists() ||
  372. (OutPath.isRegularFile() && OutPath.canWrite())) {
  373. // Create a temporary file.
  374. llvm::sys::Path TempPath(OutFile);
  375. if (!TempPath.createTemporaryFileOnDisk())
  376. TempFile = TempPath.str();
  377. }
  378. }
  379. std::string OSFile = OutFile;
  380. if (!TempFile.empty())
  381. OSFile = TempFile;
  382. llvm::OwningPtr<llvm::raw_fd_ostream> OS(
  383. new llvm::raw_fd_ostream(OSFile.c_str(), Error,
  384. (Binary ? llvm::raw_fd_ostream::F_Binary : 0)));
  385. if (!Error.empty())
  386. return 0;
  387. // Make sure the out stream file gets removed if we crash.
  388. llvm::sys::RemoveFileOnSignal(llvm::sys::Path(OSFile));
  389. if (ResultPathName)
  390. *ResultPathName = OutFile;
  391. if (TempPathName)
  392. *TempPathName = TempFile;
  393. return OS.take();
  394. }
  395. // Initialization Utilities
  396. bool CompilerInstance::InitializeSourceManager(llvm::StringRef InputFile) {
  397. return InitializeSourceManager(InputFile, getDiagnostics(), getFileManager(),
  398. getSourceManager(), getFrontendOpts());
  399. }
  400. bool CompilerInstance::InitializeSourceManager(llvm::StringRef InputFile,
  401. Diagnostic &Diags,
  402. FileManager &FileMgr,
  403. SourceManager &SourceMgr,
  404. const FrontendOptions &Opts) {
  405. // Figure out where to get and map in the main file, unless it's already
  406. // been created (e.g., by a precompiled preamble).
  407. if (!SourceMgr.getMainFileID().isInvalid()) {
  408. // Do nothing: the main file has already been set.
  409. } else if (InputFile != "-") {
  410. const FileEntry *File = FileMgr.getFile(InputFile);
  411. if (!File) {
  412. Diags.Report(diag::err_fe_error_reading) << InputFile;
  413. return false;
  414. }
  415. SourceMgr.createMainFileID(File);
  416. } else {
  417. llvm::OwningPtr<llvm::MemoryBuffer> SB;
  418. if (llvm::MemoryBuffer::getSTDIN(SB)) {
  419. // FIXME: Give ec.message() in this diag.
  420. Diags.Report(diag::err_fe_error_reading_stdin);
  421. return false;
  422. }
  423. const FileEntry *File = FileMgr.getVirtualFile(SB->getBufferIdentifier(),
  424. SB->getBufferSize(), 0);
  425. SourceMgr.createMainFileID(File);
  426. SourceMgr.overrideFileContents(File, SB.take());
  427. }
  428. assert(!SourceMgr.getMainFileID().isInvalid() &&
  429. "Couldn't establish MainFileID!");
  430. return true;
  431. }
  432. // High-Level Operations
  433. bool CompilerInstance::ExecuteAction(FrontendAction &Act) {
  434. assert(hasDiagnostics() && "Diagnostics engine is not initialized!");
  435. assert(!getFrontendOpts().ShowHelp && "Client must handle '-help'!");
  436. assert(!getFrontendOpts().ShowVersion && "Client must handle '-version'!");
  437. // FIXME: Take this as an argument, once all the APIs we used have moved to
  438. // taking it as an input instead of hard-coding llvm::errs.
  439. llvm::raw_ostream &OS = llvm::errs();
  440. // Create the target instance.
  441. setTarget(TargetInfo::CreateTargetInfo(getDiagnostics(), getTargetOpts()));
  442. if (!hasTarget())
  443. return false;
  444. // Inform the target of the language options.
  445. //
  446. // FIXME: We shouldn't need to do this, the target should be immutable once
  447. // created. This complexity should be lifted elsewhere.
  448. getTarget().setForcedLangOptions(getLangOpts());
  449. // Validate/process some options.
  450. if (getHeaderSearchOpts().Verbose)
  451. OS << "clang -cc1 version " CLANG_VERSION_STRING
  452. << " based upon " << PACKAGE_STRING
  453. << " hosted on " << llvm::sys::getHostTriple() << "\n";
  454. if (getFrontendOpts().ShowTimers)
  455. createFrontendTimer();
  456. if (getFrontendOpts().ShowStats)
  457. llvm::EnableStatistics();
  458. for (unsigned i = 0, e = getFrontendOpts().Inputs.size(); i != e; ++i) {
  459. const std::string &InFile = getFrontendOpts().Inputs[i].second;
  460. // Reset the ID tables if we are reusing the SourceManager.
  461. if (hasSourceManager())
  462. getSourceManager().clearIDTables();
  463. if (Act.BeginSourceFile(*this, InFile, getFrontendOpts().Inputs[i].first)) {
  464. Act.Execute();
  465. Act.EndSourceFile();
  466. }
  467. }
  468. if (getDiagnosticOpts().ShowCarets) {
  469. // We can have multiple diagnostics sharing one diagnostic client.
  470. // Get the total number of warnings/errors from the client.
  471. unsigned NumWarnings = getDiagnostics().getClient()->getNumWarnings();
  472. unsigned NumErrors = getDiagnostics().getClient()->getNumErrors();
  473. if (NumWarnings)
  474. OS << NumWarnings << " warning" << (NumWarnings == 1 ? "" : "s");
  475. if (NumWarnings && NumErrors)
  476. OS << " and ";
  477. if (NumErrors)
  478. OS << NumErrors << " error" << (NumErrors == 1 ? "" : "s");
  479. if (NumWarnings || NumErrors)
  480. OS << " generated.\n";
  481. }
  482. if (getFrontendOpts().ShowStats && hasFileManager()) {
  483. getFileManager().PrintStats();
  484. OS << "\n";
  485. }
  486. return !getDiagnostics().getClient()->getNumErrors();
  487. }