CompilerInstance.cpp 64 KB

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