CompilerInstance.cpp 41 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110
  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/AST/Decl.h"
  14. #include "clang/Basic/Diagnostic.h"
  15. #include "clang/Basic/FileManager.h"
  16. #include "clang/Basic/SourceManager.h"
  17. #include "clang/Basic/TargetInfo.h"
  18. #include "clang/Basic/Version.h"
  19. #include "clang/Lex/HeaderSearch.h"
  20. #include "clang/Lex/Preprocessor.h"
  21. #include "clang/Lex/PTHManager.h"
  22. #include "clang/Frontend/ChainedDiagnosticConsumer.h"
  23. #include "clang/Frontend/FrontendAction.h"
  24. #include "clang/Frontend/FrontendActions.h"
  25. #include "clang/Frontend/FrontendDiagnostic.h"
  26. #include "clang/Frontend/LogDiagnosticPrinter.h"
  27. #include "clang/Frontend/SerializedDiagnosticPrinter.h"
  28. #include "clang/Frontend/TextDiagnosticPrinter.h"
  29. #include "clang/Frontend/VerifyDiagnosticConsumer.h"
  30. #include "clang/Frontend/Utils.h"
  31. #include "clang/Serialization/ASTReader.h"
  32. #include "clang/Sema/CodeCompleteConsumer.h"
  33. #include "llvm/Support/FileSystem.h"
  34. #include "llvm/Support/MemoryBuffer.h"
  35. #include "llvm/Support/raw_ostream.h"
  36. #include "llvm/ADT/Statistic.h"
  37. #include "llvm/Support/Timer.h"
  38. #include "llvm/Support/Host.h"
  39. #include "llvm/Support/LockFileManager.h"
  40. #include "llvm/Support/Path.h"
  41. #include "llvm/Support/Program.h"
  42. #include "llvm/Support/Signals.h"
  43. #include "llvm/Support/system_error.h"
  44. #include "llvm/Support/CrashRecoveryContext.h"
  45. #include "llvm/Config/config.h"
  46. using namespace clang;
  47. CompilerInstance::CompilerInstance()
  48. : Invocation(new CompilerInvocation()), ModuleManager(0) {
  49. }
  50. CompilerInstance::~CompilerInstance() {
  51. assert(OutputFiles.empty() && "Still output files in flight?");
  52. }
  53. void CompilerInstance::setInvocation(CompilerInvocation *Value) {
  54. Invocation = Value;
  55. }
  56. void CompilerInstance::setDiagnostics(DiagnosticsEngine *Value) {
  57. Diagnostics = Value;
  58. }
  59. void CompilerInstance::setTarget(TargetInfo *Value) {
  60. Target = Value;
  61. }
  62. void CompilerInstance::setFileManager(FileManager *Value) {
  63. FileMgr = Value;
  64. }
  65. void CompilerInstance::setSourceManager(SourceManager *Value) {
  66. SourceMgr = Value;
  67. }
  68. void CompilerInstance::setPreprocessor(Preprocessor *Value) { PP = Value; }
  69. void CompilerInstance::setASTContext(ASTContext *Value) { Context = Value; }
  70. void CompilerInstance::setSema(Sema *S) {
  71. TheSema.reset(S);
  72. }
  73. void CompilerInstance::setASTConsumer(ASTConsumer *Value) {
  74. Consumer.reset(Value);
  75. }
  76. void CompilerInstance::setCodeCompletionConsumer(CodeCompleteConsumer *Value) {
  77. CompletionConsumer.reset(Value);
  78. getFrontendOpts().SkipFunctionBodies = Value != 0;
  79. }
  80. // Diagnostics
  81. static void SetUpBuildDumpLog(DiagnosticOptions *DiagOpts,
  82. unsigned argc, const char* const *argv,
  83. DiagnosticsEngine &Diags) {
  84. std::string ErrorInfo;
  85. OwningPtr<raw_ostream> OS(
  86. new llvm::raw_fd_ostream(DiagOpts->DumpBuildInformation.c_str(),ErrorInfo));
  87. if (!ErrorInfo.empty()) {
  88. Diags.Report(diag::err_fe_unable_to_open_logfile)
  89. << DiagOpts->DumpBuildInformation << ErrorInfo;
  90. return;
  91. }
  92. (*OS) << "clang -cc1 command line arguments: ";
  93. for (unsigned i = 0; i != argc; ++i)
  94. (*OS) << argv[i] << ' ';
  95. (*OS) << '\n';
  96. // Chain in a diagnostic client which will log the diagnostics.
  97. DiagnosticConsumer *Logger =
  98. new TextDiagnosticPrinter(*OS.take(), DiagOpts, /*OwnsOutputStream=*/true);
  99. Diags.setClient(new ChainedDiagnosticConsumer(Diags.takeClient(), Logger));
  100. }
  101. static void SetUpDiagnosticLog(DiagnosticOptions *DiagOpts,
  102. const CodeGenOptions *CodeGenOpts,
  103. DiagnosticsEngine &Diags) {
  104. std::string ErrorInfo;
  105. bool OwnsStream = false;
  106. raw_ostream *OS = &llvm::errs();
  107. if (DiagOpts->DiagnosticLogFile != "-") {
  108. // Create the output stream.
  109. llvm::raw_fd_ostream *FileOS(
  110. new llvm::raw_fd_ostream(DiagOpts->DiagnosticLogFile.c_str(),
  111. ErrorInfo, llvm::raw_fd_ostream::F_Append));
  112. if (!ErrorInfo.empty()) {
  113. Diags.Report(diag::warn_fe_cc_log_diagnostics_failure)
  114. << DiagOpts->DumpBuildInformation << ErrorInfo;
  115. } else {
  116. FileOS->SetUnbuffered();
  117. FileOS->SetUseAtomicWrites(true);
  118. OS = FileOS;
  119. OwnsStream = true;
  120. }
  121. }
  122. // Chain in the diagnostic client which will log the diagnostics.
  123. LogDiagnosticPrinter *Logger = new LogDiagnosticPrinter(*OS, DiagOpts,
  124. OwnsStream);
  125. if (CodeGenOpts)
  126. Logger->setDwarfDebugFlags(CodeGenOpts->DwarfDebugFlags);
  127. Diags.setClient(new ChainedDiagnosticConsumer(Diags.takeClient(), Logger));
  128. }
  129. static void SetupSerializedDiagnostics(DiagnosticOptions *DiagOpts,
  130. DiagnosticsEngine &Diags,
  131. StringRef OutputFile) {
  132. std::string ErrorInfo;
  133. OwningPtr<llvm::raw_fd_ostream> OS;
  134. OS.reset(new llvm::raw_fd_ostream(OutputFile.str().c_str(), ErrorInfo,
  135. llvm::raw_fd_ostream::F_Binary));
  136. if (!ErrorInfo.empty()) {
  137. Diags.Report(diag::warn_fe_serialized_diag_failure)
  138. << OutputFile << ErrorInfo;
  139. return;
  140. }
  141. DiagnosticConsumer *SerializedConsumer =
  142. clang::serialized_diags::create(OS.take(), DiagOpts);
  143. Diags.setClient(new ChainedDiagnosticConsumer(Diags.takeClient(),
  144. SerializedConsumer));
  145. }
  146. void CompilerInstance::createDiagnostics(int Argc, const char* const *Argv,
  147. DiagnosticConsumer *Client,
  148. bool ShouldOwnClient,
  149. bool ShouldCloneClient) {
  150. Diagnostics = createDiagnostics(&getDiagnosticOpts(), Argc, Argv, Client,
  151. ShouldOwnClient, ShouldCloneClient,
  152. &getCodeGenOpts());
  153. }
  154. IntrusiveRefCntPtr<DiagnosticsEngine>
  155. CompilerInstance::createDiagnostics(DiagnosticOptions *Opts,
  156. int Argc, const char* const *Argv,
  157. DiagnosticConsumer *Client,
  158. bool ShouldOwnClient,
  159. bool ShouldCloneClient,
  160. const CodeGenOptions *CodeGenOpts) {
  161. IntrusiveRefCntPtr<DiagnosticIDs> DiagID(new DiagnosticIDs());
  162. IntrusiveRefCntPtr<DiagnosticsEngine>
  163. Diags(new DiagnosticsEngine(DiagID, Opts));
  164. // Create the diagnostic client for reporting errors or for
  165. // implementing -verify.
  166. if (Client) {
  167. if (ShouldCloneClient)
  168. Diags->setClient(Client->clone(*Diags), ShouldOwnClient);
  169. else
  170. Diags->setClient(Client, ShouldOwnClient);
  171. } else
  172. Diags->setClient(new TextDiagnosticPrinter(llvm::errs(), Opts));
  173. // Chain in -verify checker, if requested.
  174. if (Opts->VerifyDiagnostics)
  175. Diags->setClient(new VerifyDiagnosticConsumer(*Diags));
  176. // Chain in -diagnostic-log-file dumper, if requested.
  177. if (!Opts->DiagnosticLogFile.empty())
  178. SetUpDiagnosticLog(Opts, CodeGenOpts, *Diags);
  179. if (!Opts->DumpBuildInformation.empty())
  180. SetUpBuildDumpLog(Opts, Argc, Argv, *Diags);
  181. if (!Opts->DiagnosticSerializationFile.empty())
  182. SetupSerializedDiagnostics(Opts, *Diags,
  183. Opts->DiagnosticSerializationFile);
  184. // Configure our handling of diagnostics.
  185. ProcessWarningOptions(*Diags, *Opts);
  186. return Diags;
  187. }
  188. // File Manager
  189. void CompilerInstance::createFileManager() {
  190. FileMgr = new FileManager(getFileSystemOpts());
  191. }
  192. // Source Manager
  193. void CompilerInstance::createSourceManager(FileManager &FileMgr) {
  194. SourceMgr = new SourceManager(getDiagnostics(), FileMgr);
  195. }
  196. // Preprocessor
  197. void CompilerInstance::createPreprocessor() {
  198. const PreprocessorOptions &PPOpts = getPreprocessorOpts();
  199. // Create a PTH manager if we are using some form of a token cache.
  200. PTHManager *PTHMgr = 0;
  201. if (!PPOpts.TokenCache.empty())
  202. PTHMgr = PTHManager::Create(PPOpts.TokenCache, getDiagnostics());
  203. // Create the Preprocessor.
  204. HeaderSearch *HeaderInfo = new HeaderSearch(&getHeaderSearchOpts(),
  205. getFileManager(),
  206. getDiagnostics(),
  207. getLangOpts(),
  208. &getTarget());
  209. PP = new Preprocessor(&getPreprocessorOpts(),
  210. getDiagnostics(), getLangOpts(), &getTarget(),
  211. getSourceManager(), *HeaderInfo, *this, PTHMgr,
  212. /*OwnsHeaderSearch=*/true);
  213. // Note that this is different then passing PTHMgr to Preprocessor's ctor.
  214. // That argument is used as the IdentifierInfoLookup argument to
  215. // IdentifierTable's ctor.
  216. if (PTHMgr) {
  217. PTHMgr->setPreprocessor(&*PP);
  218. PP->setPTHManager(PTHMgr);
  219. }
  220. if (PPOpts.DetailedRecord)
  221. PP->createPreprocessingRecord(PPOpts.DetailedRecordConditionalDirectives);
  222. InitializePreprocessor(*PP, PPOpts, getHeaderSearchOpts(), getFrontendOpts());
  223. // Set up the module path, including the hash for the
  224. // module-creation options.
  225. SmallString<256> SpecificModuleCache(
  226. getHeaderSearchOpts().ModuleCachePath);
  227. if (!getHeaderSearchOpts().DisableModuleHash)
  228. llvm::sys::path::append(SpecificModuleCache,
  229. getInvocation().getModuleHash());
  230. PP->getHeaderSearchInfo().setModuleCachePath(SpecificModuleCache);
  231. // Handle generating dependencies, if requested.
  232. const DependencyOutputOptions &DepOpts = getDependencyOutputOpts();
  233. if (!DepOpts.OutputFile.empty())
  234. AttachDependencyFileGen(*PP, DepOpts);
  235. if (!DepOpts.DOTOutputFile.empty())
  236. AttachDependencyGraphGen(*PP, DepOpts.DOTOutputFile,
  237. getHeaderSearchOpts().Sysroot);
  238. // Handle generating header include information, if requested.
  239. if (DepOpts.ShowHeaderIncludes)
  240. AttachHeaderIncludeGen(*PP);
  241. if (!DepOpts.HeaderIncludeOutputFile.empty()) {
  242. StringRef OutputPath = DepOpts.HeaderIncludeOutputFile;
  243. if (OutputPath == "-")
  244. OutputPath = "";
  245. AttachHeaderIncludeGen(*PP, /*ShowAllHeaders=*/true, OutputPath,
  246. /*ShowDepth=*/false);
  247. }
  248. }
  249. // ASTContext
  250. void CompilerInstance::createASTContext() {
  251. Preprocessor &PP = getPreprocessor();
  252. Context = new ASTContext(getLangOpts(), PP.getSourceManager(),
  253. &getTarget(), PP.getIdentifierTable(),
  254. PP.getSelectorTable(), PP.getBuiltinInfo(),
  255. /*size_reserve=*/ 0);
  256. }
  257. // ExternalASTSource
  258. void CompilerInstance::createPCHExternalASTSource(StringRef Path,
  259. bool DisablePCHValidation,
  260. bool DisableStatCache,
  261. bool AllowPCHWithCompilerErrors,
  262. void *DeserializationListener){
  263. OwningPtr<ExternalASTSource> Source;
  264. bool Preamble = getPreprocessorOpts().PrecompiledPreambleBytes.first != 0;
  265. Source.reset(createPCHExternalASTSource(Path, getHeaderSearchOpts().Sysroot,
  266. DisablePCHValidation,
  267. DisableStatCache,
  268. AllowPCHWithCompilerErrors,
  269. getPreprocessor(), getASTContext(),
  270. DeserializationListener,
  271. Preamble));
  272. ModuleManager = static_cast<ASTReader*>(Source.get());
  273. getASTContext().setExternalSource(Source);
  274. }
  275. ExternalASTSource *
  276. CompilerInstance::createPCHExternalASTSource(StringRef Path,
  277. const std::string &Sysroot,
  278. bool DisablePCHValidation,
  279. bool DisableStatCache,
  280. bool AllowPCHWithCompilerErrors,
  281. Preprocessor &PP,
  282. ASTContext &Context,
  283. void *DeserializationListener,
  284. bool Preamble) {
  285. OwningPtr<ASTReader> Reader;
  286. Reader.reset(new ASTReader(PP, Context,
  287. Sysroot.empty() ? "" : Sysroot.c_str(),
  288. DisablePCHValidation, DisableStatCache,
  289. AllowPCHWithCompilerErrors));
  290. Reader->setDeserializationListener(
  291. static_cast<ASTDeserializationListener *>(DeserializationListener));
  292. switch (Reader->ReadAST(Path,
  293. Preamble ? serialization::MK_Preamble
  294. : serialization::MK_PCH,
  295. ASTReader::ARR_None)) {
  296. case ASTReader::Success:
  297. // Set the predefines buffer as suggested by the PCH reader. Typically, the
  298. // predefines buffer will be empty.
  299. PP.setPredefines(Reader->getSuggestedPredefines());
  300. return Reader.take();
  301. case ASTReader::Failure:
  302. // Unrecoverable failure: don't even try to process the input file.
  303. break;
  304. case ASTReader::OutOfDate:
  305. case ASTReader::VersionMismatch:
  306. case ASTReader::ConfigurationMismatch:
  307. case ASTReader::HadErrors:
  308. // No suitable PCH file could be found. Return an error.
  309. break;
  310. }
  311. return 0;
  312. }
  313. // Code Completion
  314. static bool EnableCodeCompletion(Preprocessor &PP,
  315. const std::string &Filename,
  316. unsigned Line,
  317. unsigned Column) {
  318. // Tell the source manager to chop off the given file at a specific
  319. // line and column.
  320. const FileEntry *Entry = PP.getFileManager().getFile(Filename);
  321. if (!Entry) {
  322. PP.getDiagnostics().Report(diag::err_fe_invalid_code_complete_file)
  323. << Filename;
  324. return true;
  325. }
  326. // Truncate the named file at the given line/column.
  327. PP.SetCodeCompletionPoint(Entry, Line, Column);
  328. return false;
  329. }
  330. void CompilerInstance::createCodeCompletionConsumer() {
  331. const ParsedSourceLocation &Loc = getFrontendOpts().CodeCompletionAt;
  332. if (!CompletionConsumer) {
  333. setCodeCompletionConsumer(
  334. createCodeCompletionConsumer(getPreprocessor(),
  335. Loc.FileName, Loc.Line, Loc.Column,
  336. getFrontendOpts().CodeCompleteOpts,
  337. llvm::outs()));
  338. if (!CompletionConsumer)
  339. return;
  340. } else if (EnableCodeCompletion(getPreprocessor(), Loc.FileName,
  341. Loc.Line, Loc.Column)) {
  342. setCodeCompletionConsumer(0);
  343. return;
  344. }
  345. if (CompletionConsumer->isOutputBinary() &&
  346. llvm::sys::Program::ChangeStdoutToBinary()) {
  347. getPreprocessor().getDiagnostics().Report(diag::err_fe_stdout_binary);
  348. setCodeCompletionConsumer(0);
  349. }
  350. }
  351. void CompilerInstance::createFrontendTimer() {
  352. FrontendTimer.reset(new llvm::Timer("Clang front-end timer"));
  353. }
  354. CodeCompleteConsumer *
  355. CompilerInstance::createCodeCompletionConsumer(Preprocessor &PP,
  356. const std::string &Filename,
  357. unsigned Line,
  358. unsigned Column,
  359. const CodeCompleteOptions &Opts,
  360. raw_ostream &OS) {
  361. if (EnableCodeCompletion(PP, Filename, Line, Column))
  362. return 0;
  363. // Set up the creation routine for code-completion.
  364. return new PrintingCodeCompleteConsumer(Opts, OS);
  365. }
  366. void CompilerInstance::createSema(TranslationUnitKind TUKind,
  367. CodeCompleteConsumer *CompletionConsumer) {
  368. TheSema.reset(new Sema(getPreprocessor(), getASTContext(), getASTConsumer(),
  369. TUKind, CompletionConsumer));
  370. }
  371. // Output Files
  372. void CompilerInstance::addOutputFile(const OutputFile &OutFile) {
  373. assert(OutFile.OS && "Attempt to add empty stream to output list!");
  374. OutputFiles.push_back(OutFile);
  375. }
  376. void CompilerInstance::clearOutputFiles(bool EraseFiles) {
  377. for (std::list<OutputFile>::iterator
  378. it = OutputFiles.begin(), ie = OutputFiles.end(); it != ie; ++it) {
  379. delete it->OS;
  380. if (!it->TempFilename.empty()) {
  381. if (EraseFiles) {
  382. bool existed;
  383. llvm::sys::fs::remove(it->TempFilename, existed);
  384. } else {
  385. SmallString<128> NewOutFile(it->Filename);
  386. // If '-working-directory' was passed, the output filename should be
  387. // relative to that.
  388. FileMgr->FixupRelativePath(NewOutFile);
  389. if (llvm::error_code ec = llvm::sys::fs::rename(it->TempFilename,
  390. NewOutFile.str())) {
  391. getDiagnostics().Report(diag::err_unable_to_rename_temp)
  392. << it->TempFilename << it->Filename << ec.message();
  393. bool existed;
  394. llvm::sys::fs::remove(it->TempFilename, existed);
  395. }
  396. }
  397. } else if (!it->Filename.empty() && EraseFiles)
  398. llvm::sys::Path(it->Filename).eraseFromDisk();
  399. }
  400. OutputFiles.clear();
  401. }
  402. llvm::raw_fd_ostream *
  403. CompilerInstance::createDefaultOutputFile(bool Binary,
  404. StringRef InFile,
  405. StringRef Extension) {
  406. return createOutputFile(getFrontendOpts().OutputFile, Binary,
  407. /*RemoveFileOnSignal=*/true, InFile, Extension,
  408. /*UseTemporary=*/true);
  409. }
  410. llvm::raw_fd_ostream *
  411. CompilerInstance::createOutputFile(StringRef OutputPath,
  412. bool Binary, bool RemoveFileOnSignal,
  413. StringRef InFile,
  414. StringRef Extension,
  415. bool UseTemporary,
  416. bool CreateMissingDirectories) {
  417. std::string Error, OutputPathName, TempPathName;
  418. llvm::raw_fd_ostream *OS = createOutputFile(OutputPath, Error, Binary,
  419. RemoveFileOnSignal,
  420. InFile, Extension,
  421. UseTemporary,
  422. CreateMissingDirectories,
  423. &OutputPathName,
  424. &TempPathName);
  425. if (!OS) {
  426. getDiagnostics().Report(diag::err_fe_unable_to_open_output)
  427. << OutputPath << Error;
  428. return 0;
  429. }
  430. // Add the output file -- but don't try to remove "-", since this means we are
  431. // using stdin.
  432. addOutputFile(OutputFile((OutputPathName != "-") ? OutputPathName : "",
  433. TempPathName, OS));
  434. return OS;
  435. }
  436. llvm::raw_fd_ostream *
  437. CompilerInstance::createOutputFile(StringRef OutputPath,
  438. std::string &Error,
  439. bool Binary,
  440. bool RemoveFileOnSignal,
  441. StringRef InFile,
  442. StringRef Extension,
  443. bool UseTemporary,
  444. bool CreateMissingDirectories,
  445. std::string *ResultPathName,
  446. std::string *TempPathName) {
  447. assert((!CreateMissingDirectories || UseTemporary) &&
  448. "CreateMissingDirectories is only allowed when using temporary files");
  449. std::string OutFile, TempFile;
  450. if (!OutputPath.empty()) {
  451. OutFile = OutputPath;
  452. } else if (InFile == "-") {
  453. OutFile = "-";
  454. } else if (!Extension.empty()) {
  455. llvm::sys::Path Path(InFile);
  456. Path.eraseSuffix();
  457. Path.appendSuffix(Extension);
  458. OutFile = Path.str();
  459. } else {
  460. OutFile = "-";
  461. }
  462. OwningPtr<llvm::raw_fd_ostream> OS;
  463. std::string OSFile;
  464. if (UseTemporary && OutFile != "-") {
  465. // Only create the temporary if the parent directory exists (or create
  466. // missing directories is true) and we can actually write to OutPath,
  467. // otherwise we want to fail early.
  468. SmallString<256> AbsPath(OutputPath);
  469. llvm::sys::fs::make_absolute(AbsPath);
  470. llvm::sys::Path OutPath(AbsPath);
  471. bool ParentExists = false;
  472. if (llvm::sys::fs::exists(llvm::sys::path::parent_path(AbsPath.str()),
  473. ParentExists))
  474. ParentExists = false;
  475. bool Exists;
  476. if ((CreateMissingDirectories || ParentExists) &&
  477. ((llvm::sys::fs::exists(AbsPath.str(), Exists) || !Exists) ||
  478. (OutPath.isRegularFile() && OutPath.canWrite()))) {
  479. // Create a temporary file.
  480. SmallString<128> TempPath;
  481. TempPath = OutFile;
  482. TempPath += "-%%%%%%%%";
  483. int fd;
  484. if (llvm::sys::fs::unique_file(TempPath.str(), fd, TempPath,
  485. /*makeAbsolute=*/false, 0664)
  486. == llvm::errc::success) {
  487. OS.reset(new llvm::raw_fd_ostream(fd, /*shouldClose=*/true));
  488. OSFile = TempFile = TempPath.str();
  489. }
  490. }
  491. }
  492. if (!OS) {
  493. OSFile = OutFile;
  494. OS.reset(
  495. new llvm::raw_fd_ostream(OSFile.c_str(), Error,
  496. (Binary ? llvm::raw_fd_ostream::F_Binary : 0)));
  497. if (!Error.empty())
  498. return 0;
  499. }
  500. // Make sure the out stream file gets removed if we crash.
  501. if (RemoveFileOnSignal)
  502. llvm::sys::RemoveFileOnSignal(llvm::sys::Path(OSFile));
  503. if (ResultPathName)
  504. *ResultPathName = OutFile;
  505. if (TempPathName)
  506. *TempPathName = TempFile;
  507. return OS.take();
  508. }
  509. // Initialization Utilities
  510. bool CompilerInstance::InitializeSourceManager(StringRef InputFile,
  511. SrcMgr::CharacteristicKind Kind){
  512. return InitializeSourceManager(InputFile, Kind, getDiagnostics(),
  513. getFileManager(), getSourceManager(),
  514. getFrontendOpts());
  515. }
  516. bool CompilerInstance::InitializeSourceManager(StringRef InputFile,
  517. SrcMgr::CharacteristicKind Kind,
  518. DiagnosticsEngine &Diags,
  519. FileManager &FileMgr,
  520. SourceManager &SourceMgr,
  521. const FrontendOptions &Opts) {
  522. // Figure out where to get and map in the main file.
  523. if (InputFile != "-") {
  524. const FileEntry *File = FileMgr.getFile(InputFile);
  525. if (!File) {
  526. Diags.Report(diag::err_fe_error_reading) << InputFile;
  527. return false;
  528. }
  529. SourceMgr.createMainFileID(File, Kind);
  530. } else {
  531. OwningPtr<llvm::MemoryBuffer> SB;
  532. if (llvm::MemoryBuffer::getSTDIN(SB)) {
  533. // FIXME: Give ec.message() in this diag.
  534. Diags.Report(diag::err_fe_error_reading_stdin);
  535. return false;
  536. }
  537. const FileEntry *File = FileMgr.getVirtualFile(SB->getBufferIdentifier(),
  538. SB->getBufferSize(), 0);
  539. SourceMgr.createMainFileID(File, Kind);
  540. SourceMgr.overrideFileContents(File, SB.take());
  541. }
  542. assert(!SourceMgr.getMainFileID().isInvalid() &&
  543. "Couldn't establish MainFileID!");
  544. return true;
  545. }
  546. // High-Level Operations
  547. bool CompilerInstance::ExecuteAction(FrontendAction &Act) {
  548. assert(hasDiagnostics() && "Diagnostics engine is not initialized!");
  549. assert(!getFrontendOpts().ShowHelp && "Client must handle '-help'!");
  550. assert(!getFrontendOpts().ShowVersion && "Client must handle '-version'!");
  551. // FIXME: Take this as an argument, once all the APIs we used have moved to
  552. // taking it as an input instead of hard-coding llvm::errs.
  553. raw_ostream &OS = llvm::errs();
  554. // Create the target instance.
  555. setTarget(TargetInfo::CreateTargetInfo(getDiagnostics(), getTargetOpts()));
  556. if (!hasTarget())
  557. return false;
  558. // Inform the target of the language options.
  559. //
  560. // FIXME: We shouldn't need to do this, the target should be immutable once
  561. // created. This complexity should be lifted elsewhere.
  562. getTarget().setForcedLangOptions(getLangOpts());
  563. // rewriter project will change target built-in bool type from its default.
  564. if (getFrontendOpts().ProgramAction == frontend::RewriteObjC)
  565. getTarget().noSignedCharForObjCBool();
  566. // Validate/process some options.
  567. if (getHeaderSearchOpts().Verbose)
  568. OS << "clang -cc1 version " CLANG_VERSION_STRING
  569. << " based upon " << PACKAGE_STRING
  570. << " default target " << llvm::sys::getDefaultTargetTriple() << "\n";
  571. if (getFrontendOpts().ShowTimers)
  572. createFrontendTimer();
  573. if (getFrontendOpts().ShowStats)
  574. llvm::EnableStatistics();
  575. for (unsigned i = 0, e = getFrontendOpts().Inputs.size(); i != e; ++i) {
  576. // Reset the ID tables if we are reusing the SourceManager.
  577. if (hasSourceManager())
  578. getSourceManager().clearIDTables();
  579. if (Act.BeginSourceFile(*this, getFrontendOpts().Inputs[i])) {
  580. Act.Execute();
  581. Act.EndSourceFile();
  582. }
  583. }
  584. // Notify the diagnostic client that all files were processed.
  585. getDiagnostics().getClient()->finish();
  586. if (getDiagnosticOpts().ShowCarets) {
  587. // We can have multiple diagnostics sharing one diagnostic client.
  588. // Get the total number of warnings/errors from the client.
  589. unsigned NumWarnings = getDiagnostics().getClient()->getNumWarnings();
  590. unsigned NumErrors = getDiagnostics().getClient()->getNumErrors();
  591. if (NumWarnings)
  592. OS << NumWarnings << " warning" << (NumWarnings == 1 ? "" : "s");
  593. if (NumWarnings && NumErrors)
  594. OS << " and ";
  595. if (NumErrors)
  596. OS << NumErrors << " error" << (NumErrors == 1 ? "" : "s");
  597. if (NumWarnings || NumErrors)
  598. OS << " generated.\n";
  599. }
  600. if (getFrontendOpts().ShowStats && hasFileManager()) {
  601. getFileManager().PrintStats();
  602. OS << "\n";
  603. }
  604. return !getDiagnostics().getClient()->getNumErrors();
  605. }
  606. /// \brief Determine the appropriate source input kind based on language
  607. /// options.
  608. static InputKind getSourceInputKindFromOptions(const LangOptions &LangOpts) {
  609. if (LangOpts.OpenCL)
  610. return IK_OpenCL;
  611. if (LangOpts.CUDA)
  612. return IK_CUDA;
  613. if (LangOpts.ObjC1)
  614. return LangOpts.CPlusPlus? IK_ObjCXX : IK_ObjC;
  615. return LangOpts.CPlusPlus? IK_CXX : IK_C;
  616. }
  617. namespace {
  618. struct CompileModuleMapData {
  619. CompilerInstance &Instance;
  620. GenerateModuleAction &CreateModuleAction;
  621. };
  622. }
  623. /// \brief Helper function that executes the module-generating action under
  624. /// a crash recovery context.
  625. static void doCompileMapModule(void *UserData) {
  626. CompileModuleMapData &Data
  627. = *reinterpret_cast<CompileModuleMapData *>(UserData);
  628. Data.Instance.ExecuteAction(Data.CreateModuleAction);
  629. }
  630. /// \brief Compile a module file for the given module, using the options
  631. /// provided by the importing compiler instance.
  632. static void compileModule(CompilerInstance &ImportingInstance,
  633. Module *Module,
  634. StringRef ModuleFileName) {
  635. llvm::LockFileManager Locked(ModuleFileName);
  636. switch (Locked) {
  637. case llvm::LockFileManager::LFS_Error:
  638. return;
  639. case llvm::LockFileManager::LFS_Owned:
  640. // We're responsible for building the module ourselves. Do so below.
  641. break;
  642. case llvm::LockFileManager::LFS_Shared:
  643. // Someone else is responsible for building the module. Wait for them to
  644. // finish.
  645. Locked.waitForUnlock();
  646. break;
  647. }
  648. ModuleMap &ModMap
  649. = ImportingInstance.getPreprocessor().getHeaderSearchInfo().getModuleMap();
  650. // Construct a compiler invocation for creating this module.
  651. IntrusiveRefCntPtr<CompilerInvocation> Invocation
  652. (new CompilerInvocation(ImportingInstance.getInvocation()));
  653. PreprocessorOptions &PPOpts = Invocation->getPreprocessorOpts();
  654. // For any options that aren't intended to affect how a module is built,
  655. // reset them to their default values.
  656. Invocation->getLangOpts()->resetNonModularOptions();
  657. PPOpts.resetNonModularOptions();
  658. // Note the name of the module we're building.
  659. Invocation->getLangOpts()->CurrentModule = Module->getTopLevelModuleName();
  660. // Note that this module is part of the module build path, so that we
  661. // can detect cycles in the module graph.
  662. PPOpts.ModuleBuildPath.push_back(Module->getTopLevelModuleName());
  663. // If there is a module map file, build the module using the module map.
  664. // Set up the inputs/outputs so that we build the module from its umbrella
  665. // header.
  666. FrontendOptions &FrontendOpts = Invocation->getFrontendOpts();
  667. FrontendOpts.OutputFile = ModuleFileName.str();
  668. FrontendOpts.DisableFree = false;
  669. FrontendOpts.Inputs.clear();
  670. InputKind IK = getSourceInputKindFromOptions(*Invocation->getLangOpts());
  671. // Get or create the module map that we'll use to build this module.
  672. SmallString<128> TempModuleMapFileName;
  673. if (const FileEntry *ModuleMapFile
  674. = ModMap.getContainingModuleMapFile(Module)) {
  675. // Use the module map where this module resides.
  676. FrontendOpts.Inputs.push_back(FrontendInputFile(ModuleMapFile->getName(),
  677. IK));
  678. } else {
  679. // Create a temporary module map file.
  680. TempModuleMapFileName = Module->Name;
  681. TempModuleMapFileName += "-%%%%%%%%.map";
  682. int FD;
  683. if (llvm::sys::fs::unique_file(TempModuleMapFileName.str(), FD,
  684. TempModuleMapFileName,
  685. /*makeAbsolute=*/true)
  686. != llvm::errc::success) {
  687. ImportingInstance.getDiagnostics().Report(diag::err_module_map_temp_file)
  688. << TempModuleMapFileName;
  689. return;
  690. }
  691. // Print the module map to this file.
  692. llvm::raw_fd_ostream OS(FD, /*shouldClose=*/true);
  693. Module->print(OS);
  694. FrontendOpts.Inputs.push_back(
  695. FrontendInputFile(TempModuleMapFileName.str().str(), IK));
  696. }
  697. // Don't free the remapped file buffers; they are owned by our caller.
  698. PPOpts.RetainRemappedFileBuffers = true;
  699. Invocation->getDiagnosticOpts().VerifyDiagnostics = 0;
  700. assert(ImportingInstance.getInvocation().getModuleHash() ==
  701. Invocation->getModuleHash() && "Module hash mismatch!");
  702. // Construct a compiler instance that will be used to actually create the
  703. // module.
  704. CompilerInstance Instance;
  705. Instance.setInvocation(&*Invocation);
  706. Instance.createDiagnostics(/*argc=*/0, /*argv=*/0,
  707. &ImportingInstance.getDiagnosticClient(),
  708. /*ShouldOwnClient=*/true,
  709. /*ShouldCloneClient=*/true);
  710. // Construct a module-generating action.
  711. GenerateModuleAction CreateModuleAction;
  712. // Execute the action to actually build the module in-place. Use a separate
  713. // thread so that we get a stack large enough.
  714. const unsigned ThreadStackSize = 8 << 20;
  715. llvm::CrashRecoveryContext CRC;
  716. CompileModuleMapData Data = { Instance, CreateModuleAction };
  717. CRC.RunSafelyOnThread(&doCompileMapModule, &Data, ThreadStackSize);
  718. // Delete the temporary module map file.
  719. // FIXME: Even though we're executing under crash protection, it would still
  720. // be nice to do this with RemoveFileOnSignal when we can. However, that
  721. // doesn't make sense for all clients, so clean this up manually.
  722. Instance.clearOutputFiles(/*EraseFiles=*/true);
  723. if (!TempModuleMapFileName.empty())
  724. llvm::sys::Path(TempModuleMapFileName).eraseFromDisk();
  725. }
  726. Module *CompilerInstance::loadModule(SourceLocation ImportLoc,
  727. ModuleIdPath Path,
  728. Module::NameVisibilityKind Visibility,
  729. bool IsInclusionDirective) {
  730. // If we've already handled this import, just return the cached result.
  731. // This one-element cache is important to eliminate redundant diagnostics
  732. // when both the preprocessor and parser see the same import declaration.
  733. if (!ImportLoc.isInvalid() && LastModuleImportLoc == ImportLoc) {
  734. // Make the named module visible.
  735. if (LastModuleImportResult)
  736. ModuleManager->makeModuleVisible(LastModuleImportResult, Visibility);
  737. return LastModuleImportResult;
  738. }
  739. // Determine what file we're searching from.
  740. StringRef ModuleName = Path[0].first->getName();
  741. SourceLocation ModuleNameLoc = Path[0].second;
  742. clang::Module *Module = 0;
  743. // If we don't already have information on this module, load the module now.
  744. llvm::DenseMap<const IdentifierInfo *, clang::Module *>::iterator Known
  745. = KnownModules.find(Path[0].first);
  746. if (Known != KnownModules.end()) {
  747. // Retrieve the cached top-level module.
  748. Module = Known->second;
  749. } else if (ModuleName == getLangOpts().CurrentModule) {
  750. // This is the module we're building.
  751. Module = PP->getHeaderSearchInfo().getModuleMap().findModule(ModuleName);
  752. Known = KnownModules.insert(std::make_pair(Path[0].first, Module)).first;
  753. } else {
  754. // Search for a module with the given name.
  755. Module = PP->getHeaderSearchInfo().lookupModule(ModuleName);
  756. std::string ModuleFileName;
  757. if (Module)
  758. ModuleFileName = PP->getHeaderSearchInfo().getModuleFileName(Module);
  759. else
  760. ModuleFileName = PP->getHeaderSearchInfo().getModuleFileName(ModuleName);
  761. if (ModuleFileName.empty()) {
  762. getDiagnostics().Report(ModuleNameLoc, diag::err_module_not_found)
  763. << ModuleName
  764. << SourceRange(ImportLoc, ModuleNameLoc);
  765. LastModuleImportLoc = ImportLoc;
  766. LastModuleImportResult = 0;
  767. return 0;
  768. }
  769. const FileEntry *ModuleFile
  770. = getFileManager().getFile(ModuleFileName, /*OpenFile=*/false,
  771. /*CacheFailure=*/false);
  772. bool BuildingModule = false;
  773. if (!ModuleFile && Module) {
  774. // The module is not cached, but we have a module map from which we can
  775. // build the module.
  776. // Check whether there is a cycle in the module graph.
  777. SmallVectorImpl<std::string> &ModuleBuildPath
  778. = getPreprocessorOpts().ModuleBuildPath;
  779. SmallVectorImpl<std::string>::iterator Pos
  780. = std::find(ModuleBuildPath.begin(), ModuleBuildPath.end(), ModuleName);
  781. if (Pos != ModuleBuildPath.end()) {
  782. SmallString<256> CyclePath;
  783. for (; Pos != ModuleBuildPath.end(); ++Pos) {
  784. CyclePath += *Pos;
  785. CyclePath += " -> ";
  786. }
  787. CyclePath += ModuleName;
  788. getDiagnostics().Report(ModuleNameLoc, diag::err_module_cycle)
  789. << ModuleName << CyclePath;
  790. return 0;
  791. }
  792. getDiagnostics().Report(ModuleNameLoc, diag::warn_module_build)
  793. << ModuleName;
  794. BuildingModule = true;
  795. compileModule(*this, Module, ModuleFileName);
  796. ModuleFile = FileMgr->getFile(ModuleFileName);
  797. }
  798. if (!ModuleFile) {
  799. getDiagnostics().Report(ModuleNameLoc,
  800. BuildingModule? diag::err_module_not_built
  801. : diag::err_module_not_found)
  802. << ModuleName
  803. << SourceRange(ImportLoc, ModuleNameLoc);
  804. return 0;
  805. }
  806. // If we don't already have an ASTReader, create one now.
  807. if (!ModuleManager) {
  808. if (!hasASTContext())
  809. createASTContext();
  810. std::string Sysroot = getHeaderSearchOpts().Sysroot;
  811. const PreprocessorOptions &PPOpts = getPreprocessorOpts();
  812. ModuleManager = new ASTReader(getPreprocessor(), *Context,
  813. Sysroot.empty() ? "" : Sysroot.c_str(),
  814. PPOpts.DisablePCHValidation,
  815. PPOpts.DisableStatCache);
  816. if (hasASTConsumer()) {
  817. ModuleManager->setDeserializationListener(
  818. getASTConsumer().GetASTDeserializationListener());
  819. getASTContext().setASTMutationListener(
  820. getASTConsumer().GetASTMutationListener());
  821. getPreprocessor().setPPMutationListener(
  822. getASTConsumer().GetPPMutationListener());
  823. }
  824. OwningPtr<ExternalASTSource> Source;
  825. Source.reset(ModuleManager);
  826. getASTContext().setExternalSource(Source);
  827. if (hasSema())
  828. ModuleManager->InitializeSema(getSema());
  829. if (hasASTConsumer())
  830. ModuleManager->StartTranslationUnit(&getASTConsumer());
  831. }
  832. // Try to load the module we found.
  833. switch (ModuleManager->ReadAST(ModuleFile->getName(),
  834. serialization::MK_Module,
  835. ASTReader::ARR_None)) {
  836. case ASTReader::Success:
  837. break;
  838. case ASTReader::OutOfDate:
  839. case ASTReader::VersionMismatch:
  840. case ASTReader::ConfigurationMismatch:
  841. case ASTReader::HadErrors:
  842. // FIXME: The ASTReader will already have complained, but can we showhorn
  843. // that diagnostic information into a more useful form?
  844. KnownModules[Path[0].first] = 0;
  845. return 0;
  846. case ASTReader::Failure:
  847. // Already complained, but note now that we failed.
  848. KnownModules[Path[0].first] = 0;
  849. return 0;
  850. }
  851. if (!Module) {
  852. // If we loaded the module directly, without finding a module map first,
  853. // we'll have loaded the module's information from the module itself.
  854. Module = PP->getHeaderSearchInfo().getModuleMap()
  855. .findModule((Path[0].first->getName()));
  856. }
  857. if (Module)
  858. Module->setASTFile(ModuleFile);
  859. // Cache the result of this top-level module lookup for later.
  860. Known = KnownModules.insert(std::make_pair(Path[0].first, Module)).first;
  861. }
  862. // If we never found the module, fail.
  863. if (!Module)
  864. return 0;
  865. // Verify that the rest of the module path actually corresponds to
  866. // a submodule.
  867. if (Path.size() > 1) {
  868. for (unsigned I = 1, N = Path.size(); I != N; ++I) {
  869. StringRef Name = Path[I].first->getName();
  870. clang::Module *Sub = Module->findSubmodule(Name);
  871. if (!Sub) {
  872. // Attempt to perform typo correction to find a module name that works.
  873. llvm::SmallVector<StringRef, 2> Best;
  874. unsigned BestEditDistance = (std::numeric_limits<unsigned>::max)();
  875. for (clang::Module::submodule_iterator J = Module->submodule_begin(),
  876. JEnd = Module->submodule_end();
  877. J != JEnd; ++J) {
  878. unsigned ED = Name.edit_distance((*J)->Name,
  879. /*AllowReplacements=*/true,
  880. BestEditDistance);
  881. if (ED <= BestEditDistance) {
  882. if (ED < BestEditDistance) {
  883. Best.clear();
  884. BestEditDistance = ED;
  885. }
  886. Best.push_back((*J)->Name);
  887. }
  888. }
  889. // If there was a clear winner, user it.
  890. if (Best.size() == 1) {
  891. getDiagnostics().Report(Path[I].second,
  892. diag::err_no_submodule_suggest)
  893. << Path[I].first << Module->getFullModuleName() << Best[0]
  894. << SourceRange(Path[0].second, Path[I-1].second)
  895. << FixItHint::CreateReplacement(SourceRange(Path[I].second),
  896. Best[0]);
  897. Sub = Module->findSubmodule(Best[0]);
  898. }
  899. }
  900. if (!Sub) {
  901. // No submodule by this name. Complain, and don't look for further
  902. // submodules.
  903. getDiagnostics().Report(Path[I].second, diag::err_no_submodule)
  904. << Path[I].first << Module->getFullModuleName()
  905. << SourceRange(Path[0].second, Path[I-1].second);
  906. break;
  907. }
  908. Module = Sub;
  909. }
  910. }
  911. // Make the named module visible, if it's not already part of the module
  912. // we are parsing.
  913. if (ModuleName != getLangOpts().CurrentModule) {
  914. if (!Module->IsFromModuleFile) {
  915. // We have an umbrella header or directory that doesn't actually include
  916. // all of the headers within the directory it covers. Complain about
  917. // this missing submodule and recover by forgetting that we ever saw
  918. // this submodule.
  919. // FIXME: Should we detect this at module load time? It seems fairly
  920. // expensive (and rare).
  921. getDiagnostics().Report(ImportLoc, diag::warn_missing_submodule)
  922. << Module->getFullModuleName()
  923. << SourceRange(Path.front().second, Path.back().second);
  924. return 0;
  925. }
  926. // Check whether this module is available.
  927. StringRef Feature;
  928. if (!Module->isAvailable(getLangOpts(), getTarget(), Feature)) {
  929. getDiagnostics().Report(ImportLoc, diag::err_module_unavailable)
  930. << Module->getFullModuleName()
  931. << Feature
  932. << SourceRange(Path.front().second, Path.back().second);
  933. LastModuleImportLoc = ImportLoc;
  934. LastModuleImportResult = 0;
  935. return 0;
  936. }
  937. ModuleManager->makeModuleVisible(Module, Visibility);
  938. }
  939. // If this module import was due to an inclusion directive, create an
  940. // implicit import declaration to capture it in the AST.
  941. if (IsInclusionDirective && hasASTContext()) {
  942. TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl();
  943. ImportDecl *ImportD = ImportDecl::CreateImplicit(getASTContext(), TU,
  944. ImportLoc, Module,
  945. Path.back().second);
  946. TU->addDecl(ImportD);
  947. if (Consumer)
  948. Consumer->HandleImplicitImportDecl(ImportD);
  949. }
  950. LastModuleImportLoc = ImportLoc;
  951. LastModuleImportResult = Module;
  952. return Module;
  953. }