CompilerInstance.cpp 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538
  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/AST/ASTConsumer.h"
  11. #include "clang/AST/ASTContext.h"
  12. #include "clang/Basic/Diagnostic.h"
  13. #include "clang/Basic/FileManager.h"
  14. #include "clang/Basic/SourceManager.h"
  15. #include "clang/Basic/TargetInfo.h"
  16. #include "clang/Basic/Version.h"
  17. #include "clang/Lex/HeaderSearch.h"
  18. #include "clang/Lex/Preprocessor.h"
  19. #include "clang/Lex/PTHManager.h"
  20. #include "clang/Frontend/ChainedDiagnosticClient.h"
  21. #include "clang/Frontend/FrontendAction.h"
  22. #include "clang/Frontend/PCHReader.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/Sema/CodeCompleteConsumer.h"
  28. #include "llvm/LLVMContext.h"
  29. #include "llvm/Support/MemoryBuffer.h"
  30. #include "llvm/Support/raw_ostream.h"
  31. #include "llvm/ADT/Statistic.h"
  32. #include "llvm/Support/Timer.h"
  33. #include "llvm/System/Host.h"
  34. #include "llvm/System/Path.h"
  35. #include "llvm/System/Program.h"
  36. using namespace clang;
  37. CompilerInstance::CompilerInstance()
  38. : Invocation(new CompilerInvocation()) {
  39. }
  40. CompilerInstance::~CompilerInstance() {
  41. }
  42. void CompilerInstance::setLLVMContext(llvm::LLVMContext *Value) {
  43. LLVMContext.reset(Value);
  44. }
  45. void CompilerInstance::setInvocation(CompilerInvocation *Value) {
  46. Invocation.reset(Value);
  47. }
  48. void CompilerInstance::setDiagnostics(Diagnostic *Value) {
  49. Diagnostics = Value;
  50. }
  51. void CompilerInstance::setDiagnosticClient(DiagnosticClient *Value) {
  52. DiagClient.reset(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::setASTConsumer(ASTConsumer *Value) {
  70. Consumer.reset(Value);
  71. }
  72. void CompilerInstance::setCodeCompletionConsumer(CodeCompleteConsumer *Value) {
  73. CompletionConsumer.reset(Value);
  74. }
  75. // Diagnostics
  76. namespace {
  77. class BinaryDiagnosticSerializer : public DiagnosticClient {
  78. llvm::raw_ostream &OS;
  79. SourceManager *SourceMgr;
  80. public:
  81. explicit BinaryDiagnosticSerializer(llvm::raw_ostream &OS)
  82. : OS(OS), SourceMgr(0) { }
  83. virtual void HandleDiagnostic(Diagnostic::Level DiagLevel,
  84. const DiagnosticInfo &Info);
  85. };
  86. }
  87. void BinaryDiagnosticSerializer::HandleDiagnostic(Diagnostic::Level DiagLevel,
  88. const DiagnosticInfo &Info) {
  89. StoredDiagnostic(DiagLevel, Info).Serialize(OS);
  90. }
  91. static void SetUpBuildDumpLog(const DiagnosticOptions &DiagOpts,
  92. unsigned argc, char **argv,
  93. Diagnostic &Diags) {
  94. std::string ErrorInfo;
  95. llvm::OwningPtr<llvm::raw_ostream> OS(
  96. new llvm::raw_fd_ostream(DiagOpts.DumpBuildInformation.c_str(), ErrorInfo));
  97. if (!ErrorInfo.empty()) {
  98. Diags.Report(diag::err_fe_unable_to_open_logfile)
  99. << DiagOpts.DumpBuildInformation << ErrorInfo;
  100. return;
  101. }
  102. (*OS) << "clang -cc1 command line arguments: ";
  103. for (unsigned i = 0; i != argc; ++i)
  104. (*OS) << argv[i] << ' ';
  105. (*OS) << '\n';
  106. // Chain in a diagnostic client which will log the diagnostics.
  107. DiagnosticClient *Logger =
  108. new TextDiagnosticPrinter(*OS.take(), DiagOpts, /*OwnsOutputStream=*/true);
  109. Diags.setClient(new ChainedDiagnosticClient(Diags.getClient(), Logger));
  110. }
  111. void CompilerInstance::createDiagnostics(int Argc, char **Argv) {
  112. Diagnostics = createDiagnostics(getDiagnosticOpts(), Argc, Argv);
  113. if (Diagnostics)
  114. DiagClient.reset(Diagnostics->getClient());
  115. }
  116. llvm::IntrusiveRefCntPtr<Diagnostic>
  117. CompilerInstance::createDiagnostics(const DiagnosticOptions &Opts,
  118. int Argc, char **Argv) {
  119. llvm::IntrusiveRefCntPtr<Diagnostic> Diags(new Diagnostic());
  120. // Create the diagnostic client for reporting errors or for
  121. // implementing -verify.
  122. llvm::OwningPtr<DiagnosticClient> DiagClient;
  123. if (Opts.BinaryOutput) {
  124. if (llvm::sys::Program::ChangeStderrToBinary()) {
  125. // We weren't able to set standard error to binary, which is a
  126. // bit of a problem. So, just create a text diagnostic printer
  127. // to complain about this problem, and pretend that the user
  128. // didn't try to use binary output.
  129. DiagClient.reset(new TextDiagnosticPrinter(llvm::errs(), Opts));
  130. Diags->setClient(DiagClient.take());
  131. Diags->Report(diag::err_fe_stderr_binary);
  132. return Diags;
  133. } else {
  134. DiagClient.reset(new BinaryDiagnosticSerializer(llvm::errs()));
  135. }
  136. } else {
  137. DiagClient.reset(new TextDiagnosticPrinter(llvm::errs(), Opts));
  138. }
  139. // Chain in -verify checker, if requested.
  140. if (Opts.VerifyDiagnostics)
  141. DiagClient.reset(new VerifyDiagnosticsClient(*Diags, DiagClient.take()));
  142. Diags->setClient(DiagClient.take());
  143. if (!Opts.DumpBuildInformation.empty())
  144. SetUpBuildDumpLog(Opts, Argc, Argv, *Diags);
  145. // Configure our handling of diagnostics.
  146. ProcessWarningOptions(*Diags, Opts);
  147. return Diags;
  148. }
  149. // File Manager
  150. void CompilerInstance::createFileManager() {
  151. FileMgr.reset(new FileManager());
  152. }
  153. // Source Manager
  154. void CompilerInstance::createSourceManager() {
  155. SourceMgr.reset(new SourceManager(getDiagnostics()));
  156. }
  157. // Preprocessor
  158. void CompilerInstance::createPreprocessor() {
  159. PP.reset(createPreprocessor(getDiagnostics(), getLangOpts(),
  160. getPreprocessorOpts(), getHeaderSearchOpts(),
  161. getDependencyOutputOpts(), getTarget(),
  162. getFrontendOpts(), getSourceManager(),
  163. getFileManager()));
  164. }
  165. Preprocessor *
  166. CompilerInstance::createPreprocessor(Diagnostic &Diags,
  167. const LangOptions &LangInfo,
  168. const PreprocessorOptions &PPOpts,
  169. const HeaderSearchOptions &HSOpts,
  170. const DependencyOutputOptions &DepOpts,
  171. const TargetInfo &Target,
  172. const FrontendOptions &FEOpts,
  173. SourceManager &SourceMgr,
  174. FileManager &FileMgr) {
  175. // Create a PTH manager if we are using some form of a token cache.
  176. PTHManager *PTHMgr = 0;
  177. if (!PPOpts.TokenCache.empty())
  178. PTHMgr = PTHManager::Create(PPOpts.TokenCache, Diags);
  179. // Create the Preprocessor.
  180. HeaderSearch *HeaderInfo = new HeaderSearch(FileMgr);
  181. Preprocessor *PP = new Preprocessor(Diags, LangInfo, Target,
  182. SourceMgr, *HeaderInfo, PTHMgr,
  183. /*OwnsHeaderSearch=*/true);
  184. // Note that this is different then passing PTHMgr to Preprocessor's ctor.
  185. // That argument is used as the IdentifierInfoLookup argument to
  186. // IdentifierTable's ctor.
  187. if (PTHMgr) {
  188. PTHMgr->setPreprocessor(PP);
  189. PP->setPTHManager(PTHMgr);
  190. }
  191. if (PPOpts.DetailedRecord)
  192. PP->createPreprocessingRecord();
  193. InitializePreprocessor(*PP, PPOpts, HSOpts, FEOpts);
  194. // Handle generating dependencies, if requested.
  195. if (!DepOpts.OutputFile.empty())
  196. AttachDependencyFileGen(*PP, DepOpts);
  197. return PP;
  198. }
  199. // ASTContext
  200. void CompilerInstance::createASTContext() {
  201. Preprocessor &PP = getPreprocessor();
  202. Context.reset(new ASTContext(getLangOpts(), PP.getSourceManager(),
  203. getTarget(), PP.getIdentifierTable(),
  204. PP.getSelectorTable(), PP.getBuiltinInfo(),
  205. /*FreeMemory=*/ !getFrontendOpts().DisableFree,
  206. /*size_reserve=*/ 0));
  207. }
  208. // ExternalASTSource
  209. void CompilerInstance::createPCHExternalASTSource(llvm::StringRef Path) {
  210. llvm::OwningPtr<ExternalASTSource> Source;
  211. Source.reset(createPCHExternalASTSource(Path, getHeaderSearchOpts().Sysroot,
  212. getPreprocessor(), getASTContext()));
  213. getASTContext().setExternalSource(Source);
  214. }
  215. ExternalASTSource *
  216. CompilerInstance::createPCHExternalASTSource(llvm::StringRef Path,
  217. const std::string &Sysroot,
  218. Preprocessor &PP,
  219. ASTContext &Context) {
  220. llvm::OwningPtr<PCHReader> Reader;
  221. Reader.reset(new PCHReader(PP, &Context,
  222. Sysroot.empty() ? 0 : Sysroot.c_str()));
  223. switch (Reader->ReadPCH(Path)) {
  224. case PCHReader::Success:
  225. // Set the predefines buffer as suggested by the PCH reader. Typically, the
  226. // predefines buffer will be empty.
  227. PP.setPredefines(Reader->getSuggestedPredefines());
  228. return Reader.take();
  229. case PCHReader::Failure:
  230. // Unrecoverable failure: don't even try to process the input file.
  231. break;
  232. case PCHReader::IgnorePCH:
  233. // No suitable PCH file could be found. Return an error.
  234. break;
  235. }
  236. return 0;
  237. }
  238. // Code Completion
  239. void CompilerInstance::createCodeCompletionConsumer() {
  240. const ParsedSourceLocation &Loc = getFrontendOpts().CodeCompletionAt;
  241. CompletionConsumer.reset(
  242. createCodeCompletionConsumer(getPreprocessor(),
  243. Loc.FileName, Loc.Line, Loc.Column,
  244. getFrontendOpts().DebugCodeCompletionPrinter,
  245. getFrontendOpts().ShowMacrosInCodeCompletion,
  246. llvm::outs()));
  247. if (!CompletionConsumer)
  248. return;
  249. if (CompletionConsumer->isOutputBinary() &&
  250. llvm::sys::Program::ChangeStdoutToBinary()) {
  251. getPreprocessor().getDiagnostics().Report(diag::err_fe_stdout_binary);
  252. CompletionConsumer.reset();
  253. }
  254. }
  255. void CompilerInstance::createFrontendTimer() {
  256. FrontendTimer.reset(new llvm::Timer("Clang front-end timer"));
  257. }
  258. CodeCompleteConsumer *
  259. CompilerInstance::createCodeCompletionConsumer(Preprocessor &PP,
  260. const std::string &Filename,
  261. unsigned Line,
  262. unsigned Column,
  263. bool UseDebugPrinter,
  264. bool ShowMacros,
  265. llvm::raw_ostream &OS) {
  266. // Tell the source manager to chop off the given file at a specific
  267. // line and column.
  268. const FileEntry *Entry = PP.getFileManager().getFile(Filename);
  269. if (!Entry) {
  270. PP.getDiagnostics().Report(diag::err_fe_invalid_code_complete_file)
  271. << Filename;
  272. return 0;
  273. }
  274. // Truncate the named file at the given line/column.
  275. PP.SetCodeCompletionPoint(Entry, Line, Column);
  276. // Set up the creation routine for code-completion.
  277. if (UseDebugPrinter)
  278. return new PrintingCodeCompleteConsumer(ShowMacros, OS);
  279. else
  280. return new CIndexCodeCompleteConsumer(ShowMacros, OS);
  281. }
  282. // Output Files
  283. void CompilerInstance::addOutputFile(llvm::StringRef Path,
  284. llvm::raw_ostream *OS) {
  285. assert(OS && "Attempt to add empty stream to output list!");
  286. OutputFiles.push_back(std::make_pair(Path, OS));
  287. }
  288. void CompilerInstance::clearOutputFiles(bool EraseFiles) {
  289. for (std::list< std::pair<std::string, llvm::raw_ostream*> >::iterator
  290. it = OutputFiles.begin(), ie = OutputFiles.end(); it != ie; ++it) {
  291. delete it->second;
  292. if (EraseFiles && !it->first.empty())
  293. llvm::sys::Path(it->first).eraseFromDisk();
  294. }
  295. OutputFiles.clear();
  296. }
  297. llvm::raw_fd_ostream *
  298. CompilerInstance::createDefaultOutputFile(bool Binary,
  299. llvm::StringRef InFile,
  300. llvm::StringRef Extension) {
  301. return createOutputFile(getFrontendOpts().OutputFile, Binary,
  302. InFile, Extension);
  303. }
  304. llvm::raw_fd_ostream *
  305. CompilerInstance::createOutputFile(llvm::StringRef OutputPath,
  306. bool Binary,
  307. llvm::StringRef InFile,
  308. llvm::StringRef Extension) {
  309. std::string Error, OutputPathName;
  310. llvm::raw_fd_ostream *OS = createOutputFile(OutputPath, Error, Binary,
  311. InFile, Extension,
  312. &OutputPathName);
  313. if (!OS) {
  314. getDiagnostics().Report(diag::err_fe_unable_to_open_output)
  315. << OutputPath << Error;
  316. return 0;
  317. }
  318. // Add the output file -- but don't try to remove "-", since this means we are
  319. // using stdin.
  320. addOutputFile((OutputPathName != "-") ? OutputPathName : "", OS);
  321. return OS;
  322. }
  323. llvm::raw_fd_ostream *
  324. CompilerInstance::createOutputFile(llvm::StringRef OutputPath,
  325. std::string &Error,
  326. bool Binary,
  327. llvm::StringRef InFile,
  328. llvm::StringRef Extension,
  329. std::string *ResultPathName) {
  330. std::string OutFile;
  331. if (!OutputPath.empty()) {
  332. OutFile = OutputPath;
  333. } else if (InFile == "-") {
  334. OutFile = "-";
  335. } else if (!Extension.empty()) {
  336. llvm::sys::Path Path(InFile);
  337. Path.eraseSuffix();
  338. Path.appendSuffix(Extension);
  339. OutFile = Path.str();
  340. } else {
  341. OutFile = "-";
  342. }
  343. llvm::OwningPtr<llvm::raw_fd_ostream> OS(
  344. new llvm::raw_fd_ostream(OutFile.c_str(), Error,
  345. (Binary ? llvm::raw_fd_ostream::F_Binary : 0)));
  346. if (!Error.empty())
  347. return 0;
  348. if (ResultPathName)
  349. *ResultPathName = OutFile;
  350. return OS.take();
  351. }
  352. // Initialization Utilities
  353. bool CompilerInstance::InitializeSourceManager(llvm::StringRef InputFile) {
  354. return InitializeSourceManager(InputFile, getDiagnostics(), getFileManager(),
  355. getSourceManager(), getFrontendOpts());
  356. }
  357. bool CompilerInstance::InitializeSourceManager(llvm::StringRef InputFile,
  358. Diagnostic &Diags,
  359. FileManager &FileMgr,
  360. SourceManager &SourceMgr,
  361. const FrontendOptions &Opts) {
  362. // Figure out where to get and map in the main file.
  363. if (InputFile != "-") {
  364. const FileEntry *File = FileMgr.getFile(InputFile);
  365. if (File) SourceMgr.createMainFileID(File, SourceLocation());
  366. if (SourceMgr.getMainFileID().isInvalid()) {
  367. Diags.Report(diag::err_fe_error_reading) << InputFile;
  368. return false;
  369. }
  370. } else {
  371. llvm::MemoryBuffer *SB = llvm::MemoryBuffer::getSTDIN();
  372. SourceMgr.createMainFileIDForMemBuffer(SB);
  373. if (SourceMgr.getMainFileID().isInvalid()) {
  374. Diags.Report(diag::err_fe_error_reading_stdin);
  375. return false;
  376. }
  377. }
  378. return true;
  379. }
  380. // High-Level Operations
  381. bool CompilerInstance::ExecuteAction(FrontendAction &Act) {
  382. assert(hasDiagnostics() && "Diagnostics engine is not initialized!");
  383. assert(!getFrontendOpts().ShowHelp && "Client must handle '-help'!");
  384. assert(!getFrontendOpts().ShowVersion && "Client must handle '-version'!");
  385. // FIXME: Take this as an argument, once all the APIs we used have moved to
  386. // taking it as an input instead of hard-coding llvm::errs.
  387. llvm::raw_ostream &OS = llvm::errs();
  388. // Create the target instance.
  389. setTarget(TargetInfo::CreateTargetInfo(getDiagnostics(), getTargetOpts()));
  390. if (!hasTarget())
  391. return false;
  392. // Inform the target of the language options.
  393. //
  394. // FIXME: We shouldn't need to do this, the target should be immutable once
  395. // created. This complexity should be lifted elsewhere.
  396. getTarget().setForcedLangOptions(getLangOpts());
  397. // Validate/process some options.
  398. if (getHeaderSearchOpts().Verbose)
  399. OS << "clang -cc1 version " CLANG_VERSION_STRING
  400. << " based upon " << PACKAGE_STRING
  401. << " hosted on " << llvm::sys::getHostTriple() << "\n";
  402. if (getFrontendOpts().ShowTimers)
  403. createFrontendTimer();
  404. if (getFrontendOpts().ShowStats)
  405. llvm::EnableStatistics();
  406. for (unsigned i = 0, e = getFrontendOpts().Inputs.size(); i != e; ++i) {
  407. const std::string &InFile = getFrontendOpts().Inputs[i].second;
  408. // If we aren't using an AST file, setup the file and source managers and
  409. // the preprocessor.
  410. bool IsAST = getFrontendOpts().Inputs[i].first == FrontendOptions::IK_AST;
  411. if (!IsAST) {
  412. if (!i) {
  413. // Create a file manager object to provide access to and cache the
  414. // filesystem.
  415. createFileManager();
  416. // Create the source manager.
  417. createSourceManager();
  418. } else {
  419. // Reset the ID tables if we are reusing the SourceManager.
  420. getSourceManager().clearIDTables();
  421. }
  422. // Create the preprocessor.
  423. createPreprocessor();
  424. }
  425. if (Act.BeginSourceFile(*this, InFile, IsAST)) {
  426. Act.Execute();
  427. Act.EndSourceFile();
  428. }
  429. }
  430. if (getDiagnosticOpts().ShowCarets)
  431. if (unsigned NumDiagnostics = getDiagnostics().getNumDiagnostics())
  432. OS << NumDiagnostics << " diagnostic"
  433. << (NumDiagnostics == 1 ? "" : "s")
  434. << " generated.\n";
  435. if (getFrontendOpts().ShowStats) {
  436. getFileManager().PrintStats();
  437. OS << "\n";
  438. }
  439. // Return the appropriate status when verifying diagnostics.
  440. //
  441. // FIXME: If we could make getNumErrors() do the right thing, we wouldn't need
  442. // this.
  443. if (getDiagnosticOpts().VerifyDiagnostics)
  444. return !static_cast<VerifyDiagnosticsClient&>(
  445. getDiagnosticClient()).HadErrors();
  446. return !getDiagnostics().getNumErrors();
  447. }