CompilerInstance.cpp 56 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494
  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/AST/Decl.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/Frontend/ChainedDiagnosticConsumer.h"
  19. #include "clang/Frontend/FrontendAction.h"
  20. #include "clang/Frontend/FrontendActions.h"
  21. #include "clang/Frontend/FrontendDiagnostic.h"
  22. #include "clang/Frontend/LogDiagnosticPrinter.h"
  23. #include "clang/Frontend/SerializedDiagnosticPrinter.h"
  24. #include "clang/Frontend/TextDiagnosticPrinter.h"
  25. #include "clang/Frontend/Utils.h"
  26. #include "clang/Frontend/VerifyDiagnosticConsumer.h"
  27. #include "clang/Lex/HeaderSearch.h"
  28. #include "clang/Lex/PTHManager.h"
  29. #include "clang/Lex/Preprocessor.h"
  30. #include "clang/Sema/CodeCompleteConsumer.h"
  31. #include "clang/Sema/Sema.h"
  32. #include "clang/Serialization/ASTReader.h"
  33. #include "clang/Serialization/GlobalModuleIndex.h"
  34. #include "llvm/ADT/Statistic.h"
  35. #include "llvm/Config/config.h"
  36. #include "llvm/Support/CrashRecoveryContext.h"
  37. #include "llvm/Support/FileSystem.h"
  38. #include "llvm/Support/Host.h"
  39. #include "llvm/Support/LockFileManager.h"
  40. #include "llvm/Support/MemoryBuffer.h"
  41. #include "llvm/Support/Path.h"
  42. #include "llvm/Support/Program.h"
  43. #include "llvm/Support/Signals.h"
  44. #include "llvm/Support/Timer.h"
  45. #include "llvm/Support/raw_ostream.h"
  46. #include "llvm/Support/system_error.h"
  47. #include <sys/stat.h>
  48. #include <time.h>
  49. using namespace clang;
  50. CompilerInstance::CompilerInstance(bool BuildingModule)
  51. : ModuleLoader(BuildingModule),
  52. Invocation(new CompilerInvocation()), ModuleManager(0),
  53. BuildGlobalModuleIndex(false), HaveFullGlobalModuleIndex(false),
  54. ModuleBuildFailed(false) {
  55. }
  56. CompilerInstance::~CompilerInstance() {
  57. assert(OutputFiles.empty() && "Still output files in flight?");
  58. }
  59. void CompilerInstance::setInvocation(CompilerInvocation *Value) {
  60. Invocation = Value;
  61. }
  62. bool CompilerInstance::shouldBuildGlobalModuleIndex() const {
  63. return (BuildGlobalModuleIndex ||
  64. (ModuleManager && ModuleManager->isGlobalIndexUnavailable() &&
  65. getFrontendOpts().GenerateGlobalModuleIndex)) &&
  66. !ModuleBuildFailed;
  67. }
  68. void CompilerInstance::setDiagnostics(DiagnosticsEngine *Value) {
  69. Diagnostics = Value;
  70. }
  71. void CompilerInstance::setTarget(TargetInfo *Value) {
  72. Target = Value;
  73. }
  74. void CompilerInstance::setFileManager(FileManager *Value) {
  75. FileMgr = Value;
  76. if (Value)
  77. VirtualFileSystem = Value->getVirtualFileSystem();
  78. else
  79. VirtualFileSystem.reset();
  80. }
  81. void CompilerInstance::setSourceManager(SourceManager *Value) {
  82. SourceMgr = Value;
  83. }
  84. void CompilerInstance::setPreprocessor(Preprocessor *Value) { PP = Value; }
  85. void CompilerInstance::setASTContext(ASTContext *Value) { Context = Value; }
  86. void CompilerInstance::setSema(Sema *S) {
  87. TheSema.reset(S);
  88. }
  89. void CompilerInstance::setASTConsumer(ASTConsumer *Value) {
  90. Consumer.reset(Value);
  91. }
  92. void CompilerInstance::setCodeCompletionConsumer(CodeCompleteConsumer *Value) {
  93. CompletionConsumer.reset(Value);
  94. }
  95. IntrusiveRefCntPtr<ASTReader> CompilerInstance::getModuleManager() const {
  96. return ModuleManager;
  97. }
  98. void CompilerInstance::setModuleManager(IntrusiveRefCntPtr<ASTReader> Reader) {
  99. ModuleManager = Reader;
  100. }
  101. // Diagnostics
  102. static void SetUpDiagnosticLog(DiagnosticOptions *DiagOpts,
  103. const CodeGenOptions *CodeGenOpts,
  104. DiagnosticsEngine &Diags) {
  105. std::string ErrorInfo;
  106. bool OwnsStream = false;
  107. raw_ostream *OS = &llvm::errs();
  108. if (DiagOpts->DiagnosticLogFile != "-") {
  109. // Create the output stream.
  110. llvm::raw_fd_ostream *FileOS(new llvm::raw_fd_ostream(
  111. DiagOpts->DiagnosticLogFile.c_str(), ErrorInfo,
  112. llvm::sys::fs::F_Append | llvm::sys::fs::F_Text));
  113. if (!ErrorInfo.empty()) {
  114. Diags.Report(diag::warn_fe_cc_log_diagnostics_failure)
  115. << DiagOpts->DiagnosticLogFile << ErrorInfo;
  116. } else {
  117. FileOS->SetUnbuffered();
  118. FileOS->SetUseAtomicWrites(true);
  119. OS = FileOS;
  120. OwnsStream = true;
  121. }
  122. }
  123. // Chain in the diagnostic client which will log the diagnostics.
  124. LogDiagnosticPrinter *Logger = new LogDiagnosticPrinter(*OS, DiagOpts,
  125. OwnsStream);
  126. if (CodeGenOpts)
  127. Logger->setDwarfDebugFlags(CodeGenOpts->DwarfDebugFlags);
  128. Diags.setClient(new ChainedDiagnosticConsumer(Diags.takeClient(), Logger));
  129. }
  130. static void SetupSerializedDiagnostics(DiagnosticOptions *DiagOpts,
  131. DiagnosticsEngine &Diags,
  132. StringRef OutputFile) {
  133. std::string ErrorInfo;
  134. std::unique_ptr<llvm::raw_fd_ostream> OS;
  135. OS.reset(new llvm::raw_fd_ostream(OutputFile.str().c_str(), ErrorInfo,
  136. llvm::sys::fs::F_None));
  137. if (!ErrorInfo.empty()) {
  138. Diags.Report(diag::warn_fe_serialized_diag_failure)
  139. << OutputFile << ErrorInfo;
  140. return;
  141. }
  142. DiagnosticConsumer *SerializedConsumer =
  143. clang::serialized_diags::create(OS.release(), DiagOpts);
  144. Diags.setClient(new ChainedDiagnosticConsumer(Diags.takeClient(),
  145. SerializedConsumer));
  146. }
  147. void CompilerInstance::createDiagnostics(DiagnosticConsumer *Client,
  148. bool ShouldOwnClient) {
  149. Diagnostics = createDiagnostics(&getDiagnosticOpts(), Client,
  150. ShouldOwnClient, &getCodeGenOpts());
  151. }
  152. IntrusiveRefCntPtr<DiagnosticsEngine>
  153. CompilerInstance::createDiagnostics(DiagnosticOptions *Opts,
  154. DiagnosticConsumer *Client,
  155. bool ShouldOwnClient,
  156. const CodeGenOptions *CodeGenOpts) {
  157. IntrusiveRefCntPtr<DiagnosticIDs> DiagID(new DiagnosticIDs());
  158. IntrusiveRefCntPtr<DiagnosticsEngine>
  159. Diags(new DiagnosticsEngine(DiagID, Opts));
  160. // Create the diagnostic client for reporting errors or for
  161. // implementing -verify.
  162. if (Client) {
  163. Diags->setClient(Client, ShouldOwnClient);
  164. } else
  165. Diags->setClient(new TextDiagnosticPrinter(llvm::errs(), Opts));
  166. // Chain in -verify checker, if requested.
  167. if (Opts->VerifyDiagnostics)
  168. Diags->setClient(new VerifyDiagnosticConsumer(*Diags));
  169. // Chain in -diagnostic-log-file dumper, if requested.
  170. if (!Opts->DiagnosticLogFile.empty())
  171. SetUpDiagnosticLog(Opts, CodeGenOpts, *Diags);
  172. if (!Opts->DiagnosticSerializationFile.empty())
  173. SetupSerializedDiagnostics(Opts, *Diags,
  174. Opts->DiagnosticSerializationFile);
  175. // Configure our handling of diagnostics.
  176. ProcessWarningOptions(*Diags, *Opts);
  177. return Diags;
  178. }
  179. // File Manager
  180. void CompilerInstance::createFileManager() {
  181. if (!hasVirtualFileSystem()) {
  182. // TODO: choose the virtual file system based on the CompilerInvocation.
  183. setVirtualFileSystem(vfs::getRealFileSystem());
  184. }
  185. FileMgr = new FileManager(getFileSystemOpts(), VirtualFileSystem);
  186. }
  187. // Source Manager
  188. void CompilerInstance::createSourceManager(FileManager &FileMgr) {
  189. SourceMgr = new SourceManager(getDiagnostics(), FileMgr);
  190. }
  191. // Preprocessor
  192. void CompilerInstance::createPreprocessor(TranslationUnitKind TUKind) {
  193. const PreprocessorOptions &PPOpts = getPreprocessorOpts();
  194. // Create a PTH manager if we are using some form of a token cache.
  195. PTHManager *PTHMgr = 0;
  196. if (!PPOpts.TokenCache.empty())
  197. PTHMgr = PTHManager::Create(PPOpts.TokenCache, getDiagnostics());
  198. // Create the Preprocessor.
  199. HeaderSearch *HeaderInfo = new HeaderSearch(&getHeaderSearchOpts(),
  200. getSourceManager(),
  201. getDiagnostics(),
  202. getLangOpts(),
  203. &getTarget());
  204. PP = new Preprocessor(&getPreprocessorOpts(),
  205. getDiagnostics(), getLangOpts(),
  206. getSourceManager(), *HeaderInfo, *this, PTHMgr,
  207. /*OwnsHeaderSearch=*/true,
  208. TUKind);
  209. PP->Initialize(getTarget());
  210. // Note that this is different then passing PTHMgr to Preprocessor's ctor.
  211. // That argument is used as the IdentifierInfoLookup argument to
  212. // IdentifierTable's ctor.
  213. if (PTHMgr) {
  214. PTHMgr->setPreprocessor(&*PP);
  215. PP->setPTHManager(PTHMgr);
  216. }
  217. if (PPOpts.DetailedRecord)
  218. PP->createPreprocessingRecord();
  219. InitializePreprocessor(*PP, PPOpts, getHeaderSearchOpts(), getFrontendOpts());
  220. PP->setPreprocessedOutput(getPreprocessorOutputOpts().ShowCPP);
  221. // Set up the module path, including the hash for the
  222. // module-creation options.
  223. SmallString<256> SpecificModuleCache(
  224. getHeaderSearchOpts().ModuleCachePath);
  225. if (!getHeaderSearchOpts().DisableModuleHash)
  226. llvm::sys::path::append(SpecificModuleCache,
  227. getInvocation().getModuleHash());
  228. PP->getHeaderSearchInfo().setModuleCachePath(SpecificModuleCache);
  229. // Handle generating dependencies, if requested.
  230. const DependencyOutputOptions &DepOpts = getDependencyOutputOpts();
  231. if (!DepOpts.OutputFile.empty())
  232. TheDependencyFileGenerator.reset(
  233. DependencyFileGenerator::CreateAndAttachToPreprocessor(*PP, DepOpts));
  234. if (!DepOpts.DOTOutputFile.empty())
  235. AttachDependencyGraphGen(*PP, DepOpts.DOTOutputFile,
  236. getHeaderSearchOpts().Sysroot);
  237. // Handle generating header include information, if requested.
  238. if (DepOpts.ShowHeaderIncludes)
  239. AttachHeaderIncludeGen(*PP);
  240. if (!DepOpts.HeaderIncludeOutputFile.empty()) {
  241. StringRef OutputPath = DepOpts.HeaderIncludeOutputFile;
  242. if (OutputPath == "-")
  243. OutputPath = "";
  244. AttachHeaderIncludeGen(*PP, /*ShowAllHeaders=*/true, OutputPath,
  245. /*ShowDepth=*/false);
  246. }
  247. if (DepOpts.PrintShowIncludes) {
  248. AttachHeaderIncludeGen(*PP, /*ShowAllHeaders=*/false, /*OutputPath=*/"",
  249. /*ShowDepth=*/true, /*MSStyle=*/true);
  250. }
  251. }
  252. // ASTContext
  253. void CompilerInstance::createASTContext() {
  254. Preprocessor &PP = getPreprocessor();
  255. Context = new ASTContext(getLangOpts(), PP.getSourceManager(),
  256. &getTarget(), PP.getIdentifierTable(),
  257. PP.getSelectorTable(), PP.getBuiltinInfo(),
  258. /*size_reserve=*/ 0);
  259. }
  260. // ExternalASTSource
  261. void CompilerInstance::createPCHExternalASTSource(StringRef Path,
  262. bool DisablePCHValidation,
  263. bool AllowPCHWithCompilerErrors,
  264. void *DeserializationListener){
  265. IntrusiveRefCntPtr<ExternalASTSource> Source;
  266. bool Preamble = getPreprocessorOpts().PrecompiledPreambleBytes.first != 0;
  267. Source = createPCHExternalASTSource(Path, getHeaderSearchOpts().Sysroot,
  268. DisablePCHValidation,
  269. AllowPCHWithCompilerErrors,
  270. getPreprocessor(), getASTContext(),
  271. DeserializationListener,
  272. Preamble,
  273. getFrontendOpts().UseGlobalModuleIndex);
  274. ModuleManager = static_cast<ASTReader*>(Source.getPtr());
  275. getASTContext().setExternalSource(Source);
  276. }
  277. ExternalASTSource *
  278. CompilerInstance::createPCHExternalASTSource(StringRef Path,
  279. const std::string &Sysroot,
  280. bool DisablePCHValidation,
  281. bool AllowPCHWithCompilerErrors,
  282. Preprocessor &PP,
  283. ASTContext &Context,
  284. void *DeserializationListener,
  285. bool Preamble,
  286. bool UseGlobalModuleIndex) {
  287. HeaderSearchOptions &HSOpts = PP.getHeaderSearchInfo().getHeaderSearchOpts();
  288. std::unique_ptr<ASTReader> Reader;
  289. Reader.reset(new ASTReader(PP, Context,
  290. Sysroot.empty() ? "" : Sysroot.c_str(),
  291. DisablePCHValidation,
  292. AllowPCHWithCompilerErrors,
  293. /*AllowConfigurationMismatch*/false,
  294. HSOpts.ModulesValidateSystemHeaders,
  295. UseGlobalModuleIndex));
  296. Reader->setDeserializationListener(
  297. static_cast<ASTDeserializationListener *>(DeserializationListener));
  298. switch (Reader->ReadAST(Path,
  299. Preamble ? serialization::MK_Preamble
  300. : serialization::MK_PCH,
  301. SourceLocation(),
  302. ASTReader::ARR_None)) {
  303. case ASTReader::Success:
  304. // Set the predefines buffer as suggested by the PCH reader. Typically, the
  305. // predefines buffer will be empty.
  306. PP.setPredefines(Reader->getSuggestedPredefines());
  307. return Reader.release();
  308. case ASTReader::Failure:
  309. // Unrecoverable failure: don't even try to process the input file.
  310. break;
  311. case ASTReader::Missing:
  312. case ASTReader::OutOfDate:
  313. case ASTReader::VersionMismatch:
  314. case ASTReader::ConfigurationMismatch:
  315. case ASTReader::HadErrors:
  316. // No suitable PCH file could be found. Return an error.
  317. break;
  318. }
  319. return 0;
  320. }
  321. // Code Completion
  322. static bool EnableCodeCompletion(Preprocessor &PP,
  323. const std::string &Filename,
  324. unsigned Line,
  325. unsigned Column) {
  326. // Tell the source manager to chop off the given file at a specific
  327. // line and column.
  328. const FileEntry *Entry = PP.getFileManager().getFile(Filename);
  329. if (!Entry) {
  330. PP.getDiagnostics().Report(diag::err_fe_invalid_code_complete_file)
  331. << Filename;
  332. return true;
  333. }
  334. // Truncate the named file at the given line/column.
  335. PP.SetCodeCompletionPoint(Entry, Line, Column);
  336. return false;
  337. }
  338. void CompilerInstance::createCodeCompletionConsumer() {
  339. const ParsedSourceLocation &Loc = getFrontendOpts().CodeCompletionAt;
  340. if (!CompletionConsumer) {
  341. setCodeCompletionConsumer(
  342. createCodeCompletionConsumer(getPreprocessor(),
  343. Loc.FileName, Loc.Line, Loc.Column,
  344. getFrontendOpts().CodeCompleteOpts,
  345. llvm::outs()));
  346. if (!CompletionConsumer)
  347. return;
  348. } else if (EnableCodeCompletion(getPreprocessor(), Loc.FileName,
  349. Loc.Line, Loc.Column)) {
  350. setCodeCompletionConsumer(0);
  351. return;
  352. }
  353. if (CompletionConsumer->isOutputBinary() &&
  354. llvm::sys::ChangeStdoutToBinary()) {
  355. getPreprocessor().getDiagnostics().Report(diag::err_fe_stdout_binary);
  356. setCodeCompletionConsumer(0);
  357. }
  358. }
  359. void CompilerInstance::createFrontendTimer() {
  360. FrontendTimer.reset(new llvm::Timer("Clang front-end timer"));
  361. }
  362. CodeCompleteConsumer *
  363. CompilerInstance::createCodeCompletionConsumer(Preprocessor &PP,
  364. const std::string &Filename,
  365. unsigned Line,
  366. unsigned Column,
  367. const CodeCompleteOptions &Opts,
  368. raw_ostream &OS) {
  369. if (EnableCodeCompletion(PP, Filename, Line, Column))
  370. return 0;
  371. // Set up the creation routine for code-completion.
  372. return new PrintingCodeCompleteConsumer(Opts, OS);
  373. }
  374. void CompilerInstance::createSema(TranslationUnitKind TUKind,
  375. CodeCompleteConsumer *CompletionConsumer) {
  376. TheSema.reset(new Sema(getPreprocessor(), getASTContext(), getASTConsumer(),
  377. TUKind, CompletionConsumer));
  378. }
  379. // Output Files
  380. void CompilerInstance::addOutputFile(const OutputFile &OutFile) {
  381. assert(OutFile.OS && "Attempt to add empty stream to output list!");
  382. OutputFiles.push_back(OutFile);
  383. }
  384. void CompilerInstance::clearOutputFiles(bool EraseFiles) {
  385. for (std::list<OutputFile>::iterator
  386. it = OutputFiles.begin(), ie = OutputFiles.end(); it != ie; ++it) {
  387. delete it->OS;
  388. if (!it->TempFilename.empty()) {
  389. if (EraseFiles) {
  390. llvm::sys::fs::remove(it->TempFilename);
  391. } else {
  392. SmallString<128> NewOutFile(it->Filename);
  393. // If '-working-directory' was passed, the output filename should be
  394. // relative to that.
  395. FileMgr->FixupRelativePath(NewOutFile);
  396. if (llvm::error_code ec = llvm::sys::fs::rename(it->TempFilename,
  397. NewOutFile.str())) {
  398. getDiagnostics().Report(diag::err_unable_to_rename_temp)
  399. << it->TempFilename << it->Filename << ec.message();
  400. llvm::sys::fs::remove(it->TempFilename);
  401. }
  402. }
  403. } else if (!it->Filename.empty() && EraseFiles)
  404. llvm::sys::fs::remove(it->Filename);
  405. }
  406. OutputFiles.clear();
  407. }
  408. llvm::raw_fd_ostream *
  409. CompilerInstance::createDefaultOutputFile(bool Binary,
  410. StringRef InFile,
  411. StringRef Extension) {
  412. return createOutputFile(getFrontendOpts().OutputFile, Binary,
  413. /*RemoveFileOnSignal=*/true, InFile, Extension,
  414. /*UseTemporary=*/true);
  415. }
  416. llvm::raw_fd_ostream *
  417. CompilerInstance::createOutputFile(StringRef OutputPath,
  418. bool Binary, bool RemoveFileOnSignal,
  419. StringRef InFile,
  420. StringRef Extension,
  421. bool UseTemporary,
  422. bool CreateMissingDirectories) {
  423. std::string Error, OutputPathName, TempPathName;
  424. llvm::raw_fd_ostream *OS = createOutputFile(OutputPath, Error, Binary,
  425. RemoveFileOnSignal,
  426. InFile, Extension,
  427. UseTemporary,
  428. CreateMissingDirectories,
  429. &OutputPathName,
  430. &TempPathName);
  431. if (!OS) {
  432. getDiagnostics().Report(diag::err_fe_unable_to_open_output)
  433. << OutputPath << Error;
  434. return 0;
  435. }
  436. // Add the output file -- but don't try to remove "-", since this means we are
  437. // using stdin.
  438. addOutputFile(OutputFile((OutputPathName != "-") ? OutputPathName : "",
  439. TempPathName, OS));
  440. return OS;
  441. }
  442. llvm::raw_fd_ostream *
  443. CompilerInstance::createOutputFile(StringRef OutputPath,
  444. std::string &Error,
  445. bool Binary,
  446. bool RemoveFileOnSignal,
  447. StringRef InFile,
  448. StringRef Extension,
  449. bool UseTemporary,
  450. bool CreateMissingDirectories,
  451. std::string *ResultPathName,
  452. std::string *TempPathName) {
  453. assert((!CreateMissingDirectories || UseTemporary) &&
  454. "CreateMissingDirectories is only allowed when using temporary files");
  455. std::string OutFile, TempFile;
  456. if (!OutputPath.empty()) {
  457. OutFile = OutputPath;
  458. } else if (InFile == "-") {
  459. OutFile = "-";
  460. } else if (!Extension.empty()) {
  461. SmallString<128> Path(InFile);
  462. llvm::sys::path::replace_extension(Path, Extension);
  463. OutFile = Path.str();
  464. } else {
  465. OutFile = "-";
  466. }
  467. std::unique_ptr<llvm::raw_fd_ostream> OS;
  468. std::string OSFile;
  469. if (UseTemporary) {
  470. if (OutFile == "-")
  471. UseTemporary = false;
  472. else {
  473. llvm::sys::fs::file_status Status;
  474. llvm::sys::fs::status(OutputPath, Status);
  475. if (llvm::sys::fs::exists(Status)) {
  476. // Fail early if we can't write to the final destination.
  477. if (!llvm::sys::fs::can_write(OutputPath))
  478. return 0;
  479. // Don't use a temporary if the output is a special file. This handles
  480. // things like '-o /dev/null'
  481. if (!llvm::sys::fs::is_regular_file(Status))
  482. UseTemporary = false;
  483. }
  484. }
  485. }
  486. if (UseTemporary) {
  487. // Create a temporary file.
  488. SmallString<128> TempPath;
  489. TempPath = OutFile;
  490. TempPath += "-%%%%%%%%";
  491. int fd;
  492. llvm::error_code EC =
  493. llvm::sys::fs::createUniqueFile(TempPath.str(), fd, TempPath);
  494. if (CreateMissingDirectories &&
  495. EC == llvm::errc::no_such_file_or_directory) {
  496. StringRef Parent = llvm::sys::path::parent_path(OutputPath);
  497. EC = llvm::sys::fs::create_directories(Parent);
  498. if (!EC) {
  499. EC = llvm::sys::fs::createUniqueFile(TempPath.str(), fd, TempPath);
  500. }
  501. }
  502. if (!EC) {
  503. OS.reset(new llvm::raw_fd_ostream(fd, /*shouldClose=*/true));
  504. OSFile = TempFile = TempPath.str();
  505. }
  506. // If we failed to create the temporary, fallback to writing to the file
  507. // directly. This handles the corner case where we cannot write to the
  508. // directory, but can write to the file.
  509. }
  510. if (!OS) {
  511. OSFile = OutFile;
  512. OS.reset(new llvm::raw_fd_ostream(
  513. OSFile.c_str(), Error,
  514. (Binary ? llvm::sys::fs::F_None : llvm::sys::fs::F_Text)));
  515. if (!Error.empty())
  516. return 0;
  517. }
  518. // Make sure the out stream file gets removed if we crash.
  519. if (RemoveFileOnSignal)
  520. llvm::sys::RemoveFileOnSignal(OSFile);
  521. if (ResultPathName)
  522. *ResultPathName = OutFile;
  523. if (TempPathName)
  524. *TempPathName = TempFile;
  525. return OS.release();
  526. }
  527. // Initialization Utilities
  528. bool CompilerInstance::InitializeSourceManager(const FrontendInputFile &Input){
  529. return InitializeSourceManager(Input, getDiagnostics(),
  530. getFileManager(), getSourceManager(),
  531. getFrontendOpts());
  532. }
  533. bool CompilerInstance::InitializeSourceManager(const FrontendInputFile &Input,
  534. DiagnosticsEngine &Diags,
  535. FileManager &FileMgr,
  536. SourceManager &SourceMgr,
  537. const FrontendOptions &Opts) {
  538. SrcMgr::CharacteristicKind
  539. Kind = Input.isSystem() ? SrcMgr::C_System : SrcMgr::C_User;
  540. if (Input.isBuffer()) {
  541. SourceMgr.createMainFileIDForMemBuffer(Input.getBuffer(), Kind);
  542. assert(!SourceMgr.getMainFileID().isInvalid() &&
  543. "Couldn't establish MainFileID!");
  544. return true;
  545. }
  546. StringRef InputFile = Input.getFile();
  547. // Figure out where to get and map in the main file.
  548. if (InputFile != "-") {
  549. const FileEntry *File = FileMgr.getFile(InputFile, /*OpenFile=*/true);
  550. if (!File) {
  551. Diags.Report(diag::err_fe_error_reading) << InputFile;
  552. return false;
  553. }
  554. // The natural SourceManager infrastructure can't currently handle named
  555. // pipes, but we would at least like to accept them for the main
  556. // file. Detect them here, read them with the volatile flag so FileMgr will
  557. // pick up the correct size, and simply override their contents as we do for
  558. // STDIN.
  559. if (File->isNamedPipe()) {
  560. std::string ErrorStr;
  561. if (llvm::MemoryBuffer *MB =
  562. FileMgr.getBufferForFile(File, &ErrorStr, /*isVolatile=*/true)) {
  563. // Create a new virtual file that will have the correct size.
  564. File = FileMgr.getVirtualFile(InputFile, MB->getBufferSize(), 0);
  565. SourceMgr.overrideFileContents(File, MB);
  566. } else {
  567. Diags.Report(diag::err_cannot_open_file) << InputFile << ErrorStr;
  568. return false;
  569. }
  570. }
  571. SourceMgr.createMainFileID(File, Kind);
  572. } else {
  573. std::unique_ptr<llvm::MemoryBuffer> SB;
  574. if (llvm::error_code ec = llvm::MemoryBuffer::getSTDIN(SB)) {
  575. Diags.Report(diag::err_fe_error_reading_stdin) << ec.message();
  576. return false;
  577. }
  578. const FileEntry *File = FileMgr.getVirtualFile(SB->getBufferIdentifier(),
  579. SB->getBufferSize(), 0);
  580. SourceMgr.createMainFileID(File, Kind);
  581. SourceMgr.overrideFileContents(File, SB.release());
  582. }
  583. assert(!SourceMgr.getMainFileID().isInvalid() &&
  584. "Couldn't establish MainFileID!");
  585. return true;
  586. }
  587. // High-Level Operations
  588. bool CompilerInstance::ExecuteAction(FrontendAction &Act) {
  589. assert(hasDiagnostics() && "Diagnostics engine is not initialized!");
  590. assert(!getFrontendOpts().ShowHelp && "Client must handle '-help'!");
  591. assert(!getFrontendOpts().ShowVersion && "Client must handle '-version'!");
  592. // FIXME: Take this as an argument, once all the APIs we used have moved to
  593. // taking it as an input instead of hard-coding llvm::errs.
  594. raw_ostream &OS = llvm::errs();
  595. // Create the target instance.
  596. setTarget(TargetInfo::CreateTargetInfo(getDiagnostics(), &getTargetOpts()));
  597. if (!hasTarget())
  598. return false;
  599. // Inform the target of the language options.
  600. //
  601. // FIXME: We shouldn't need to do this, the target should be immutable once
  602. // created. This complexity should be lifted elsewhere.
  603. getTarget().setForcedLangOptions(getLangOpts());
  604. // rewriter project will change target built-in bool type from its default.
  605. if (getFrontendOpts().ProgramAction == frontend::RewriteObjC)
  606. getTarget().noSignedCharForObjCBool();
  607. // Validate/process some options.
  608. if (getHeaderSearchOpts().Verbose)
  609. OS << "clang -cc1 version " CLANG_VERSION_STRING
  610. << " based upon " << PACKAGE_STRING
  611. << " default target " << llvm::sys::getDefaultTargetTriple() << "\n";
  612. if (getFrontendOpts().ShowTimers)
  613. createFrontendTimer();
  614. if (getFrontendOpts().ShowStats)
  615. llvm::EnableStatistics();
  616. for (unsigned i = 0, e = getFrontendOpts().Inputs.size(); i != e; ++i) {
  617. // Reset the ID tables if we are reusing the SourceManager.
  618. if (hasSourceManager())
  619. getSourceManager().clearIDTables();
  620. if (Act.BeginSourceFile(*this, getFrontendOpts().Inputs[i])) {
  621. Act.Execute();
  622. Act.EndSourceFile();
  623. }
  624. }
  625. // Notify the diagnostic client that all files were processed.
  626. getDiagnostics().getClient()->finish();
  627. if (getDiagnosticOpts().ShowCarets) {
  628. // We can have multiple diagnostics sharing one diagnostic client.
  629. // Get the total number of warnings/errors from the client.
  630. unsigned NumWarnings = getDiagnostics().getClient()->getNumWarnings();
  631. unsigned NumErrors = getDiagnostics().getClient()->getNumErrors();
  632. if (NumWarnings)
  633. OS << NumWarnings << " warning" << (NumWarnings == 1 ? "" : "s");
  634. if (NumWarnings && NumErrors)
  635. OS << " and ";
  636. if (NumErrors)
  637. OS << NumErrors << " error" << (NumErrors == 1 ? "" : "s");
  638. if (NumWarnings || NumErrors)
  639. OS << " generated.\n";
  640. }
  641. if (getFrontendOpts().ShowStats && hasFileManager()) {
  642. getFileManager().PrintStats();
  643. OS << "\n";
  644. }
  645. return !getDiagnostics().getClient()->getNumErrors();
  646. }
  647. /// \brief Determine the appropriate source input kind based on language
  648. /// options.
  649. static InputKind getSourceInputKindFromOptions(const LangOptions &LangOpts) {
  650. if (LangOpts.OpenCL)
  651. return IK_OpenCL;
  652. if (LangOpts.CUDA)
  653. return IK_CUDA;
  654. if (LangOpts.ObjC1)
  655. return LangOpts.CPlusPlus? IK_ObjCXX : IK_ObjC;
  656. return LangOpts.CPlusPlus? IK_CXX : IK_C;
  657. }
  658. /// \brief Compile a module file for the given module, using the options
  659. /// provided by the importing compiler instance.
  660. static void compileModuleImpl(CompilerInstance &ImportingInstance,
  661. SourceLocation ImportLoc,
  662. Module *Module,
  663. StringRef ModuleFileName) {
  664. ModuleMap &ModMap
  665. = ImportingInstance.getPreprocessor().getHeaderSearchInfo().getModuleMap();
  666. // Construct a compiler invocation for creating this module.
  667. IntrusiveRefCntPtr<CompilerInvocation> Invocation
  668. (new CompilerInvocation(ImportingInstance.getInvocation()));
  669. PreprocessorOptions &PPOpts = Invocation->getPreprocessorOpts();
  670. // For any options that aren't intended to affect how a module is built,
  671. // reset them to their default values.
  672. Invocation->getLangOpts()->resetNonModularOptions();
  673. PPOpts.resetNonModularOptions();
  674. // Remove any macro definitions that are explicitly ignored by the module.
  675. // They aren't supposed to affect how the module is built anyway.
  676. const HeaderSearchOptions &HSOpts = Invocation->getHeaderSearchOpts();
  677. PPOpts.Macros.erase(
  678. std::remove_if(PPOpts.Macros.begin(), PPOpts.Macros.end(),
  679. [&HSOpts](const std::pair<std::string, bool> &def) {
  680. StringRef MacroDef = def.first;
  681. return HSOpts.ModulesIgnoreMacros.count(MacroDef.split('=').first) > 0;
  682. }),
  683. PPOpts.Macros.end());
  684. // Note the name of the module we're building.
  685. Invocation->getLangOpts()->CurrentModule = Module->getTopLevelModuleName();
  686. // Make sure that the failed-module structure has been allocated in
  687. // the importing instance, and propagate the pointer to the newly-created
  688. // instance.
  689. PreprocessorOptions &ImportingPPOpts
  690. = ImportingInstance.getInvocation().getPreprocessorOpts();
  691. if (!ImportingPPOpts.FailedModules)
  692. ImportingPPOpts.FailedModules = new PreprocessorOptions::FailedModulesSet;
  693. PPOpts.FailedModules = ImportingPPOpts.FailedModules;
  694. // If there is a module map file, build the module using the module map.
  695. // Set up the inputs/outputs so that we build the module from its umbrella
  696. // header.
  697. FrontendOptions &FrontendOpts = Invocation->getFrontendOpts();
  698. FrontendOpts.OutputFile = ModuleFileName.str();
  699. FrontendOpts.DisableFree = false;
  700. FrontendOpts.GenerateGlobalModuleIndex = false;
  701. FrontendOpts.Inputs.clear();
  702. InputKind IK = getSourceInputKindFromOptions(*Invocation->getLangOpts());
  703. // Don't free the remapped file buffers; they are owned by our caller.
  704. PPOpts.RetainRemappedFileBuffers = true;
  705. Invocation->getDiagnosticOpts().VerifyDiagnostics = 0;
  706. assert(ImportingInstance.getInvocation().getModuleHash() ==
  707. Invocation->getModuleHash() && "Module hash mismatch!");
  708. // Construct a compiler instance that will be used to actually create the
  709. // module.
  710. CompilerInstance Instance(/*BuildingModule=*/true);
  711. Instance.setInvocation(&*Invocation);
  712. Instance.createDiagnostics(new ForwardingDiagnosticConsumer(
  713. ImportingInstance.getDiagnosticClient()),
  714. /*ShouldOwnClient=*/true);
  715. Instance.setVirtualFileSystem(&ImportingInstance.getVirtualFileSystem());
  716. // Note that this module is part of the module build stack, so that we
  717. // can detect cycles in the module graph.
  718. Instance.setFileManager(&ImportingInstance.getFileManager());
  719. Instance.createSourceManager(Instance.getFileManager());
  720. SourceManager &SourceMgr = Instance.getSourceManager();
  721. SourceMgr.setModuleBuildStack(
  722. ImportingInstance.getSourceManager().getModuleBuildStack());
  723. SourceMgr.pushModuleBuildStack(Module->getTopLevelModuleName(),
  724. FullSourceLoc(ImportLoc, ImportingInstance.getSourceManager()));
  725. // Get or create the module map that we'll use to build this module.
  726. std::string InferredModuleMapContent;
  727. if (const FileEntry *ModuleMapFile =
  728. ModMap.getContainingModuleMapFile(Module)) {
  729. // Use the module map where this module resides.
  730. FrontendOpts.Inputs.push_back(
  731. FrontendInputFile(ModuleMapFile->getName(), IK));
  732. } else {
  733. llvm::raw_string_ostream OS(InferredModuleMapContent);
  734. Module->print(OS);
  735. OS.flush();
  736. FrontendOpts.Inputs.push_back(
  737. FrontendInputFile("__inferred_module.map", IK));
  738. const llvm::MemoryBuffer *ModuleMapBuffer =
  739. llvm::MemoryBuffer::getMemBuffer(InferredModuleMapContent);
  740. ModuleMapFile = Instance.getFileManager().getVirtualFile(
  741. "__inferred_module.map", InferredModuleMapContent.size(), 0);
  742. SourceMgr.overrideFileContents(ModuleMapFile, ModuleMapBuffer);
  743. }
  744. // Construct a module-generating action. Passing through Module->ModuleMap is
  745. // safe because the FileManager is shared between the compiler instances.
  746. GenerateModuleAction CreateModuleAction(Module->ModuleMap, Module->IsSystem);
  747. // Execute the action to actually build the module in-place. Use a separate
  748. // thread so that we get a stack large enough.
  749. const unsigned ThreadStackSize = 8 << 20;
  750. llvm::CrashRecoveryContext CRC;
  751. CRC.RunSafelyOnThread([&]() { Instance.ExecuteAction(CreateModuleAction); },
  752. ThreadStackSize);
  753. // Delete the temporary module map file.
  754. // FIXME: Even though we're executing under crash protection, it would still
  755. // be nice to do this with RemoveFileOnSignal when we can. However, that
  756. // doesn't make sense for all clients, so clean this up manually.
  757. Instance.clearOutputFiles(/*EraseFiles=*/true);
  758. // We've rebuilt a module. If we're allowed to generate or update the global
  759. // module index, record that fact in the importing compiler instance.
  760. if (ImportingInstance.getFrontendOpts().GenerateGlobalModuleIndex) {
  761. ImportingInstance.setBuildGlobalModuleIndex(true);
  762. }
  763. }
  764. static void compileModule(CompilerInstance &ImportingInstance,
  765. SourceLocation ImportLoc,
  766. Module *Module,
  767. StringRef ModuleFileName) {
  768. // FIXME: have LockFileManager return an error_code so that we can
  769. // avoid the mkdir when the directory already exists.
  770. StringRef Dir = llvm::sys::path::parent_path(ModuleFileName);
  771. llvm::sys::fs::create_directories(Dir);
  772. while (1) {
  773. llvm::LockFileManager Locked(ModuleFileName);
  774. switch (Locked) {
  775. case llvm::LockFileManager::LFS_Error:
  776. return;
  777. case llvm::LockFileManager::LFS_Owned:
  778. // We're responsible for building the module ourselves. Do so below.
  779. break;
  780. case llvm::LockFileManager::LFS_Shared:
  781. // Someone else is responsible for building the module. Wait for them to
  782. // finish.
  783. if (Locked.waitForUnlock() == llvm::LockFileManager::Res_OwnerDied)
  784. continue; // try again to get the lock.
  785. return;
  786. }
  787. return compileModuleImpl(ImportingInstance, ImportLoc, Module,
  788. ModuleFileName);
  789. }
  790. }
  791. /// \brief Diagnose differences between the current definition of the given
  792. /// configuration macro and the definition provided on the command line.
  793. static void checkConfigMacro(Preprocessor &PP, StringRef ConfigMacro,
  794. Module *Mod, SourceLocation ImportLoc) {
  795. IdentifierInfo *Id = PP.getIdentifierInfo(ConfigMacro);
  796. SourceManager &SourceMgr = PP.getSourceManager();
  797. // If this identifier has never had a macro definition, then it could
  798. // not have changed.
  799. if (!Id->hadMacroDefinition())
  800. return;
  801. // If this identifier does not currently have a macro definition,
  802. // check whether it had one on the command line.
  803. if (!Id->hasMacroDefinition()) {
  804. MacroDirective::DefInfo LatestDef =
  805. PP.getMacroDirectiveHistory(Id)->getDefinition();
  806. for (MacroDirective::DefInfo Def = LatestDef; Def;
  807. Def = Def.getPreviousDefinition()) {
  808. FileID FID = SourceMgr.getFileID(Def.getLocation());
  809. if (FID.isInvalid())
  810. continue;
  811. // We only care about the predefines buffer.
  812. if (FID != PP.getPredefinesFileID())
  813. continue;
  814. // This macro was defined on the command line, then #undef'd later.
  815. // Complain.
  816. PP.Diag(ImportLoc, diag::warn_module_config_macro_undef)
  817. << true << ConfigMacro << Mod->getFullModuleName();
  818. if (LatestDef.isUndefined())
  819. PP.Diag(LatestDef.getUndefLocation(), diag::note_module_def_undef_here)
  820. << true;
  821. return;
  822. }
  823. // Okay: no definition in the predefines buffer.
  824. return;
  825. }
  826. // This identifier has a macro definition. Check whether we had a definition
  827. // on the command line.
  828. MacroDirective::DefInfo LatestDef =
  829. PP.getMacroDirectiveHistory(Id)->getDefinition();
  830. MacroDirective::DefInfo PredefinedDef;
  831. for (MacroDirective::DefInfo Def = LatestDef; Def;
  832. Def = Def.getPreviousDefinition()) {
  833. FileID FID = SourceMgr.getFileID(Def.getLocation());
  834. if (FID.isInvalid())
  835. continue;
  836. // We only care about the predefines buffer.
  837. if (FID != PP.getPredefinesFileID())
  838. continue;
  839. PredefinedDef = Def;
  840. break;
  841. }
  842. // If there was no definition for this macro in the predefines buffer,
  843. // complain.
  844. if (!PredefinedDef ||
  845. (!PredefinedDef.getLocation().isValid() &&
  846. PredefinedDef.getUndefLocation().isValid())) {
  847. PP.Diag(ImportLoc, diag::warn_module_config_macro_undef)
  848. << false << ConfigMacro << Mod->getFullModuleName();
  849. PP.Diag(LatestDef.getLocation(), diag::note_module_def_undef_here)
  850. << false;
  851. return;
  852. }
  853. // If the current macro definition is the same as the predefined macro
  854. // definition, it's okay.
  855. if (LatestDef.getMacroInfo() == PredefinedDef.getMacroInfo() ||
  856. LatestDef.getMacroInfo()->isIdenticalTo(*PredefinedDef.getMacroInfo(),PP,
  857. /*Syntactically=*/true))
  858. return;
  859. // The macro definitions differ.
  860. PP.Diag(ImportLoc, diag::warn_module_config_macro_undef)
  861. << false << ConfigMacro << Mod->getFullModuleName();
  862. PP.Diag(LatestDef.getLocation(), diag::note_module_def_undef_here)
  863. << false;
  864. }
  865. /// \brief Write a new timestamp file with the given path.
  866. static void writeTimestampFile(StringRef TimestampFile) {
  867. std::string ErrorInfo;
  868. llvm::raw_fd_ostream Out(TimestampFile.str().c_str(), ErrorInfo,
  869. llvm::sys::fs::F_None);
  870. }
  871. /// \brief Prune the module cache of modules that haven't been accessed in
  872. /// a long time.
  873. static void pruneModuleCache(const HeaderSearchOptions &HSOpts) {
  874. struct stat StatBuf;
  875. llvm::SmallString<128> TimestampFile;
  876. TimestampFile = HSOpts.ModuleCachePath;
  877. llvm::sys::path::append(TimestampFile, "modules.timestamp");
  878. // Try to stat() the timestamp file.
  879. if (::stat(TimestampFile.c_str(), &StatBuf)) {
  880. // If the timestamp file wasn't there, create one now.
  881. if (errno == ENOENT) {
  882. writeTimestampFile(TimestampFile);
  883. }
  884. return;
  885. }
  886. // Check whether the time stamp is older than our pruning interval.
  887. // If not, do nothing.
  888. time_t TimeStampModTime = StatBuf.st_mtime;
  889. time_t CurrentTime = time(0);
  890. if (CurrentTime - TimeStampModTime <= time_t(HSOpts.ModuleCachePruneInterval))
  891. return;
  892. // Write a new timestamp file so that nobody else attempts to prune.
  893. // There is a benign race condition here, if two Clang instances happen to
  894. // notice at the same time that the timestamp is out-of-date.
  895. writeTimestampFile(TimestampFile);
  896. // Walk the entire module cache, looking for unused module files and module
  897. // indices.
  898. llvm::error_code EC;
  899. SmallString<128> ModuleCachePathNative;
  900. llvm::sys::path::native(HSOpts.ModuleCachePath, ModuleCachePathNative);
  901. for (llvm::sys::fs::directory_iterator
  902. Dir(ModuleCachePathNative.str(), EC), DirEnd;
  903. Dir != DirEnd && !EC; Dir.increment(EC)) {
  904. // If we don't have a directory, there's nothing to look into.
  905. if (!llvm::sys::fs::is_directory(Dir->path()))
  906. continue;
  907. // Walk all of the files within this directory.
  908. for (llvm::sys::fs::directory_iterator File(Dir->path(), EC), FileEnd;
  909. File != FileEnd && !EC; File.increment(EC)) {
  910. // We only care about module and global module index files.
  911. StringRef Extension = llvm::sys::path::extension(File->path());
  912. if (Extension != ".pcm" && Extension != ".timestamp" &&
  913. llvm::sys::path::filename(File->path()) != "modules.idx")
  914. continue;
  915. // Look at this file. If we can't stat it, there's nothing interesting
  916. // there.
  917. if (::stat(File->path().c_str(), &StatBuf))
  918. continue;
  919. // If the file has been used recently enough, leave it there.
  920. time_t FileAccessTime = StatBuf.st_atime;
  921. if (CurrentTime - FileAccessTime <=
  922. time_t(HSOpts.ModuleCachePruneAfter)) {
  923. continue;
  924. }
  925. // Remove the file.
  926. llvm::sys::fs::remove(File->path());
  927. // Remove the timestamp file.
  928. std::string TimpestampFilename = File->path() + ".timestamp";
  929. llvm::sys::fs::remove(TimpestampFilename);
  930. }
  931. // If we removed all of the files in the directory, remove the directory
  932. // itself.
  933. if (llvm::sys::fs::directory_iterator(Dir->path(), EC) ==
  934. llvm::sys::fs::directory_iterator() && !EC)
  935. llvm::sys::fs::remove(Dir->path());
  936. }
  937. }
  938. void CompilerInstance::createModuleManager() {
  939. if (!ModuleManager) {
  940. if (!hasASTContext())
  941. createASTContext();
  942. // If we're not recursively building a module, check whether we
  943. // need to prune the module cache.
  944. if (getSourceManager().getModuleBuildStack().empty() &&
  945. getHeaderSearchOpts().ModuleCachePruneInterval > 0 &&
  946. getHeaderSearchOpts().ModuleCachePruneAfter > 0) {
  947. pruneModuleCache(getHeaderSearchOpts());
  948. }
  949. HeaderSearchOptions &HSOpts = getHeaderSearchOpts();
  950. std::string Sysroot = HSOpts.Sysroot;
  951. const PreprocessorOptions &PPOpts = getPreprocessorOpts();
  952. ModuleManager = new ASTReader(getPreprocessor(), *Context,
  953. Sysroot.empty() ? "" : Sysroot.c_str(),
  954. PPOpts.DisablePCHValidation,
  955. /*AllowASTWithCompilerErrors=*/false,
  956. /*AllowConfigurationMismatch=*/false,
  957. HSOpts.ModulesValidateSystemHeaders,
  958. getFrontendOpts().UseGlobalModuleIndex);
  959. if (hasASTConsumer()) {
  960. ModuleManager->setDeserializationListener(
  961. getASTConsumer().GetASTDeserializationListener());
  962. getASTContext().setASTMutationListener(
  963. getASTConsumer().GetASTMutationListener());
  964. }
  965. getASTContext().setExternalSource(ModuleManager);
  966. if (hasSema())
  967. ModuleManager->InitializeSema(getSema());
  968. if (hasASTConsumer())
  969. ModuleManager->StartTranslationUnit(&getASTConsumer());
  970. }
  971. }
  972. ModuleLoadResult
  973. CompilerInstance::loadModule(SourceLocation ImportLoc,
  974. ModuleIdPath Path,
  975. Module::NameVisibilityKind Visibility,
  976. bool IsInclusionDirective) {
  977. // Determine what file we're searching from.
  978. StringRef ModuleName = Path[0].first->getName();
  979. SourceLocation ModuleNameLoc = Path[0].second;
  980. // If we've already handled this import, just return the cached result.
  981. // This one-element cache is important to eliminate redundant diagnostics
  982. // when both the preprocessor and parser see the same import declaration.
  983. if (!ImportLoc.isInvalid() && LastModuleImportLoc == ImportLoc) {
  984. // Make the named module visible.
  985. if (LastModuleImportResult && ModuleName != getLangOpts().CurrentModule)
  986. ModuleManager->makeModuleVisible(LastModuleImportResult, Visibility,
  987. ImportLoc, /*Complain=*/false);
  988. return LastModuleImportResult;
  989. }
  990. clang::Module *Module = 0;
  991. // If we don't already have information on this module, load the module now.
  992. llvm::DenseMap<const IdentifierInfo *, clang::Module *>::iterator Known
  993. = KnownModules.find(Path[0].first);
  994. if (Known != KnownModules.end()) {
  995. // Retrieve the cached top-level module.
  996. Module = Known->second;
  997. } else if (ModuleName == getLangOpts().CurrentModule) {
  998. // This is the module we're building.
  999. Module = PP->getHeaderSearchInfo().getModuleMap().findModule(ModuleName);
  1000. Known = KnownModules.insert(std::make_pair(Path[0].first, Module)).first;
  1001. } else {
  1002. // Search for a module with the given name.
  1003. Module = PP->getHeaderSearchInfo().lookupModule(ModuleName);
  1004. if (!Module) {
  1005. getDiagnostics().Report(ModuleNameLoc, diag::err_module_not_found)
  1006. << ModuleName
  1007. << SourceRange(ImportLoc, ModuleNameLoc);
  1008. ModuleBuildFailed = true;
  1009. return ModuleLoadResult();
  1010. }
  1011. std::string ModuleFileName =
  1012. PP->getHeaderSearchInfo().getModuleFileName(Module);
  1013. // If we don't already have an ASTReader, create one now.
  1014. if (!ModuleManager)
  1015. createModuleManager();
  1016. if (TheDependencyFileGenerator)
  1017. TheDependencyFileGenerator->AttachToASTReader(*ModuleManager);
  1018. // Try to load the module file.
  1019. unsigned ARRFlags = ASTReader::ARR_OutOfDate | ASTReader::ARR_Missing;
  1020. switch (ModuleManager->ReadAST(ModuleFileName, serialization::MK_Module,
  1021. ImportLoc, ARRFlags)) {
  1022. case ASTReader::Success:
  1023. break;
  1024. case ASTReader::OutOfDate:
  1025. case ASTReader::Missing: {
  1026. // The module file is missing or out-of-date. Build it.
  1027. assert(Module && "missing module file");
  1028. // Check whether there is a cycle in the module graph.
  1029. ModuleBuildStack ModPath = getSourceManager().getModuleBuildStack();
  1030. ModuleBuildStack::iterator Pos = ModPath.begin(), PosEnd = ModPath.end();
  1031. for (; Pos != PosEnd; ++Pos) {
  1032. if (Pos->first == ModuleName)
  1033. break;
  1034. }
  1035. if (Pos != PosEnd) {
  1036. SmallString<256> CyclePath;
  1037. for (; Pos != PosEnd; ++Pos) {
  1038. CyclePath += Pos->first;
  1039. CyclePath += " -> ";
  1040. }
  1041. CyclePath += ModuleName;
  1042. getDiagnostics().Report(ModuleNameLoc, diag::err_module_cycle)
  1043. << ModuleName << CyclePath;
  1044. return ModuleLoadResult();
  1045. }
  1046. // Check whether we have already attempted to build this module (but
  1047. // failed).
  1048. if (getPreprocessorOpts().FailedModules &&
  1049. getPreprocessorOpts().FailedModules->hasAlreadyFailed(ModuleName)) {
  1050. getDiagnostics().Report(ModuleNameLoc, diag::err_module_not_built)
  1051. << ModuleName
  1052. << SourceRange(ImportLoc, ModuleNameLoc);
  1053. ModuleBuildFailed = true;
  1054. return ModuleLoadResult();
  1055. }
  1056. // Try to compile the module.
  1057. compileModule(*this, ModuleNameLoc, Module, ModuleFileName);
  1058. // Try to read the module file, now that we've compiled it.
  1059. ASTReader::ASTReadResult ReadResult
  1060. = ModuleManager->ReadAST(ModuleFileName,
  1061. serialization::MK_Module, ImportLoc,
  1062. ASTReader::ARR_Missing);
  1063. if (ReadResult != ASTReader::Success) {
  1064. if (ReadResult == ASTReader::Missing) {
  1065. getDiagnostics().Report(ModuleNameLoc,
  1066. Module? diag::err_module_not_built
  1067. : diag::err_module_not_found)
  1068. << ModuleName
  1069. << SourceRange(ImportLoc, ModuleNameLoc);
  1070. }
  1071. if (getPreprocessorOpts().FailedModules)
  1072. getPreprocessorOpts().FailedModules->addFailed(ModuleName);
  1073. KnownModules[Path[0].first] = 0;
  1074. ModuleBuildFailed = true;
  1075. return ModuleLoadResult();
  1076. }
  1077. // Okay, we've rebuilt and now loaded the module.
  1078. break;
  1079. }
  1080. case ASTReader::VersionMismatch:
  1081. case ASTReader::ConfigurationMismatch:
  1082. case ASTReader::HadErrors:
  1083. ModuleLoader::HadFatalFailure = true;
  1084. // FIXME: The ASTReader will already have complained, but can we showhorn
  1085. // that diagnostic information into a more useful form?
  1086. KnownModules[Path[0].first] = 0;
  1087. return ModuleLoadResult();
  1088. case ASTReader::Failure:
  1089. ModuleLoader::HadFatalFailure = true;
  1090. // Already complained, but note now that we failed.
  1091. KnownModules[Path[0].first] = 0;
  1092. ModuleBuildFailed = true;
  1093. return ModuleLoadResult();
  1094. }
  1095. // Cache the result of this top-level module lookup for later.
  1096. Known = KnownModules.insert(std::make_pair(Path[0].first, Module)).first;
  1097. }
  1098. // If we never found the module, fail.
  1099. if (!Module)
  1100. return ModuleLoadResult();
  1101. // Verify that the rest of the module path actually corresponds to
  1102. // a submodule.
  1103. if (Path.size() > 1) {
  1104. for (unsigned I = 1, N = Path.size(); I != N; ++I) {
  1105. StringRef Name = Path[I].first->getName();
  1106. clang::Module *Sub = Module->findSubmodule(Name);
  1107. if (!Sub) {
  1108. // Attempt to perform typo correction to find a module name that works.
  1109. SmallVector<StringRef, 2> Best;
  1110. unsigned BestEditDistance = (std::numeric_limits<unsigned>::max)();
  1111. for (clang::Module::submodule_iterator J = Module->submodule_begin(),
  1112. JEnd = Module->submodule_end();
  1113. J != JEnd; ++J) {
  1114. unsigned ED = Name.edit_distance((*J)->Name,
  1115. /*AllowReplacements=*/true,
  1116. BestEditDistance);
  1117. if (ED <= BestEditDistance) {
  1118. if (ED < BestEditDistance) {
  1119. Best.clear();
  1120. BestEditDistance = ED;
  1121. }
  1122. Best.push_back((*J)->Name);
  1123. }
  1124. }
  1125. // If there was a clear winner, user it.
  1126. if (Best.size() == 1) {
  1127. getDiagnostics().Report(Path[I].second,
  1128. diag::err_no_submodule_suggest)
  1129. << Path[I].first << Module->getFullModuleName() << Best[0]
  1130. << SourceRange(Path[0].second, Path[I-1].second)
  1131. << FixItHint::CreateReplacement(SourceRange(Path[I].second),
  1132. Best[0]);
  1133. Sub = Module->findSubmodule(Best[0]);
  1134. }
  1135. }
  1136. if (!Sub) {
  1137. // No submodule by this name. Complain, and don't look for further
  1138. // submodules.
  1139. getDiagnostics().Report(Path[I].second, diag::err_no_submodule)
  1140. << Path[I].first << Module->getFullModuleName()
  1141. << SourceRange(Path[0].second, Path[I-1].second);
  1142. break;
  1143. }
  1144. Module = Sub;
  1145. }
  1146. }
  1147. // Make the named module visible, if it's not already part of the module
  1148. // we are parsing.
  1149. if (ModuleName != getLangOpts().CurrentModule) {
  1150. if (!Module->IsFromModuleFile) {
  1151. // We have an umbrella header or directory that doesn't actually include
  1152. // all of the headers within the directory it covers. Complain about
  1153. // this missing submodule and recover by forgetting that we ever saw
  1154. // this submodule.
  1155. // FIXME: Should we detect this at module load time? It seems fairly
  1156. // expensive (and rare).
  1157. getDiagnostics().Report(ImportLoc, diag::warn_missing_submodule)
  1158. << Module->getFullModuleName()
  1159. << SourceRange(Path.front().second, Path.back().second);
  1160. return ModuleLoadResult(0, true);
  1161. }
  1162. // Check whether this module is available.
  1163. clang::Module::Requirement Requirement;
  1164. clang::Module::HeaderDirective MissingHeader;
  1165. if (!Module->isAvailable(getLangOpts(), getTarget(), Requirement,
  1166. MissingHeader)) {
  1167. if (MissingHeader.FileNameLoc.isValid()) {
  1168. getDiagnostics().Report(MissingHeader.FileNameLoc,
  1169. diag::err_module_header_missing)
  1170. << MissingHeader.IsUmbrella << MissingHeader.FileName;
  1171. } else {
  1172. getDiagnostics().Report(ImportLoc, diag::err_module_unavailable)
  1173. << Module->getFullModuleName()
  1174. << Requirement.second << Requirement.first
  1175. << SourceRange(Path.front().second, Path.back().second);
  1176. }
  1177. LastModuleImportLoc = ImportLoc;
  1178. LastModuleImportResult = ModuleLoadResult();
  1179. return ModuleLoadResult();
  1180. }
  1181. ModuleManager->makeModuleVisible(Module, Visibility, ImportLoc,
  1182. /*Complain=*/true);
  1183. }
  1184. // Check for any configuration macros that have changed.
  1185. clang::Module *TopModule = Module->getTopLevelModule();
  1186. for (unsigned I = 0, N = TopModule->ConfigMacros.size(); I != N; ++I) {
  1187. checkConfigMacro(getPreprocessor(), TopModule->ConfigMacros[I],
  1188. Module, ImportLoc);
  1189. }
  1190. // If this module import was due to an inclusion directive, create an
  1191. // implicit import declaration to capture it in the AST.
  1192. if (IsInclusionDirective && hasASTContext()) {
  1193. TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl();
  1194. ImportDecl *ImportD = ImportDecl::CreateImplicit(getASTContext(), TU,
  1195. ImportLoc, Module,
  1196. Path.back().second);
  1197. TU->addDecl(ImportD);
  1198. if (Consumer)
  1199. Consumer->HandleImplicitImportDecl(ImportD);
  1200. }
  1201. LastModuleImportLoc = ImportLoc;
  1202. LastModuleImportResult = ModuleLoadResult(Module, false);
  1203. return LastModuleImportResult;
  1204. }
  1205. void CompilerInstance::makeModuleVisible(Module *Mod,
  1206. Module::NameVisibilityKind Visibility,
  1207. SourceLocation ImportLoc,
  1208. bool Complain){
  1209. ModuleManager->makeModuleVisible(Mod, Visibility, ImportLoc, Complain);
  1210. }
  1211. GlobalModuleIndex *CompilerInstance::loadGlobalModuleIndex(
  1212. SourceLocation TriggerLoc) {
  1213. if (!ModuleManager)
  1214. createModuleManager();
  1215. // Can't do anything if we don't have the module manager.
  1216. if (!ModuleManager)
  1217. return 0;
  1218. // Get an existing global index. This loads it if not already
  1219. // loaded.
  1220. ModuleManager->loadGlobalIndex();
  1221. GlobalModuleIndex *GlobalIndex = ModuleManager->getGlobalIndex();
  1222. // If the global index doesn't exist, create it.
  1223. if (!GlobalIndex && shouldBuildGlobalModuleIndex() && hasFileManager() &&
  1224. hasPreprocessor()) {
  1225. llvm::sys::fs::create_directories(
  1226. getPreprocessor().getHeaderSearchInfo().getModuleCachePath());
  1227. GlobalModuleIndex::writeIndex(
  1228. getFileManager(),
  1229. getPreprocessor().getHeaderSearchInfo().getModuleCachePath());
  1230. ModuleManager->resetForReload();
  1231. ModuleManager->loadGlobalIndex();
  1232. GlobalIndex = ModuleManager->getGlobalIndex();
  1233. }
  1234. // For finding modules needing to be imported for fixit messages,
  1235. // we need to make the global index cover all modules, so we do that here.
  1236. if (!HaveFullGlobalModuleIndex && GlobalIndex && !buildingModule()) {
  1237. ModuleMap &MMap = getPreprocessor().getHeaderSearchInfo().getModuleMap();
  1238. bool RecreateIndex = false;
  1239. for (ModuleMap::module_iterator I = MMap.module_begin(),
  1240. E = MMap.module_end(); I != E; ++I) {
  1241. Module *TheModule = I->second;
  1242. const FileEntry *Entry = TheModule->getASTFile();
  1243. if (!Entry) {
  1244. SmallVector<std::pair<IdentifierInfo *, SourceLocation>, 2> Path;
  1245. Path.push_back(std::make_pair(
  1246. getPreprocessor().getIdentifierInfo(TheModule->Name), TriggerLoc));
  1247. std::reverse(Path.begin(), Path.end());
  1248. // Load a module as hidden. This also adds it to the global index.
  1249. loadModule(TheModule->DefinitionLoc, Path,
  1250. Module::Hidden, false);
  1251. RecreateIndex = true;
  1252. }
  1253. }
  1254. if (RecreateIndex) {
  1255. GlobalModuleIndex::writeIndex(
  1256. getFileManager(),
  1257. getPreprocessor().getHeaderSearchInfo().getModuleCachePath());
  1258. ModuleManager->resetForReload();
  1259. ModuleManager->loadGlobalIndex();
  1260. GlobalIndex = ModuleManager->getGlobalIndex();
  1261. }
  1262. HaveFullGlobalModuleIndex = true;
  1263. }
  1264. return GlobalIndex;
  1265. }
  1266. // Check global module index for missing imports.
  1267. bool
  1268. CompilerInstance::lookupMissingImports(StringRef Name,
  1269. SourceLocation TriggerLoc) {
  1270. // Look for the symbol in non-imported modules, but only if an error
  1271. // actually occurred.
  1272. if (!buildingModule()) {
  1273. // Load global module index, or retrieve a previously loaded one.
  1274. GlobalModuleIndex *GlobalIndex = loadGlobalModuleIndex(
  1275. TriggerLoc);
  1276. // Only if we have a global index.
  1277. if (GlobalIndex) {
  1278. GlobalModuleIndex::HitSet FoundModules;
  1279. // Find the modules that reference the identifier.
  1280. // Note that this only finds top-level modules.
  1281. // We'll let diagnoseTypo find the actual declaration module.
  1282. if (GlobalIndex->lookupIdentifier(Name, FoundModules))
  1283. return true;
  1284. }
  1285. }
  1286. return false;
  1287. }