CompilerInstance.cpp 63 KB

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