CompilerInstance.cpp 58 KB

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