CompilerInstance.cpp 82 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137
  1. //===--- CompilerInstance.cpp ---------------------------------------------===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. #include "clang/Frontend/CompilerInstance.h"
  9. #include "clang/AST/ASTConsumer.h"
  10. #include "clang/AST/ASTContext.h"
  11. #include "clang/AST/Decl.h"
  12. #include "clang/Basic/CharInfo.h"
  13. #include "clang/Basic/Diagnostic.h"
  14. #include "clang/Basic/FileManager.h"
  15. #include "clang/Basic/LangStandard.h"
  16. #include "clang/Basic/SourceManager.h"
  17. #include "clang/Basic/Stack.h"
  18. #include "clang/Basic/TargetInfo.h"
  19. #include "clang/Basic/Version.h"
  20. #include "clang/Config/config.h"
  21. #include "clang/Frontend/ChainedDiagnosticConsumer.h"
  22. #include "clang/Frontend/FrontendAction.h"
  23. #include "clang/Frontend/FrontendActions.h"
  24. #include "clang/Frontend/FrontendDiagnostic.h"
  25. #include "clang/Frontend/LogDiagnosticPrinter.h"
  26. #include "clang/Frontend/SerializedDiagnosticPrinter.h"
  27. #include "clang/Frontend/TextDiagnosticPrinter.h"
  28. #include "clang/Frontend/Utils.h"
  29. #include "clang/Frontend/VerifyDiagnosticConsumer.h"
  30. #include "clang/Lex/HeaderSearch.h"
  31. #include "clang/Lex/Preprocessor.h"
  32. #include "clang/Lex/PreprocessorOptions.h"
  33. #include "clang/Sema/CodeCompleteConsumer.h"
  34. #include "clang/Sema/Sema.h"
  35. #include "clang/Serialization/ASTReader.h"
  36. #include "clang/Serialization/GlobalModuleIndex.h"
  37. #include "clang/Serialization/InMemoryModuleCache.h"
  38. #include "llvm/ADT/Statistic.h"
  39. #include "llvm/Support/BuryPointer.h"
  40. #include "llvm/Support/CrashRecoveryContext.h"
  41. #include "llvm/Support/Errc.h"
  42. #include "llvm/Support/FileSystem.h"
  43. #include "llvm/Support/Host.h"
  44. #include "llvm/Support/LockFileManager.h"
  45. #include "llvm/Support/MemoryBuffer.h"
  46. #include "llvm/Support/Path.h"
  47. #include "llvm/Support/Program.h"
  48. #include "llvm/Support/Signals.h"
  49. #include "llvm/Support/TimeProfiler.h"
  50. #include "llvm/Support/Timer.h"
  51. #include "llvm/Support/raw_ostream.h"
  52. #include <sys/stat.h>
  53. #include <system_error>
  54. #include <time.h>
  55. #include <utility>
  56. using namespace clang;
  57. CompilerInstance::CompilerInstance(
  58. std::shared_ptr<PCHContainerOperations> PCHContainerOps,
  59. InMemoryModuleCache *SharedModuleCache)
  60. : ModuleLoader(/* BuildingModule = */ SharedModuleCache),
  61. Invocation(new CompilerInvocation()),
  62. ModuleCache(SharedModuleCache ? SharedModuleCache
  63. : new InMemoryModuleCache),
  64. ThePCHContainerOperations(std::move(PCHContainerOps)) {}
  65. CompilerInstance::~CompilerInstance() {
  66. assert(OutputFiles.empty() && "Still output files in flight?");
  67. }
  68. void CompilerInstance::setInvocation(
  69. std::shared_ptr<CompilerInvocation> Value) {
  70. Invocation = std::move(Value);
  71. }
  72. bool CompilerInstance::shouldBuildGlobalModuleIndex() const {
  73. return (BuildGlobalModuleIndex ||
  74. (ModuleManager && ModuleManager->isGlobalIndexUnavailable() &&
  75. getFrontendOpts().GenerateGlobalModuleIndex)) &&
  76. !ModuleBuildFailed;
  77. }
  78. void CompilerInstance::setDiagnostics(DiagnosticsEngine *Value) {
  79. Diagnostics = Value;
  80. }
  81. void CompilerInstance::setTarget(TargetInfo *Value) { Target = Value; }
  82. void CompilerInstance::setAuxTarget(TargetInfo *Value) { AuxTarget = Value; }
  83. void CompilerInstance::setFileManager(FileManager *Value) {
  84. FileMgr = Value;
  85. }
  86. void CompilerInstance::setSourceManager(SourceManager *Value) {
  87. SourceMgr = Value;
  88. }
  89. void CompilerInstance::setPreprocessor(std::shared_ptr<Preprocessor> Value) {
  90. PP = std::move(Value);
  91. }
  92. void CompilerInstance::setASTContext(ASTContext *Value) {
  93. Context = Value;
  94. if (Context && Consumer)
  95. getASTConsumer().Initialize(getASTContext());
  96. }
  97. void CompilerInstance::setSema(Sema *S) {
  98. TheSema.reset(S);
  99. }
  100. void CompilerInstance::setASTConsumer(std::unique_ptr<ASTConsumer> Value) {
  101. Consumer = std::move(Value);
  102. if (Context && Consumer)
  103. getASTConsumer().Initialize(getASTContext());
  104. }
  105. void CompilerInstance::setCodeCompletionConsumer(CodeCompleteConsumer *Value) {
  106. CompletionConsumer.reset(Value);
  107. }
  108. std::unique_ptr<Sema> CompilerInstance::takeSema() {
  109. return std::move(TheSema);
  110. }
  111. IntrusiveRefCntPtr<ASTReader> CompilerInstance::getModuleManager() const {
  112. return ModuleManager;
  113. }
  114. void CompilerInstance::setModuleManager(IntrusiveRefCntPtr<ASTReader> Reader) {
  115. assert(ModuleCache.get() == &Reader->getModuleManager().getModuleCache() &&
  116. "Expected ASTReader to use the same PCM cache");
  117. ModuleManager = std::move(Reader);
  118. }
  119. std::shared_ptr<ModuleDependencyCollector>
  120. CompilerInstance::getModuleDepCollector() const {
  121. return ModuleDepCollector;
  122. }
  123. void CompilerInstance::setModuleDepCollector(
  124. std::shared_ptr<ModuleDependencyCollector> Collector) {
  125. ModuleDepCollector = std::move(Collector);
  126. }
  127. static void collectHeaderMaps(const HeaderSearch &HS,
  128. std::shared_ptr<ModuleDependencyCollector> MDC) {
  129. SmallVector<std::string, 4> HeaderMapFileNames;
  130. HS.getHeaderMapFileNames(HeaderMapFileNames);
  131. for (auto &Name : HeaderMapFileNames)
  132. MDC->addFile(Name);
  133. }
  134. static void collectIncludePCH(CompilerInstance &CI,
  135. std::shared_ptr<ModuleDependencyCollector> MDC) {
  136. const PreprocessorOptions &PPOpts = CI.getPreprocessorOpts();
  137. if (PPOpts.ImplicitPCHInclude.empty())
  138. return;
  139. StringRef PCHInclude = PPOpts.ImplicitPCHInclude;
  140. FileManager &FileMgr = CI.getFileManager();
  141. auto PCHDir = FileMgr.getDirectory(PCHInclude);
  142. if (!PCHDir) {
  143. MDC->addFile(PCHInclude);
  144. return;
  145. }
  146. std::error_code EC;
  147. SmallString<128> DirNative;
  148. llvm::sys::path::native((*PCHDir)->getName(), DirNative);
  149. llvm::vfs::FileSystem &FS = FileMgr.getVirtualFileSystem();
  150. SimpleASTReaderListener Validator(CI.getPreprocessor());
  151. for (llvm::vfs::directory_iterator Dir = FS.dir_begin(DirNative, EC), DirEnd;
  152. Dir != DirEnd && !EC; Dir.increment(EC)) {
  153. // Check whether this is an AST file. ASTReader::isAcceptableASTFile is not
  154. // used here since we're not interested in validating the PCH at this time,
  155. // but only to check whether this is a file containing an AST.
  156. if (!ASTReader::readASTFileControlBlock(
  157. Dir->path(), FileMgr, CI.getPCHContainerReader(),
  158. /*FindModuleFileExtensions=*/false, Validator,
  159. /*ValidateDiagnosticOptions=*/false))
  160. MDC->addFile(Dir->path());
  161. }
  162. }
  163. static void collectVFSEntries(CompilerInstance &CI,
  164. std::shared_ptr<ModuleDependencyCollector> MDC) {
  165. if (CI.getHeaderSearchOpts().VFSOverlayFiles.empty())
  166. return;
  167. // Collect all VFS found.
  168. SmallVector<llvm::vfs::YAMLVFSEntry, 16> VFSEntries;
  169. for (const std::string &VFSFile : CI.getHeaderSearchOpts().VFSOverlayFiles) {
  170. llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> Buffer =
  171. llvm::MemoryBuffer::getFile(VFSFile);
  172. if (!Buffer)
  173. return;
  174. llvm::vfs::collectVFSFromYAML(std::move(Buffer.get()),
  175. /*DiagHandler*/ nullptr, VFSFile, VFSEntries);
  176. }
  177. for (auto &E : VFSEntries)
  178. MDC->addFile(E.VPath, E.RPath);
  179. }
  180. // Diagnostics
  181. static void SetUpDiagnosticLog(DiagnosticOptions *DiagOpts,
  182. const CodeGenOptions *CodeGenOpts,
  183. DiagnosticsEngine &Diags) {
  184. std::error_code EC;
  185. std::unique_ptr<raw_ostream> StreamOwner;
  186. raw_ostream *OS = &llvm::errs();
  187. if (DiagOpts->DiagnosticLogFile != "-") {
  188. // Create the output stream.
  189. auto FileOS = std::make_unique<llvm::raw_fd_ostream>(
  190. DiagOpts->DiagnosticLogFile, EC,
  191. llvm::sys::fs::OF_Append | llvm::sys::fs::OF_Text);
  192. if (EC) {
  193. Diags.Report(diag::warn_fe_cc_log_diagnostics_failure)
  194. << DiagOpts->DiagnosticLogFile << EC.message();
  195. } else {
  196. FileOS->SetUnbuffered();
  197. OS = FileOS.get();
  198. StreamOwner = std::move(FileOS);
  199. }
  200. }
  201. // Chain in the diagnostic client which will log the diagnostics.
  202. auto Logger = std::make_unique<LogDiagnosticPrinter>(*OS, DiagOpts,
  203. std::move(StreamOwner));
  204. if (CodeGenOpts)
  205. Logger->setDwarfDebugFlags(CodeGenOpts->DwarfDebugFlags);
  206. if (Diags.ownsClient()) {
  207. Diags.setClient(
  208. new ChainedDiagnosticConsumer(Diags.takeClient(), std::move(Logger)));
  209. } else {
  210. Diags.setClient(
  211. new ChainedDiagnosticConsumer(Diags.getClient(), std::move(Logger)));
  212. }
  213. }
  214. static void SetupSerializedDiagnostics(DiagnosticOptions *DiagOpts,
  215. DiagnosticsEngine &Diags,
  216. StringRef OutputFile) {
  217. auto SerializedConsumer =
  218. clang::serialized_diags::create(OutputFile, DiagOpts);
  219. if (Diags.ownsClient()) {
  220. Diags.setClient(new ChainedDiagnosticConsumer(
  221. Diags.takeClient(), std::move(SerializedConsumer)));
  222. } else {
  223. Diags.setClient(new ChainedDiagnosticConsumer(
  224. Diags.getClient(), std::move(SerializedConsumer)));
  225. }
  226. }
  227. void CompilerInstance::createDiagnostics(DiagnosticConsumer *Client,
  228. bool ShouldOwnClient) {
  229. Diagnostics = createDiagnostics(&getDiagnosticOpts(), Client,
  230. ShouldOwnClient, &getCodeGenOpts());
  231. }
  232. IntrusiveRefCntPtr<DiagnosticsEngine>
  233. CompilerInstance::createDiagnostics(DiagnosticOptions *Opts,
  234. DiagnosticConsumer *Client,
  235. bool ShouldOwnClient,
  236. const CodeGenOptions *CodeGenOpts) {
  237. IntrusiveRefCntPtr<DiagnosticIDs> DiagID(new DiagnosticIDs());
  238. IntrusiveRefCntPtr<DiagnosticsEngine>
  239. Diags(new DiagnosticsEngine(DiagID, Opts));
  240. // Create the diagnostic client for reporting errors or for
  241. // implementing -verify.
  242. if (Client) {
  243. Diags->setClient(Client, ShouldOwnClient);
  244. } else
  245. Diags->setClient(new TextDiagnosticPrinter(llvm::errs(), Opts));
  246. // Chain in -verify checker, if requested.
  247. if (Opts->VerifyDiagnostics)
  248. Diags->setClient(new VerifyDiagnosticConsumer(*Diags));
  249. // Chain in -diagnostic-log-file dumper, if requested.
  250. if (!Opts->DiagnosticLogFile.empty())
  251. SetUpDiagnosticLog(Opts, CodeGenOpts, *Diags);
  252. if (!Opts->DiagnosticSerializationFile.empty())
  253. SetupSerializedDiagnostics(Opts, *Diags,
  254. Opts->DiagnosticSerializationFile);
  255. // Configure our handling of diagnostics.
  256. ProcessWarningOptions(*Diags, *Opts);
  257. return Diags;
  258. }
  259. // File Manager
  260. FileManager *CompilerInstance::createFileManager(
  261. IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS) {
  262. if (!VFS)
  263. VFS = FileMgr ? &FileMgr->getVirtualFileSystem()
  264. : createVFSFromCompilerInvocation(getInvocation(),
  265. getDiagnostics());
  266. assert(VFS && "FileManager has no VFS?");
  267. FileMgr = new FileManager(getFileSystemOpts(), std::move(VFS));
  268. return FileMgr.get();
  269. }
  270. // Source Manager
  271. void CompilerInstance::createSourceManager(FileManager &FileMgr) {
  272. SourceMgr = new SourceManager(getDiagnostics(), FileMgr);
  273. }
  274. // Initialize the remapping of files to alternative contents, e.g.,
  275. // those specified through other files.
  276. static void InitializeFileRemapping(DiagnosticsEngine &Diags,
  277. SourceManager &SourceMgr,
  278. FileManager &FileMgr,
  279. const PreprocessorOptions &InitOpts) {
  280. // Remap files in the source manager (with buffers).
  281. for (const auto &RB : InitOpts.RemappedFileBuffers) {
  282. // Create the file entry for the file that we're mapping from.
  283. const FileEntry *FromFile =
  284. FileMgr.getVirtualFile(RB.first, RB.second->getBufferSize(), 0);
  285. if (!FromFile) {
  286. Diags.Report(diag::err_fe_remap_missing_from_file) << RB.first;
  287. if (!InitOpts.RetainRemappedFileBuffers)
  288. delete RB.second;
  289. continue;
  290. }
  291. // Override the contents of the "from" file with the contents of
  292. // the "to" file.
  293. SourceMgr.overrideFileContents(FromFile, RB.second,
  294. InitOpts.RetainRemappedFileBuffers);
  295. }
  296. // Remap files in the source manager (with other files).
  297. for (const auto &RF : InitOpts.RemappedFiles) {
  298. // Find the file that we're mapping to.
  299. auto ToFile = FileMgr.getFile(RF.second);
  300. if (!ToFile) {
  301. Diags.Report(diag::err_fe_remap_missing_to_file) << RF.first << RF.second;
  302. continue;
  303. }
  304. // Create the file entry for the file that we're mapping from.
  305. const FileEntry *FromFile =
  306. FileMgr.getVirtualFile(RF.first, (*ToFile)->getSize(), 0);
  307. if (!FromFile) {
  308. Diags.Report(diag::err_fe_remap_missing_from_file) << RF.first;
  309. continue;
  310. }
  311. // Override the contents of the "from" file with the contents of
  312. // the "to" file.
  313. SourceMgr.overrideFileContents(FromFile, *ToFile);
  314. }
  315. SourceMgr.setOverridenFilesKeepOriginalName(
  316. InitOpts.RemappedFilesKeepOriginalName);
  317. }
  318. // Preprocessor
  319. void CompilerInstance::createPreprocessor(TranslationUnitKind TUKind) {
  320. const PreprocessorOptions &PPOpts = getPreprocessorOpts();
  321. // The module manager holds a reference to the old preprocessor (if any).
  322. ModuleManager.reset();
  323. // Create the Preprocessor.
  324. HeaderSearch *HeaderInfo =
  325. new HeaderSearch(getHeaderSearchOptsPtr(), getSourceManager(),
  326. getDiagnostics(), getLangOpts(), &getTarget());
  327. PP = std::make_shared<Preprocessor>(Invocation->getPreprocessorOptsPtr(),
  328. getDiagnostics(), getLangOpts(),
  329. getSourceManager(), *HeaderInfo, *this,
  330. /*IdentifierInfoLookup=*/nullptr,
  331. /*OwnsHeaderSearch=*/true, TUKind);
  332. getTarget().adjust(getLangOpts());
  333. PP->Initialize(getTarget(), getAuxTarget());
  334. if (PPOpts.DetailedRecord)
  335. PP->createPreprocessingRecord();
  336. // Apply remappings to the source manager.
  337. InitializeFileRemapping(PP->getDiagnostics(), PP->getSourceManager(),
  338. PP->getFileManager(), PPOpts);
  339. // Predefine macros and configure the preprocessor.
  340. InitializePreprocessor(*PP, PPOpts, getPCHContainerReader(),
  341. getFrontendOpts());
  342. // Initialize the header search object. In CUDA compilations, we use the aux
  343. // triple (the host triple) to initialize our header search, since we need to
  344. // find the host headers in order to compile the CUDA code.
  345. const llvm::Triple *HeaderSearchTriple = &PP->getTargetInfo().getTriple();
  346. if (PP->getTargetInfo().getTriple().getOS() == llvm::Triple::CUDA &&
  347. PP->getAuxTargetInfo())
  348. HeaderSearchTriple = &PP->getAuxTargetInfo()->getTriple();
  349. ApplyHeaderSearchOptions(PP->getHeaderSearchInfo(), getHeaderSearchOpts(),
  350. PP->getLangOpts(), *HeaderSearchTriple);
  351. PP->setPreprocessedOutput(getPreprocessorOutputOpts().ShowCPP);
  352. if (PP->getLangOpts().Modules && PP->getLangOpts().ImplicitModules)
  353. PP->getHeaderSearchInfo().setModuleCachePath(getSpecificModuleCachePath());
  354. // Handle generating dependencies, if requested.
  355. const DependencyOutputOptions &DepOpts = getDependencyOutputOpts();
  356. if (!DepOpts.OutputFile.empty())
  357. addDependencyCollector(std::make_shared<DependencyFileGenerator>(DepOpts));
  358. if (!DepOpts.DOTOutputFile.empty())
  359. AttachDependencyGraphGen(*PP, DepOpts.DOTOutputFile,
  360. getHeaderSearchOpts().Sysroot);
  361. // If we don't have a collector, but we are collecting module dependencies,
  362. // then we're the top level compiler instance and need to create one.
  363. if (!ModuleDepCollector && !DepOpts.ModuleDependencyOutputDir.empty()) {
  364. ModuleDepCollector = std::make_shared<ModuleDependencyCollector>(
  365. DepOpts.ModuleDependencyOutputDir);
  366. }
  367. // If there is a module dep collector, register with other dep collectors
  368. // and also (a) collect header maps and (b) TODO: input vfs overlay files.
  369. if (ModuleDepCollector) {
  370. addDependencyCollector(ModuleDepCollector);
  371. collectHeaderMaps(PP->getHeaderSearchInfo(), ModuleDepCollector);
  372. collectIncludePCH(*this, ModuleDepCollector);
  373. collectVFSEntries(*this, ModuleDepCollector);
  374. }
  375. for (auto &Listener : DependencyCollectors)
  376. Listener->attachToPreprocessor(*PP);
  377. // Handle generating header include information, if requested.
  378. if (DepOpts.ShowHeaderIncludes)
  379. AttachHeaderIncludeGen(*PP, DepOpts);
  380. if (!DepOpts.HeaderIncludeOutputFile.empty()) {
  381. StringRef OutputPath = DepOpts.HeaderIncludeOutputFile;
  382. if (OutputPath == "-")
  383. OutputPath = "";
  384. AttachHeaderIncludeGen(*PP, DepOpts,
  385. /*ShowAllHeaders=*/true, OutputPath,
  386. /*ShowDepth=*/false);
  387. }
  388. if (DepOpts.ShowIncludesDest != ShowIncludesDestination::None) {
  389. AttachHeaderIncludeGen(*PP, DepOpts,
  390. /*ShowAllHeaders=*/true, /*OutputPath=*/"",
  391. /*ShowDepth=*/true, /*MSStyle=*/true);
  392. }
  393. }
  394. std::string CompilerInstance::getSpecificModuleCachePath() {
  395. // Set up the module path, including the hash for the
  396. // module-creation options.
  397. SmallString<256> SpecificModuleCache(getHeaderSearchOpts().ModuleCachePath);
  398. if (!SpecificModuleCache.empty() && !getHeaderSearchOpts().DisableModuleHash)
  399. llvm::sys::path::append(SpecificModuleCache,
  400. getInvocation().getModuleHash());
  401. return SpecificModuleCache.str();
  402. }
  403. // ASTContext
  404. void CompilerInstance::createASTContext() {
  405. Preprocessor &PP = getPreprocessor();
  406. auto *Context = new ASTContext(getLangOpts(), PP.getSourceManager(),
  407. PP.getIdentifierTable(), PP.getSelectorTable(),
  408. PP.getBuiltinInfo());
  409. Context->InitBuiltinTypes(getTarget(), getAuxTarget());
  410. setASTContext(Context);
  411. }
  412. // ExternalASTSource
  413. void CompilerInstance::createPCHExternalASTSource(
  414. StringRef Path, bool DisablePCHValidation, bool AllowPCHWithCompilerErrors,
  415. void *DeserializationListener, bool OwnDeserializationListener) {
  416. bool Preamble = getPreprocessorOpts().PrecompiledPreambleBytes.first != 0;
  417. ModuleManager = createPCHExternalASTSource(
  418. Path, getHeaderSearchOpts().Sysroot, DisablePCHValidation,
  419. AllowPCHWithCompilerErrors, getPreprocessor(), getModuleCache(),
  420. getASTContext(), getPCHContainerReader(),
  421. getFrontendOpts().ModuleFileExtensions, DependencyCollectors,
  422. DeserializationListener, OwnDeserializationListener, Preamble,
  423. getFrontendOpts().UseGlobalModuleIndex);
  424. }
  425. IntrusiveRefCntPtr<ASTReader> CompilerInstance::createPCHExternalASTSource(
  426. StringRef Path, StringRef Sysroot, bool DisablePCHValidation,
  427. bool AllowPCHWithCompilerErrors, Preprocessor &PP,
  428. InMemoryModuleCache &ModuleCache, ASTContext &Context,
  429. const PCHContainerReader &PCHContainerRdr,
  430. ArrayRef<std::shared_ptr<ModuleFileExtension>> Extensions,
  431. ArrayRef<std::shared_ptr<DependencyCollector>> DependencyCollectors,
  432. void *DeserializationListener, bool OwnDeserializationListener,
  433. bool Preamble, bool UseGlobalModuleIndex) {
  434. HeaderSearchOptions &HSOpts = PP.getHeaderSearchInfo().getHeaderSearchOpts();
  435. IntrusiveRefCntPtr<ASTReader> Reader(new ASTReader(
  436. PP, ModuleCache, &Context, PCHContainerRdr, Extensions,
  437. Sysroot.empty() ? "" : Sysroot.data(), DisablePCHValidation,
  438. AllowPCHWithCompilerErrors, /*AllowConfigurationMismatch*/ false,
  439. HSOpts.ModulesValidateSystemHeaders, UseGlobalModuleIndex));
  440. // We need the external source to be set up before we read the AST, because
  441. // eagerly-deserialized declarations may use it.
  442. Context.setExternalSource(Reader.get());
  443. Reader->setDeserializationListener(
  444. static_cast<ASTDeserializationListener *>(DeserializationListener),
  445. /*TakeOwnership=*/OwnDeserializationListener);
  446. for (auto &Listener : DependencyCollectors)
  447. Listener->attachToASTReader(*Reader);
  448. switch (Reader->ReadAST(Path,
  449. Preamble ? serialization::MK_Preamble
  450. : serialization::MK_PCH,
  451. SourceLocation(),
  452. ASTReader::ARR_None)) {
  453. case ASTReader::Success:
  454. // Set the predefines buffer as suggested by the PCH reader. Typically, the
  455. // predefines buffer will be empty.
  456. PP.setPredefines(Reader->getSuggestedPredefines());
  457. return Reader;
  458. case ASTReader::Failure:
  459. // Unrecoverable failure: don't even try to process the input file.
  460. break;
  461. case ASTReader::Missing:
  462. case ASTReader::OutOfDate:
  463. case ASTReader::VersionMismatch:
  464. case ASTReader::ConfigurationMismatch:
  465. case ASTReader::HadErrors:
  466. // No suitable PCH file could be found. Return an error.
  467. break;
  468. }
  469. Context.setExternalSource(nullptr);
  470. return nullptr;
  471. }
  472. // Code Completion
  473. static bool EnableCodeCompletion(Preprocessor &PP,
  474. StringRef Filename,
  475. unsigned Line,
  476. unsigned Column) {
  477. // Tell the source manager to chop off the given file at a specific
  478. // line and column.
  479. auto Entry = PP.getFileManager().getFile(Filename);
  480. if (!Entry) {
  481. PP.getDiagnostics().Report(diag::err_fe_invalid_code_complete_file)
  482. << Filename;
  483. return true;
  484. }
  485. // Truncate the named file at the given line/column.
  486. PP.SetCodeCompletionPoint(*Entry, Line, Column);
  487. return false;
  488. }
  489. void CompilerInstance::createCodeCompletionConsumer() {
  490. const ParsedSourceLocation &Loc = getFrontendOpts().CodeCompletionAt;
  491. if (!CompletionConsumer) {
  492. setCodeCompletionConsumer(
  493. createCodeCompletionConsumer(getPreprocessor(),
  494. Loc.FileName, Loc.Line, Loc.Column,
  495. getFrontendOpts().CodeCompleteOpts,
  496. llvm::outs()));
  497. if (!CompletionConsumer)
  498. return;
  499. } else if (EnableCodeCompletion(getPreprocessor(), Loc.FileName,
  500. Loc.Line, Loc.Column)) {
  501. setCodeCompletionConsumer(nullptr);
  502. return;
  503. }
  504. }
  505. void CompilerInstance::createFrontendTimer() {
  506. FrontendTimerGroup.reset(
  507. new llvm::TimerGroup("frontend", "Clang front-end time report"));
  508. FrontendTimer.reset(
  509. new llvm::Timer("frontend", "Clang front-end timer",
  510. *FrontendTimerGroup));
  511. }
  512. CodeCompleteConsumer *
  513. CompilerInstance::createCodeCompletionConsumer(Preprocessor &PP,
  514. StringRef Filename,
  515. unsigned Line,
  516. unsigned Column,
  517. const CodeCompleteOptions &Opts,
  518. raw_ostream &OS) {
  519. if (EnableCodeCompletion(PP, Filename, Line, Column))
  520. return nullptr;
  521. // Set up the creation routine for code-completion.
  522. return new PrintingCodeCompleteConsumer(Opts, OS);
  523. }
  524. void CompilerInstance::createSema(TranslationUnitKind TUKind,
  525. CodeCompleteConsumer *CompletionConsumer) {
  526. TheSema.reset(new Sema(getPreprocessor(), getASTContext(), getASTConsumer(),
  527. TUKind, CompletionConsumer));
  528. // Attach the external sema source if there is any.
  529. if (ExternalSemaSrc) {
  530. TheSema->addExternalSource(ExternalSemaSrc.get());
  531. ExternalSemaSrc->InitializeSema(*TheSema);
  532. }
  533. }
  534. // Output Files
  535. void CompilerInstance::addOutputFile(OutputFile &&OutFile) {
  536. OutputFiles.push_back(std::move(OutFile));
  537. }
  538. void CompilerInstance::clearOutputFiles(bool EraseFiles) {
  539. for (OutputFile &OF : OutputFiles) {
  540. if (!OF.TempFilename.empty()) {
  541. if (EraseFiles) {
  542. llvm::sys::fs::remove(OF.TempFilename);
  543. } else {
  544. SmallString<128> NewOutFile(OF.Filename);
  545. // If '-working-directory' was passed, the output filename should be
  546. // relative to that.
  547. FileMgr->FixupRelativePath(NewOutFile);
  548. if (std::error_code ec =
  549. llvm::sys::fs::rename(OF.TempFilename, NewOutFile)) {
  550. getDiagnostics().Report(diag::err_unable_to_rename_temp)
  551. << OF.TempFilename << OF.Filename << ec.message();
  552. llvm::sys::fs::remove(OF.TempFilename);
  553. }
  554. }
  555. } else if (!OF.Filename.empty() && EraseFiles)
  556. llvm::sys::fs::remove(OF.Filename);
  557. }
  558. OutputFiles.clear();
  559. if (DeleteBuiltModules) {
  560. for (auto &Module : BuiltModules)
  561. llvm::sys::fs::remove(Module.second);
  562. BuiltModules.clear();
  563. }
  564. NonSeekStream.reset();
  565. }
  566. std::unique_ptr<raw_pwrite_stream>
  567. CompilerInstance::createDefaultOutputFile(bool Binary, StringRef InFile,
  568. StringRef Extension) {
  569. return createOutputFile(getFrontendOpts().OutputFile, Binary,
  570. /*RemoveFileOnSignal=*/true, InFile, Extension,
  571. /*UseTemporary=*/true);
  572. }
  573. std::unique_ptr<raw_pwrite_stream> CompilerInstance::createNullOutputFile() {
  574. return std::make_unique<llvm::raw_null_ostream>();
  575. }
  576. std::unique_ptr<raw_pwrite_stream>
  577. CompilerInstance::createOutputFile(StringRef OutputPath, bool Binary,
  578. bool RemoveFileOnSignal, StringRef InFile,
  579. StringRef Extension, bool UseTemporary,
  580. bool CreateMissingDirectories) {
  581. std::string OutputPathName, TempPathName;
  582. std::error_code EC;
  583. std::unique_ptr<raw_pwrite_stream> OS = createOutputFile(
  584. OutputPath, EC, Binary, RemoveFileOnSignal, InFile, Extension,
  585. UseTemporary, CreateMissingDirectories, &OutputPathName, &TempPathName);
  586. if (!OS) {
  587. getDiagnostics().Report(diag::err_fe_unable_to_open_output) << OutputPath
  588. << EC.message();
  589. return nullptr;
  590. }
  591. // Add the output file -- but don't try to remove "-", since this means we are
  592. // using stdin.
  593. addOutputFile(
  594. OutputFile((OutputPathName != "-") ? OutputPathName : "", TempPathName));
  595. return OS;
  596. }
  597. std::unique_ptr<llvm::raw_pwrite_stream> CompilerInstance::createOutputFile(
  598. StringRef OutputPath, std::error_code &Error, bool Binary,
  599. bool RemoveFileOnSignal, StringRef InFile, StringRef Extension,
  600. bool UseTemporary, bool CreateMissingDirectories,
  601. std::string *ResultPathName, std::string *TempPathName) {
  602. assert((!CreateMissingDirectories || UseTemporary) &&
  603. "CreateMissingDirectories is only allowed when using temporary files");
  604. std::string OutFile, TempFile;
  605. if (!OutputPath.empty()) {
  606. OutFile = OutputPath;
  607. } else if (InFile == "-") {
  608. OutFile = "-";
  609. } else if (!Extension.empty()) {
  610. SmallString<128> Path(InFile);
  611. llvm::sys::path::replace_extension(Path, Extension);
  612. OutFile = Path.str();
  613. } else {
  614. OutFile = "-";
  615. }
  616. std::unique_ptr<llvm::raw_fd_ostream> OS;
  617. std::string OSFile;
  618. if (UseTemporary) {
  619. if (OutFile == "-")
  620. UseTemporary = false;
  621. else {
  622. llvm::sys::fs::file_status Status;
  623. llvm::sys::fs::status(OutputPath, Status);
  624. if (llvm::sys::fs::exists(Status)) {
  625. // Fail early if we can't write to the final destination.
  626. if (!llvm::sys::fs::can_write(OutputPath)) {
  627. Error = make_error_code(llvm::errc::operation_not_permitted);
  628. return nullptr;
  629. }
  630. // Don't use a temporary if the output is a special file. This handles
  631. // things like '-o /dev/null'
  632. if (!llvm::sys::fs::is_regular_file(Status))
  633. UseTemporary = false;
  634. }
  635. }
  636. }
  637. if (UseTemporary) {
  638. // Create a temporary file.
  639. // Insert -%%%%%%%% before the extension (if any), and because some tools
  640. // (noticeable, clang's own GlobalModuleIndex.cpp) glob for build
  641. // artifacts, also append .tmp.
  642. StringRef OutputExtension = llvm::sys::path::extension(OutFile);
  643. SmallString<128> TempPath =
  644. StringRef(OutFile).drop_back(OutputExtension.size());
  645. TempPath += "-%%%%%%%%";
  646. TempPath += OutputExtension;
  647. TempPath += ".tmp";
  648. int fd;
  649. std::error_code EC =
  650. llvm::sys::fs::createUniqueFile(TempPath, fd, TempPath);
  651. if (CreateMissingDirectories &&
  652. EC == llvm::errc::no_such_file_or_directory) {
  653. StringRef Parent = llvm::sys::path::parent_path(OutputPath);
  654. EC = llvm::sys::fs::create_directories(Parent);
  655. if (!EC) {
  656. EC = llvm::sys::fs::createUniqueFile(TempPath, fd, TempPath);
  657. }
  658. }
  659. if (!EC) {
  660. OS.reset(new llvm::raw_fd_ostream(fd, /*shouldClose=*/true));
  661. OSFile = TempFile = TempPath.str();
  662. }
  663. // If we failed to create the temporary, fallback to writing to the file
  664. // directly. This handles the corner case where we cannot write to the
  665. // directory, but can write to the file.
  666. }
  667. if (!OS) {
  668. OSFile = OutFile;
  669. OS.reset(new llvm::raw_fd_ostream(
  670. OSFile, Error,
  671. (Binary ? llvm::sys::fs::OF_None : llvm::sys::fs::OF_Text)));
  672. if (Error)
  673. return nullptr;
  674. }
  675. // Make sure the out stream file gets removed if we crash.
  676. if (RemoveFileOnSignal)
  677. llvm::sys::RemoveFileOnSignal(OSFile);
  678. if (ResultPathName)
  679. *ResultPathName = OutFile;
  680. if (TempPathName)
  681. *TempPathName = TempFile;
  682. if (!Binary || OS->supportsSeeking())
  683. return std::move(OS);
  684. auto B = std::make_unique<llvm::buffer_ostream>(*OS);
  685. assert(!NonSeekStream);
  686. NonSeekStream = std::move(OS);
  687. return std::move(B);
  688. }
  689. // Initialization Utilities
  690. bool CompilerInstance::InitializeSourceManager(const FrontendInputFile &Input){
  691. return InitializeSourceManager(
  692. Input, getDiagnostics(), getFileManager(), getSourceManager(),
  693. hasPreprocessor() ? &getPreprocessor().getHeaderSearchInfo() : nullptr,
  694. getDependencyOutputOpts(), getFrontendOpts());
  695. }
  696. // static
  697. bool CompilerInstance::InitializeSourceManager(
  698. const FrontendInputFile &Input, DiagnosticsEngine &Diags,
  699. FileManager &FileMgr, SourceManager &SourceMgr, HeaderSearch *HS,
  700. DependencyOutputOptions &DepOpts, const FrontendOptions &Opts) {
  701. SrcMgr::CharacteristicKind Kind =
  702. Input.getKind().getFormat() == InputKind::ModuleMap
  703. ? Input.isSystem() ? SrcMgr::C_System_ModuleMap
  704. : SrcMgr::C_User_ModuleMap
  705. : Input.isSystem() ? SrcMgr::C_System : SrcMgr::C_User;
  706. if (Input.isBuffer()) {
  707. SourceMgr.setMainFileID(SourceMgr.createFileID(SourceManager::Unowned,
  708. Input.getBuffer(), Kind));
  709. assert(SourceMgr.getMainFileID().isValid() &&
  710. "Couldn't establish MainFileID!");
  711. return true;
  712. }
  713. StringRef InputFile = Input.getFile();
  714. // Figure out where to get and map in the main file.
  715. if (InputFile != "-") {
  716. auto FileOrErr = FileMgr.getFileRef(InputFile, /*OpenFile=*/true);
  717. if (!FileOrErr) {
  718. Diags.Report(diag::err_fe_error_reading) << InputFile;
  719. return false;
  720. }
  721. FileEntryRef File = *FileOrErr;
  722. // The natural SourceManager infrastructure can't currently handle named
  723. // pipes, but we would at least like to accept them for the main
  724. // file. Detect them here, read them with the volatile flag so FileMgr will
  725. // pick up the correct size, and simply override their contents as we do for
  726. // STDIN.
  727. if (File.getFileEntry().isNamedPipe()) {
  728. auto MB =
  729. FileMgr.getBufferForFile(&File.getFileEntry(), /*isVolatile=*/true);
  730. if (MB) {
  731. // Create a new virtual file that will have the correct size.
  732. const FileEntry *FE =
  733. FileMgr.getVirtualFile(InputFile, (*MB)->getBufferSize(), 0);
  734. SourceMgr.overrideFileContents(FE, std::move(*MB));
  735. SourceMgr.setMainFileID(
  736. SourceMgr.createFileID(FE, SourceLocation(), Kind));
  737. } else {
  738. Diags.Report(diag::err_cannot_open_file) << InputFile
  739. << MB.getError().message();
  740. return false;
  741. }
  742. } else {
  743. SourceMgr.setMainFileID(
  744. SourceMgr.createFileID(File, SourceLocation(), Kind));
  745. }
  746. } else {
  747. llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> SBOrErr =
  748. llvm::MemoryBuffer::getSTDIN();
  749. if (std::error_code EC = SBOrErr.getError()) {
  750. Diags.Report(diag::err_fe_error_reading_stdin) << EC.message();
  751. return false;
  752. }
  753. std::unique_ptr<llvm::MemoryBuffer> SB = std::move(SBOrErr.get());
  754. const FileEntry *File = FileMgr.getVirtualFile(SB->getBufferIdentifier(),
  755. SB->getBufferSize(), 0);
  756. SourceMgr.setMainFileID(
  757. SourceMgr.createFileID(File, SourceLocation(), Kind));
  758. SourceMgr.overrideFileContents(File, std::move(SB));
  759. }
  760. assert(SourceMgr.getMainFileID().isValid() &&
  761. "Couldn't establish MainFileID!");
  762. return true;
  763. }
  764. // High-Level Operations
  765. bool CompilerInstance::ExecuteAction(FrontendAction &Act) {
  766. assert(hasDiagnostics() && "Diagnostics engine is not initialized!");
  767. assert(!getFrontendOpts().ShowHelp && "Client must handle '-help'!");
  768. assert(!getFrontendOpts().ShowVersion && "Client must handle '-version'!");
  769. // FIXME: Take this as an argument, once all the APIs we used have moved to
  770. // taking it as an input instead of hard-coding llvm::errs.
  771. raw_ostream &OS = llvm::errs();
  772. if (!Act.PrepareToExecute(*this))
  773. return false;
  774. // Create the target instance.
  775. setTarget(TargetInfo::CreateTargetInfo(getDiagnostics(),
  776. getInvocation().TargetOpts));
  777. if (!hasTarget())
  778. return false;
  779. // Create TargetInfo for the other side of CUDA and OpenMP compilation.
  780. if ((getLangOpts().CUDA || getLangOpts().OpenMPIsDevice) &&
  781. !getFrontendOpts().AuxTriple.empty()) {
  782. auto TO = std::make_shared<TargetOptions>();
  783. TO->Triple = llvm::Triple::normalize(getFrontendOpts().AuxTriple);
  784. TO->HostTriple = getTarget().getTriple().str();
  785. setAuxTarget(TargetInfo::CreateTargetInfo(getDiagnostics(), TO));
  786. }
  787. // Inform the target of the language options.
  788. //
  789. // FIXME: We shouldn't need to do this, the target should be immutable once
  790. // created. This complexity should be lifted elsewhere.
  791. getTarget().adjust(getLangOpts());
  792. // Adjust target options based on codegen options.
  793. getTarget().adjustTargetOptions(getCodeGenOpts(), getTargetOpts());
  794. if (auto *Aux = getAuxTarget())
  795. getTarget().setAuxTarget(Aux);
  796. // rewriter project will change target built-in bool type from its default.
  797. if (getFrontendOpts().ProgramAction == frontend::RewriteObjC)
  798. getTarget().noSignedCharForObjCBool();
  799. // Validate/process some options.
  800. if (getHeaderSearchOpts().Verbose)
  801. OS << "clang -cc1 version " CLANG_VERSION_STRING
  802. << " based upon " << BACKEND_PACKAGE_STRING
  803. << " default target " << llvm::sys::getDefaultTargetTriple() << "\n";
  804. if (getFrontendOpts().ShowTimers)
  805. createFrontendTimer();
  806. if (getFrontendOpts().ShowStats || !getFrontendOpts().StatsFile.empty())
  807. llvm::EnableStatistics(false);
  808. for (const FrontendInputFile &FIF : getFrontendOpts().Inputs) {
  809. // Reset the ID tables if we are reusing the SourceManager and parsing
  810. // regular files.
  811. if (hasSourceManager() && !Act.isModelParsingAction())
  812. getSourceManager().clearIDTables();
  813. if (Act.BeginSourceFile(*this, FIF)) {
  814. if (llvm::Error Err = Act.Execute()) {
  815. consumeError(std::move(Err)); // FIXME this drops errors on the floor.
  816. }
  817. Act.EndSourceFile();
  818. }
  819. }
  820. // Notify the diagnostic client that all files were processed.
  821. getDiagnostics().getClient()->finish();
  822. if (getDiagnosticOpts().ShowCarets) {
  823. // We can have multiple diagnostics sharing one diagnostic client.
  824. // Get the total number of warnings/errors from the client.
  825. unsigned NumWarnings = getDiagnostics().getClient()->getNumWarnings();
  826. unsigned NumErrors = getDiagnostics().getClient()->getNumErrors();
  827. if (NumWarnings)
  828. OS << NumWarnings << " warning" << (NumWarnings == 1 ? "" : "s");
  829. if (NumWarnings && NumErrors)
  830. OS << " and ";
  831. if (NumErrors)
  832. OS << NumErrors << " error" << (NumErrors == 1 ? "" : "s");
  833. if (NumWarnings || NumErrors) {
  834. OS << " generated";
  835. if (getLangOpts().CUDA) {
  836. if (!getLangOpts().CUDAIsDevice) {
  837. OS << " when compiling for host";
  838. } else {
  839. OS << " when compiling for " << getTargetOpts().CPU;
  840. }
  841. }
  842. OS << ".\n";
  843. }
  844. }
  845. if (getFrontendOpts().ShowStats) {
  846. if (hasFileManager()) {
  847. getFileManager().PrintStats();
  848. OS << '\n';
  849. }
  850. llvm::PrintStatistics(OS);
  851. }
  852. StringRef StatsFile = getFrontendOpts().StatsFile;
  853. if (!StatsFile.empty()) {
  854. std::error_code EC;
  855. auto StatS = std::make_unique<llvm::raw_fd_ostream>(
  856. StatsFile, EC, llvm::sys::fs::OF_Text);
  857. if (EC) {
  858. getDiagnostics().Report(diag::warn_fe_unable_to_open_stats_file)
  859. << StatsFile << EC.message();
  860. } else {
  861. llvm::PrintStatisticsJSON(*StatS);
  862. }
  863. }
  864. return !getDiagnostics().getClient()->getNumErrors();
  865. }
  866. /// Determine the appropriate source input kind based on language
  867. /// options.
  868. static Language getLanguageFromOptions(const LangOptions &LangOpts) {
  869. if (LangOpts.OpenCL)
  870. return Language::OpenCL;
  871. if (LangOpts.CUDA)
  872. return Language::CUDA;
  873. if (LangOpts.ObjC)
  874. return LangOpts.CPlusPlus ? Language::ObjCXX : Language::ObjC;
  875. return LangOpts.CPlusPlus ? Language::CXX : Language::C;
  876. }
  877. /// Compile a module file for the given module, using the options
  878. /// provided by the importing compiler instance. Returns true if the module
  879. /// was built without errors.
  880. static bool
  881. compileModuleImpl(CompilerInstance &ImportingInstance, SourceLocation ImportLoc,
  882. StringRef ModuleName, FrontendInputFile Input,
  883. StringRef OriginalModuleMapFile, StringRef ModuleFileName,
  884. llvm::function_ref<void(CompilerInstance &)> PreBuildStep =
  885. [](CompilerInstance &) {},
  886. llvm::function_ref<void(CompilerInstance &)> PostBuildStep =
  887. [](CompilerInstance &) {}) {
  888. llvm::TimeTraceScope TimeScope("Module Compile", ModuleName);
  889. // Construct a compiler invocation for creating this module.
  890. auto Invocation =
  891. std::make_shared<CompilerInvocation>(ImportingInstance.getInvocation());
  892. PreprocessorOptions &PPOpts = Invocation->getPreprocessorOpts();
  893. // For any options that aren't intended to affect how a module is built,
  894. // reset them to their default values.
  895. Invocation->getLangOpts()->resetNonModularOptions();
  896. PPOpts.resetNonModularOptions();
  897. // Remove any macro definitions that are explicitly ignored by the module.
  898. // They aren't supposed to affect how the module is built anyway.
  899. HeaderSearchOptions &HSOpts = Invocation->getHeaderSearchOpts();
  900. PPOpts.Macros.erase(
  901. std::remove_if(PPOpts.Macros.begin(), PPOpts.Macros.end(),
  902. [&HSOpts](const std::pair<std::string, bool> &def) {
  903. StringRef MacroDef = def.first;
  904. return HSOpts.ModulesIgnoreMacros.count(
  905. llvm::CachedHashString(MacroDef.split('=').first)) > 0;
  906. }),
  907. PPOpts.Macros.end());
  908. // If the original compiler invocation had -fmodule-name, pass it through.
  909. Invocation->getLangOpts()->ModuleName =
  910. ImportingInstance.getInvocation().getLangOpts()->ModuleName;
  911. // Note the name of the module we're building.
  912. Invocation->getLangOpts()->CurrentModule = ModuleName;
  913. // Make sure that the failed-module structure has been allocated in
  914. // the importing instance, and propagate the pointer to the newly-created
  915. // instance.
  916. PreprocessorOptions &ImportingPPOpts
  917. = ImportingInstance.getInvocation().getPreprocessorOpts();
  918. if (!ImportingPPOpts.FailedModules)
  919. ImportingPPOpts.FailedModules =
  920. std::make_shared<PreprocessorOptions::FailedModulesSet>();
  921. PPOpts.FailedModules = ImportingPPOpts.FailedModules;
  922. // If there is a module map file, build the module using the module map.
  923. // Set up the inputs/outputs so that we build the module from its umbrella
  924. // header.
  925. FrontendOptions &FrontendOpts = Invocation->getFrontendOpts();
  926. FrontendOpts.OutputFile = ModuleFileName.str();
  927. FrontendOpts.DisableFree = false;
  928. FrontendOpts.GenerateGlobalModuleIndex = false;
  929. FrontendOpts.BuildingImplicitModule = true;
  930. FrontendOpts.OriginalModuleMap = OriginalModuleMapFile;
  931. // Force implicitly-built modules to hash the content of the module file.
  932. HSOpts.ModulesHashContent = true;
  933. FrontendOpts.Inputs = {Input};
  934. // Don't free the remapped file buffers; they are owned by our caller.
  935. PPOpts.RetainRemappedFileBuffers = true;
  936. Invocation->getDiagnosticOpts().VerifyDiagnostics = 0;
  937. assert(ImportingInstance.getInvocation().getModuleHash() ==
  938. Invocation->getModuleHash() && "Module hash mismatch!");
  939. // Construct a compiler instance that will be used to actually create the
  940. // module. Since we're sharing an in-memory module cache,
  941. // CompilerInstance::CompilerInstance is responsible for finalizing the
  942. // buffers to prevent use-after-frees.
  943. CompilerInstance Instance(ImportingInstance.getPCHContainerOperations(),
  944. &ImportingInstance.getModuleCache());
  945. auto &Inv = *Invocation;
  946. Instance.setInvocation(std::move(Invocation));
  947. Instance.createDiagnostics(new ForwardingDiagnosticConsumer(
  948. ImportingInstance.getDiagnosticClient()),
  949. /*ShouldOwnClient=*/true);
  950. // Note that this module is part of the module build stack, so that we
  951. // can detect cycles in the module graph.
  952. Instance.setFileManager(&ImportingInstance.getFileManager());
  953. Instance.createSourceManager(Instance.getFileManager());
  954. SourceManager &SourceMgr = Instance.getSourceManager();
  955. SourceMgr.setModuleBuildStack(
  956. ImportingInstance.getSourceManager().getModuleBuildStack());
  957. SourceMgr.pushModuleBuildStack(ModuleName,
  958. FullSourceLoc(ImportLoc, ImportingInstance.getSourceManager()));
  959. // If we're collecting module dependencies, we need to share a collector
  960. // between all of the module CompilerInstances. Other than that, we don't
  961. // want to produce any dependency output from the module build.
  962. Instance.setModuleDepCollector(ImportingInstance.getModuleDepCollector());
  963. Inv.getDependencyOutputOpts() = DependencyOutputOptions();
  964. ImportingInstance.getDiagnostics().Report(ImportLoc,
  965. diag::remark_module_build)
  966. << ModuleName << ModuleFileName;
  967. PreBuildStep(Instance);
  968. // Execute the action to actually build the module in-place. Use a separate
  969. // thread so that we get a stack large enough.
  970. llvm::CrashRecoveryContext CRC;
  971. CRC.RunSafelyOnThread(
  972. [&]() {
  973. GenerateModuleFromModuleMapAction Action;
  974. Instance.ExecuteAction(Action);
  975. },
  976. DesiredStackSize);
  977. PostBuildStep(Instance);
  978. ImportingInstance.getDiagnostics().Report(ImportLoc,
  979. diag::remark_module_build_done)
  980. << ModuleName;
  981. // Delete the temporary module map file.
  982. // FIXME: Even though we're executing under crash protection, it would still
  983. // be nice to do this with RemoveFileOnSignal when we can. However, that
  984. // doesn't make sense for all clients, so clean this up manually.
  985. Instance.clearOutputFiles(/*EraseFiles=*/true);
  986. return !Instance.getDiagnostics().hasErrorOccurred();
  987. }
  988. static const FileEntry *getPublicModuleMap(const FileEntry *File,
  989. FileManager &FileMgr) {
  990. StringRef Filename = llvm::sys::path::filename(File->getName());
  991. SmallString<128> PublicFilename(File->getDir()->getName());
  992. if (Filename == "module_private.map")
  993. llvm::sys::path::append(PublicFilename, "module.map");
  994. else if (Filename == "module.private.modulemap")
  995. llvm::sys::path::append(PublicFilename, "module.modulemap");
  996. else
  997. return nullptr;
  998. if (auto FE = FileMgr.getFile(PublicFilename))
  999. return *FE;
  1000. return nullptr;
  1001. }
  1002. /// Compile a module file for the given module, using the options
  1003. /// provided by the importing compiler instance. Returns true if the module
  1004. /// was built without errors.
  1005. static bool compileModuleImpl(CompilerInstance &ImportingInstance,
  1006. SourceLocation ImportLoc,
  1007. Module *Module,
  1008. StringRef ModuleFileName) {
  1009. InputKind IK(getLanguageFromOptions(ImportingInstance.getLangOpts()),
  1010. InputKind::ModuleMap);
  1011. // Get or create the module map that we'll use to build this module.
  1012. ModuleMap &ModMap
  1013. = ImportingInstance.getPreprocessor().getHeaderSearchInfo().getModuleMap();
  1014. bool Result;
  1015. if (const FileEntry *ModuleMapFile =
  1016. ModMap.getContainingModuleMapFile(Module)) {
  1017. // Canonicalize compilation to start with the public module map. This is
  1018. // vital for submodules declarations in the private module maps to be
  1019. // correctly parsed when depending on a top level module in the public one.
  1020. if (const FileEntry *PublicMMFile = getPublicModuleMap(
  1021. ModuleMapFile, ImportingInstance.getFileManager()))
  1022. ModuleMapFile = PublicMMFile;
  1023. // Use the module map where this module resides.
  1024. Result = compileModuleImpl(
  1025. ImportingInstance, ImportLoc, Module->getTopLevelModuleName(),
  1026. FrontendInputFile(ModuleMapFile->getName(), IK, +Module->IsSystem),
  1027. ModMap.getModuleMapFileForUniquing(Module)->getName(),
  1028. ModuleFileName);
  1029. } else {
  1030. // FIXME: We only need to fake up an input file here as a way of
  1031. // transporting the module's directory to the module map parser. We should
  1032. // be able to do that more directly, and parse from a memory buffer without
  1033. // inventing this file.
  1034. SmallString<128> FakeModuleMapFile(Module->Directory->getName());
  1035. llvm::sys::path::append(FakeModuleMapFile, "__inferred_module.map");
  1036. std::string InferredModuleMapContent;
  1037. llvm::raw_string_ostream OS(InferredModuleMapContent);
  1038. Module->print(OS);
  1039. OS.flush();
  1040. Result = compileModuleImpl(
  1041. ImportingInstance, ImportLoc, Module->getTopLevelModuleName(),
  1042. FrontendInputFile(FakeModuleMapFile, IK, +Module->IsSystem),
  1043. ModMap.getModuleMapFileForUniquing(Module)->getName(),
  1044. ModuleFileName,
  1045. [&](CompilerInstance &Instance) {
  1046. std::unique_ptr<llvm::MemoryBuffer> ModuleMapBuffer =
  1047. llvm::MemoryBuffer::getMemBuffer(InferredModuleMapContent);
  1048. ModuleMapFile = Instance.getFileManager().getVirtualFile(
  1049. FakeModuleMapFile, InferredModuleMapContent.size(), 0);
  1050. Instance.getSourceManager().overrideFileContents(
  1051. ModuleMapFile, std::move(ModuleMapBuffer));
  1052. });
  1053. }
  1054. // We've rebuilt a module. If we're allowed to generate or update the global
  1055. // module index, record that fact in the importing compiler instance.
  1056. if (ImportingInstance.getFrontendOpts().GenerateGlobalModuleIndex) {
  1057. ImportingInstance.setBuildGlobalModuleIndex(true);
  1058. }
  1059. return Result;
  1060. }
  1061. static bool compileAndLoadModule(CompilerInstance &ImportingInstance,
  1062. SourceLocation ImportLoc,
  1063. SourceLocation ModuleNameLoc, Module *Module,
  1064. StringRef ModuleFileName) {
  1065. DiagnosticsEngine &Diags = ImportingInstance.getDiagnostics();
  1066. auto diagnoseBuildFailure = [&] {
  1067. Diags.Report(ModuleNameLoc, diag::err_module_not_built)
  1068. << Module->Name << SourceRange(ImportLoc, ModuleNameLoc);
  1069. };
  1070. // FIXME: have LockFileManager return an error_code so that we can
  1071. // avoid the mkdir when the directory already exists.
  1072. StringRef Dir = llvm::sys::path::parent_path(ModuleFileName);
  1073. llvm::sys::fs::create_directories(Dir);
  1074. while (1) {
  1075. unsigned ModuleLoadCapabilities = ASTReader::ARR_Missing;
  1076. llvm::LockFileManager Locked(ModuleFileName);
  1077. switch (Locked) {
  1078. case llvm::LockFileManager::LFS_Error:
  1079. // ModuleCache takes care of correctness and locks are only necessary for
  1080. // performance. Fallback to building the module in case of any lock
  1081. // related errors.
  1082. Diags.Report(ModuleNameLoc, diag::remark_module_lock_failure)
  1083. << Module->Name << Locked.getErrorMessage();
  1084. // Clear out any potential leftover.
  1085. Locked.unsafeRemoveLockFile();
  1086. LLVM_FALLTHROUGH;
  1087. case llvm::LockFileManager::LFS_Owned:
  1088. // We're responsible for building the module ourselves.
  1089. if (!compileModuleImpl(ImportingInstance, ModuleNameLoc, Module,
  1090. ModuleFileName)) {
  1091. diagnoseBuildFailure();
  1092. return false;
  1093. }
  1094. break;
  1095. case llvm::LockFileManager::LFS_Shared:
  1096. // Someone else is responsible for building the module. Wait for them to
  1097. // finish.
  1098. switch (Locked.waitForUnlock()) {
  1099. case llvm::LockFileManager::Res_Success:
  1100. ModuleLoadCapabilities |= ASTReader::ARR_OutOfDate;
  1101. break;
  1102. case llvm::LockFileManager::Res_OwnerDied:
  1103. continue; // try again to get the lock.
  1104. case llvm::LockFileManager::Res_Timeout:
  1105. // Since ModuleCache takes care of correctness, we try waiting for
  1106. // another process to complete the build so clang does not do it done
  1107. // twice. If case of timeout, build it ourselves.
  1108. Diags.Report(ModuleNameLoc, diag::remark_module_lock_timeout)
  1109. << Module->Name;
  1110. // Clear the lock file so that future invocations can make progress.
  1111. Locked.unsafeRemoveLockFile();
  1112. continue;
  1113. }
  1114. break;
  1115. }
  1116. // Try to read the module file, now that we've compiled it.
  1117. ASTReader::ASTReadResult ReadResult =
  1118. ImportingInstance.getModuleManager()->ReadAST(
  1119. ModuleFileName, serialization::MK_ImplicitModule, ImportLoc,
  1120. ModuleLoadCapabilities);
  1121. if (ReadResult == ASTReader::OutOfDate &&
  1122. Locked == llvm::LockFileManager::LFS_Shared) {
  1123. // The module may be out of date in the presence of file system races,
  1124. // or if one of its imports depends on header search paths that are not
  1125. // consistent with this ImportingInstance. Try again...
  1126. continue;
  1127. } else if (ReadResult == ASTReader::Missing) {
  1128. diagnoseBuildFailure();
  1129. } else if (ReadResult != ASTReader::Success &&
  1130. !Diags.hasErrorOccurred()) {
  1131. // The ASTReader didn't diagnose the error, so conservatively report it.
  1132. diagnoseBuildFailure();
  1133. }
  1134. return ReadResult == ASTReader::Success;
  1135. }
  1136. }
  1137. /// Diagnose differences between the current definition of the given
  1138. /// configuration macro and the definition provided on the command line.
  1139. static void checkConfigMacro(Preprocessor &PP, StringRef ConfigMacro,
  1140. Module *Mod, SourceLocation ImportLoc) {
  1141. IdentifierInfo *Id = PP.getIdentifierInfo(ConfigMacro);
  1142. SourceManager &SourceMgr = PP.getSourceManager();
  1143. // If this identifier has never had a macro definition, then it could
  1144. // not have changed.
  1145. if (!Id->hadMacroDefinition())
  1146. return;
  1147. auto *LatestLocalMD = PP.getLocalMacroDirectiveHistory(Id);
  1148. // Find the macro definition from the command line.
  1149. MacroInfo *CmdLineDefinition = nullptr;
  1150. for (auto *MD = LatestLocalMD; MD; MD = MD->getPrevious()) {
  1151. // We only care about the predefines buffer.
  1152. FileID FID = SourceMgr.getFileID(MD->getLocation());
  1153. if (FID.isInvalid() || FID != PP.getPredefinesFileID())
  1154. continue;
  1155. if (auto *DMD = dyn_cast<DefMacroDirective>(MD))
  1156. CmdLineDefinition = DMD->getMacroInfo();
  1157. break;
  1158. }
  1159. auto *CurrentDefinition = PP.getMacroInfo(Id);
  1160. if (CurrentDefinition == CmdLineDefinition) {
  1161. // Macro matches. Nothing to do.
  1162. } else if (!CurrentDefinition) {
  1163. // This macro was defined on the command line, then #undef'd later.
  1164. // Complain.
  1165. PP.Diag(ImportLoc, diag::warn_module_config_macro_undef)
  1166. << true << ConfigMacro << Mod->getFullModuleName();
  1167. auto LatestDef = LatestLocalMD->getDefinition();
  1168. assert(LatestDef.isUndefined() &&
  1169. "predefined macro went away with no #undef?");
  1170. PP.Diag(LatestDef.getUndefLocation(), diag::note_module_def_undef_here)
  1171. << true;
  1172. return;
  1173. } else if (!CmdLineDefinition) {
  1174. // There was no definition for this macro in the predefines buffer,
  1175. // but there was a local definition. Complain.
  1176. PP.Diag(ImportLoc, diag::warn_module_config_macro_undef)
  1177. << false << ConfigMacro << Mod->getFullModuleName();
  1178. PP.Diag(CurrentDefinition->getDefinitionLoc(),
  1179. diag::note_module_def_undef_here)
  1180. << false;
  1181. } else if (!CurrentDefinition->isIdenticalTo(*CmdLineDefinition, PP,
  1182. /*Syntactically=*/true)) {
  1183. // The macro definitions differ.
  1184. PP.Diag(ImportLoc, diag::warn_module_config_macro_undef)
  1185. << false << ConfigMacro << Mod->getFullModuleName();
  1186. PP.Diag(CurrentDefinition->getDefinitionLoc(),
  1187. diag::note_module_def_undef_here)
  1188. << false;
  1189. }
  1190. }
  1191. /// Write a new timestamp file with the given path.
  1192. static void writeTimestampFile(StringRef TimestampFile) {
  1193. std::error_code EC;
  1194. llvm::raw_fd_ostream Out(TimestampFile.str(), EC, llvm::sys::fs::OF_None);
  1195. }
  1196. /// Prune the module cache of modules that haven't been accessed in
  1197. /// a long time.
  1198. static void pruneModuleCache(const HeaderSearchOptions &HSOpts) {
  1199. struct stat StatBuf;
  1200. llvm::SmallString<128> TimestampFile;
  1201. TimestampFile = HSOpts.ModuleCachePath;
  1202. assert(!TimestampFile.empty());
  1203. llvm::sys::path::append(TimestampFile, "modules.timestamp");
  1204. // Try to stat() the timestamp file.
  1205. if (::stat(TimestampFile.c_str(), &StatBuf)) {
  1206. // If the timestamp file wasn't there, create one now.
  1207. if (errno == ENOENT) {
  1208. writeTimestampFile(TimestampFile);
  1209. }
  1210. return;
  1211. }
  1212. // Check whether the time stamp is older than our pruning interval.
  1213. // If not, do nothing.
  1214. time_t TimeStampModTime = StatBuf.st_mtime;
  1215. time_t CurrentTime = time(nullptr);
  1216. if (CurrentTime - TimeStampModTime <= time_t(HSOpts.ModuleCachePruneInterval))
  1217. return;
  1218. // Write a new timestamp file so that nobody else attempts to prune.
  1219. // There is a benign race condition here, if two Clang instances happen to
  1220. // notice at the same time that the timestamp is out-of-date.
  1221. writeTimestampFile(TimestampFile);
  1222. // Walk the entire module cache, looking for unused module files and module
  1223. // indices.
  1224. std::error_code EC;
  1225. SmallString<128> ModuleCachePathNative;
  1226. llvm::sys::path::native(HSOpts.ModuleCachePath, ModuleCachePathNative);
  1227. for (llvm::sys::fs::directory_iterator Dir(ModuleCachePathNative, EC), DirEnd;
  1228. Dir != DirEnd && !EC; Dir.increment(EC)) {
  1229. // If we don't have a directory, there's nothing to look into.
  1230. if (!llvm::sys::fs::is_directory(Dir->path()))
  1231. continue;
  1232. // Walk all of the files within this directory.
  1233. for (llvm::sys::fs::directory_iterator File(Dir->path(), EC), FileEnd;
  1234. File != FileEnd && !EC; File.increment(EC)) {
  1235. // We only care about module and global module index files.
  1236. StringRef Extension = llvm::sys::path::extension(File->path());
  1237. if (Extension != ".pcm" && Extension != ".timestamp" &&
  1238. llvm::sys::path::filename(File->path()) != "modules.idx")
  1239. continue;
  1240. // Look at this file. If we can't stat it, there's nothing interesting
  1241. // there.
  1242. if (::stat(File->path().c_str(), &StatBuf))
  1243. continue;
  1244. // If the file has been used recently enough, leave it there.
  1245. time_t FileAccessTime = StatBuf.st_atime;
  1246. if (CurrentTime - FileAccessTime <=
  1247. time_t(HSOpts.ModuleCachePruneAfter)) {
  1248. continue;
  1249. }
  1250. // Remove the file.
  1251. llvm::sys::fs::remove(File->path());
  1252. // Remove the timestamp file.
  1253. std::string TimpestampFilename = File->path() + ".timestamp";
  1254. llvm::sys::fs::remove(TimpestampFilename);
  1255. }
  1256. // If we removed all of the files in the directory, remove the directory
  1257. // itself.
  1258. if (llvm::sys::fs::directory_iterator(Dir->path(), EC) ==
  1259. llvm::sys::fs::directory_iterator() && !EC)
  1260. llvm::sys::fs::remove(Dir->path());
  1261. }
  1262. }
  1263. void CompilerInstance::createModuleManager() {
  1264. if (!ModuleManager) {
  1265. if (!hasASTContext())
  1266. createASTContext();
  1267. // If we're implicitly building modules but not currently recursively
  1268. // building a module, check whether we need to prune the module cache.
  1269. if (getSourceManager().getModuleBuildStack().empty() &&
  1270. !getPreprocessor().getHeaderSearchInfo().getModuleCachePath().empty() &&
  1271. getHeaderSearchOpts().ModuleCachePruneInterval > 0 &&
  1272. getHeaderSearchOpts().ModuleCachePruneAfter > 0) {
  1273. pruneModuleCache(getHeaderSearchOpts());
  1274. }
  1275. HeaderSearchOptions &HSOpts = getHeaderSearchOpts();
  1276. std::string Sysroot = HSOpts.Sysroot;
  1277. const PreprocessorOptions &PPOpts = getPreprocessorOpts();
  1278. std::unique_ptr<llvm::Timer> ReadTimer;
  1279. if (FrontendTimerGroup)
  1280. ReadTimer = std::make_unique<llvm::Timer>("reading_modules",
  1281. "Reading modules",
  1282. *FrontendTimerGroup);
  1283. ModuleManager = new ASTReader(
  1284. getPreprocessor(), getModuleCache(), &getASTContext(),
  1285. getPCHContainerReader(), getFrontendOpts().ModuleFileExtensions,
  1286. Sysroot.empty() ? "" : Sysroot.c_str(), PPOpts.DisablePCHValidation,
  1287. /*AllowASTWithCompilerErrors=*/false,
  1288. /*AllowConfigurationMismatch=*/false,
  1289. HSOpts.ModulesValidateSystemHeaders,
  1290. getFrontendOpts().UseGlobalModuleIndex, std::move(ReadTimer));
  1291. if (hasASTConsumer()) {
  1292. ModuleManager->setDeserializationListener(
  1293. getASTConsumer().GetASTDeserializationListener());
  1294. getASTContext().setASTMutationListener(
  1295. getASTConsumer().GetASTMutationListener());
  1296. }
  1297. getASTContext().setExternalSource(ModuleManager);
  1298. if (hasSema())
  1299. ModuleManager->InitializeSema(getSema());
  1300. if (hasASTConsumer())
  1301. ModuleManager->StartTranslationUnit(&getASTConsumer());
  1302. for (auto &Listener : DependencyCollectors)
  1303. Listener->attachToASTReader(*ModuleManager);
  1304. }
  1305. }
  1306. bool CompilerInstance::loadModuleFile(StringRef FileName) {
  1307. llvm::Timer Timer;
  1308. if (FrontendTimerGroup)
  1309. Timer.init("preloading." + FileName.str(), "Preloading " + FileName.str(),
  1310. *FrontendTimerGroup);
  1311. llvm::TimeRegion TimeLoading(FrontendTimerGroup ? &Timer : nullptr);
  1312. // Helper to recursively read the module names for all modules we're adding.
  1313. // We mark these as known and redirect any attempt to load that module to
  1314. // the files we were handed.
  1315. struct ReadModuleNames : ASTReaderListener {
  1316. CompilerInstance &CI;
  1317. llvm::SmallVector<IdentifierInfo*, 8> LoadedModules;
  1318. ReadModuleNames(CompilerInstance &CI) : CI(CI) {}
  1319. void ReadModuleName(StringRef ModuleName) override {
  1320. LoadedModules.push_back(
  1321. CI.getPreprocessor().getIdentifierInfo(ModuleName));
  1322. }
  1323. void registerAll() {
  1324. for (auto *II : LoadedModules) {
  1325. CI.KnownModules[II] = CI.getPreprocessor()
  1326. .getHeaderSearchInfo()
  1327. .getModuleMap()
  1328. .findModule(II->getName());
  1329. }
  1330. LoadedModules.clear();
  1331. }
  1332. void markAllUnavailable() {
  1333. for (auto *II : LoadedModules) {
  1334. if (Module *M = CI.getPreprocessor()
  1335. .getHeaderSearchInfo()
  1336. .getModuleMap()
  1337. .findModule(II->getName())) {
  1338. M->HasIncompatibleModuleFile = true;
  1339. // Mark module as available if the only reason it was unavailable
  1340. // was missing headers.
  1341. SmallVector<Module *, 2> Stack;
  1342. Stack.push_back(M);
  1343. while (!Stack.empty()) {
  1344. Module *Current = Stack.pop_back_val();
  1345. if (Current->IsMissingRequirement) continue;
  1346. Current->IsAvailable = true;
  1347. Stack.insert(Stack.end(),
  1348. Current->submodule_begin(), Current->submodule_end());
  1349. }
  1350. }
  1351. }
  1352. LoadedModules.clear();
  1353. }
  1354. };
  1355. // If we don't already have an ASTReader, create one now.
  1356. if (!ModuleManager)
  1357. createModuleManager();
  1358. // If -Wmodule-file-config-mismatch is mapped as an error or worse, allow the
  1359. // ASTReader to diagnose it, since it can produce better errors that we can.
  1360. bool ConfigMismatchIsRecoverable =
  1361. getDiagnostics().getDiagnosticLevel(diag::warn_module_config_mismatch,
  1362. SourceLocation())
  1363. <= DiagnosticsEngine::Warning;
  1364. auto Listener = std::make_unique<ReadModuleNames>(*this);
  1365. auto &ListenerRef = *Listener;
  1366. ASTReader::ListenerScope ReadModuleNamesListener(*ModuleManager,
  1367. std::move(Listener));
  1368. // Try to load the module file.
  1369. switch (ModuleManager->ReadAST(
  1370. FileName, serialization::MK_ExplicitModule, SourceLocation(),
  1371. ConfigMismatchIsRecoverable ? ASTReader::ARR_ConfigurationMismatch : 0)) {
  1372. case ASTReader::Success:
  1373. // We successfully loaded the module file; remember the set of provided
  1374. // modules so that we don't try to load implicit modules for them.
  1375. ListenerRef.registerAll();
  1376. return true;
  1377. case ASTReader::ConfigurationMismatch:
  1378. // Ignore unusable module files.
  1379. getDiagnostics().Report(SourceLocation(), diag::warn_module_config_mismatch)
  1380. << FileName;
  1381. // All modules provided by any files we tried and failed to load are now
  1382. // unavailable; includes of those modules should now be handled textually.
  1383. ListenerRef.markAllUnavailable();
  1384. return true;
  1385. default:
  1386. return false;
  1387. }
  1388. }
  1389. ModuleLoadResult
  1390. CompilerInstance::loadModule(SourceLocation ImportLoc,
  1391. ModuleIdPath Path,
  1392. Module::NameVisibilityKind Visibility,
  1393. bool IsInclusionDirective) {
  1394. // Determine what file we're searching from.
  1395. StringRef ModuleName = Path[0].first->getName();
  1396. SourceLocation ModuleNameLoc = Path[0].second;
  1397. // If we've already handled this import, just return the cached result.
  1398. // This one-element cache is important to eliminate redundant diagnostics
  1399. // when both the preprocessor and parser see the same import declaration.
  1400. if (ImportLoc.isValid() && LastModuleImportLoc == ImportLoc) {
  1401. // Make the named module visible.
  1402. if (LastModuleImportResult && ModuleName != getLangOpts().CurrentModule)
  1403. ModuleManager->makeModuleVisible(LastModuleImportResult, Visibility,
  1404. ImportLoc);
  1405. return LastModuleImportResult;
  1406. }
  1407. clang::Module *Module = nullptr;
  1408. // If we don't already have information on this module, load the module now.
  1409. llvm::DenseMap<const IdentifierInfo *, clang::Module *>::iterator Known
  1410. = KnownModules.find(Path[0].first);
  1411. if (Known != KnownModules.end()) {
  1412. // Retrieve the cached top-level module.
  1413. Module = Known->second;
  1414. } else if (ModuleName == getLangOpts().CurrentModule) {
  1415. // This is the module we're building.
  1416. Module = PP->getHeaderSearchInfo().lookupModule(
  1417. ModuleName, /*AllowSearch*/ true,
  1418. /*AllowExtraModuleMapSearch*/ !IsInclusionDirective);
  1419. /// FIXME: perhaps we should (a) look for a module using the module name
  1420. // to file map (PrebuiltModuleFiles) and (b) diagnose if still not found?
  1421. //if (Module == nullptr) {
  1422. // getDiagnostics().Report(ModuleNameLoc, diag::err_module_not_found)
  1423. // << ModuleName;
  1424. // ModuleBuildFailed = true;
  1425. // return ModuleLoadResult();
  1426. //}
  1427. Known = KnownModules.insert(std::make_pair(Path[0].first, Module)).first;
  1428. } else {
  1429. // Search for a module with the given name.
  1430. Module = PP->getHeaderSearchInfo().lookupModule(ModuleName, true,
  1431. !IsInclusionDirective);
  1432. HeaderSearchOptions &HSOpts =
  1433. PP->getHeaderSearchInfo().getHeaderSearchOpts();
  1434. std::string ModuleFileName;
  1435. enum ModuleSource {
  1436. ModuleNotFound, ModuleCache, PrebuiltModulePath, ModuleBuildPragma
  1437. } Source = ModuleNotFound;
  1438. // Check to see if the module has been built as part of this compilation
  1439. // via a module build pragma.
  1440. auto BuiltModuleIt = BuiltModules.find(ModuleName);
  1441. if (BuiltModuleIt != BuiltModules.end()) {
  1442. ModuleFileName = BuiltModuleIt->second;
  1443. Source = ModuleBuildPragma;
  1444. }
  1445. // Try to load the module from the prebuilt module path.
  1446. if (Source == ModuleNotFound && (!HSOpts.PrebuiltModuleFiles.empty() ||
  1447. !HSOpts.PrebuiltModulePaths.empty())) {
  1448. ModuleFileName =
  1449. PP->getHeaderSearchInfo().getPrebuiltModuleFileName(ModuleName);
  1450. if (!ModuleFileName.empty())
  1451. Source = PrebuiltModulePath;
  1452. }
  1453. // Try to load the module from the module cache.
  1454. if (Source == ModuleNotFound && Module) {
  1455. ModuleFileName = PP->getHeaderSearchInfo().getCachedModuleFileName(Module);
  1456. Source = ModuleCache;
  1457. }
  1458. if (Source == ModuleNotFound) {
  1459. // We can't find a module, error out here.
  1460. getDiagnostics().Report(ModuleNameLoc, diag::err_module_not_found)
  1461. << ModuleName << SourceRange(ImportLoc, ModuleNameLoc);
  1462. ModuleBuildFailed = true;
  1463. return ModuleLoadResult();
  1464. }
  1465. if (ModuleFileName.empty()) {
  1466. if (Module && Module->HasIncompatibleModuleFile) {
  1467. // We tried and failed to load a module file for this module. Fall
  1468. // back to textual inclusion for its headers.
  1469. return ModuleLoadResult::ConfigMismatch;
  1470. }
  1471. getDiagnostics().Report(ModuleNameLoc, diag::err_module_build_disabled)
  1472. << ModuleName;
  1473. ModuleBuildFailed = true;
  1474. return ModuleLoadResult();
  1475. }
  1476. // If we don't already have an ASTReader, create one now.
  1477. if (!ModuleManager)
  1478. createModuleManager();
  1479. llvm::Timer Timer;
  1480. if (FrontendTimerGroup)
  1481. Timer.init("loading." + ModuleFileName, "Loading " + ModuleFileName,
  1482. *FrontendTimerGroup);
  1483. llvm::TimeRegion TimeLoading(FrontendTimerGroup ? &Timer : nullptr);
  1484. llvm::TimeTraceScope TimeScope("Module Load", ModuleName);
  1485. // Try to load the module file. If we are not trying to load from the
  1486. // module cache, we don't know how to rebuild modules.
  1487. unsigned ARRFlags = Source == ModuleCache ?
  1488. ASTReader::ARR_OutOfDate | ASTReader::ARR_Missing :
  1489. Source == PrebuiltModulePath ?
  1490. 0 :
  1491. ASTReader::ARR_ConfigurationMismatch;
  1492. switch (ModuleManager->ReadAST(ModuleFileName,
  1493. Source == PrebuiltModulePath
  1494. ? serialization::MK_PrebuiltModule
  1495. : Source == ModuleBuildPragma
  1496. ? serialization::MK_ExplicitModule
  1497. : serialization::MK_ImplicitModule,
  1498. ImportLoc, ARRFlags)) {
  1499. case ASTReader::Success: {
  1500. if (Source != ModuleCache && !Module) {
  1501. Module = PP->getHeaderSearchInfo().lookupModule(ModuleName, true,
  1502. !IsInclusionDirective);
  1503. auto ModuleFile = FileMgr->getFile(ModuleFileName);
  1504. if (!Module || !Module->getASTFile() ||
  1505. !ModuleFile || (*ModuleFile != Module->getASTFile())) {
  1506. // Error out if Module does not refer to the file in the prebuilt
  1507. // module path.
  1508. getDiagnostics().Report(ModuleNameLoc, diag::err_module_prebuilt)
  1509. << ModuleName;
  1510. ModuleBuildFailed = true;
  1511. KnownModules[Path[0].first] = nullptr;
  1512. return ModuleLoadResult();
  1513. }
  1514. }
  1515. break;
  1516. }
  1517. case ASTReader::OutOfDate:
  1518. case ASTReader::Missing: {
  1519. if (Source != ModuleCache) {
  1520. // We don't know the desired configuration for this module and don't
  1521. // necessarily even have a module map. Since ReadAST already produces
  1522. // diagnostics for these two cases, we simply error out here.
  1523. ModuleBuildFailed = true;
  1524. KnownModules[Path[0].first] = nullptr;
  1525. return ModuleLoadResult();
  1526. }
  1527. // The module file is missing or out-of-date. Build it.
  1528. assert(Module && "missing module file");
  1529. // Check whether there is a cycle in the module graph.
  1530. ModuleBuildStack ModPath = getSourceManager().getModuleBuildStack();
  1531. ModuleBuildStack::iterator Pos = ModPath.begin(), PosEnd = ModPath.end();
  1532. for (; Pos != PosEnd; ++Pos) {
  1533. if (Pos->first == ModuleName)
  1534. break;
  1535. }
  1536. if (Pos != PosEnd) {
  1537. SmallString<256> CyclePath;
  1538. for (; Pos != PosEnd; ++Pos) {
  1539. CyclePath += Pos->first;
  1540. CyclePath += " -> ";
  1541. }
  1542. CyclePath += ModuleName;
  1543. getDiagnostics().Report(ModuleNameLoc, diag::err_module_cycle)
  1544. << ModuleName << CyclePath;
  1545. return ModuleLoadResult();
  1546. }
  1547. // Check whether we have already attempted to build this module (but
  1548. // failed).
  1549. if (getPreprocessorOpts().FailedModules &&
  1550. getPreprocessorOpts().FailedModules->hasAlreadyFailed(ModuleName)) {
  1551. getDiagnostics().Report(ModuleNameLoc, diag::err_module_not_built)
  1552. << ModuleName
  1553. << SourceRange(ImportLoc, ModuleNameLoc);
  1554. ModuleBuildFailed = true;
  1555. return ModuleLoadResult();
  1556. }
  1557. // Try to compile and then load the module.
  1558. if (!compileAndLoadModule(*this, ImportLoc, ModuleNameLoc, Module,
  1559. ModuleFileName)) {
  1560. assert(getDiagnostics().hasErrorOccurred() &&
  1561. "undiagnosed error in compileAndLoadModule");
  1562. if (getPreprocessorOpts().FailedModules)
  1563. getPreprocessorOpts().FailedModules->addFailed(ModuleName);
  1564. KnownModules[Path[0].first] = nullptr;
  1565. ModuleBuildFailed = true;
  1566. return ModuleLoadResult();
  1567. }
  1568. // Okay, we've rebuilt and now loaded the module.
  1569. break;
  1570. }
  1571. case ASTReader::ConfigurationMismatch:
  1572. if (Source == PrebuiltModulePath)
  1573. // FIXME: We shouldn't be setting HadFatalFailure below if we only
  1574. // produce a warning here!
  1575. getDiagnostics().Report(SourceLocation(),
  1576. diag::warn_module_config_mismatch)
  1577. << ModuleFileName;
  1578. // Fall through to error out.
  1579. LLVM_FALLTHROUGH;
  1580. case ASTReader::VersionMismatch:
  1581. case ASTReader::HadErrors:
  1582. ModuleLoader::HadFatalFailure = true;
  1583. // FIXME: The ASTReader will already have complained, but can we shoehorn
  1584. // that diagnostic information into a more useful form?
  1585. KnownModules[Path[0].first] = nullptr;
  1586. return ModuleLoadResult();
  1587. case ASTReader::Failure:
  1588. ModuleLoader::HadFatalFailure = true;
  1589. // Already complained, but note now that we failed.
  1590. KnownModules[Path[0].first] = nullptr;
  1591. ModuleBuildFailed = true;
  1592. return ModuleLoadResult();
  1593. }
  1594. // Cache the result of this top-level module lookup for later.
  1595. Known = KnownModules.insert(std::make_pair(Path[0].first, Module)).first;
  1596. }
  1597. // If we never found the module, fail.
  1598. if (!Module)
  1599. return ModuleLoadResult();
  1600. // Verify that the rest of the module path actually corresponds to
  1601. // a submodule.
  1602. bool MapPrivateSubModToTopLevel = false;
  1603. if (Path.size() > 1) {
  1604. for (unsigned I = 1, N = Path.size(); I != N; ++I) {
  1605. StringRef Name = Path[I].first->getName();
  1606. clang::Module *Sub = Module->findSubmodule(Name);
  1607. // If the user is requesting Foo.Private and it doesn't exist, try to
  1608. // match Foo_Private and emit a warning asking for the user to write
  1609. // @import Foo_Private instead. FIXME: remove this when existing clients
  1610. // migrate off of Foo.Private syntax.
  1611. if (!Sub && PP->getLangOpts().ImplicitModules && Name == "Private" &&
  1612. Module == Module->getTopLevelModule()) {
  1613. SmallString<128> PrivateModule(Module->Name);
  1614. PrivateModule.append("_Private");
  1615. SmallVector<std::pair<IdentifierInfo *, SourceLocation>, 2> PrivPath;
  1616. auto &II = PP->getIdentifierTable().get(
  1617. PrivateModule, PP->getIdentifierInfo(Module->Name)->getTokenID());
  1618. PrivPath.push_back(std::make_pair(&II, Path[0].second));
  1619. if (PP->getHeaderSearchInfo().lookupModule(PrivateModule, true,
  1620. !IsInclusionDirective))
  1621. Sub =
  1622. loadModule(ImportLoc, PrivPath, Visibility, IsInclusionDirective);
  1623. if (Sub) {
  1624. MapPrivateSubModToTopLevel = true;
  1625. if (!getDiagnostics().isIgnored(
  1626. diag::warn_no_priv_submodule_use_toplevel, ImportLoc)) {
  1627. getDiagnostics().Report(Path[I].second,
  1628. diag::warn_no_priv_submodule_use_toplevel)
  1629. << Path[I].first << Module->getFullModuleName() << PrivateModule
  1630. << SourceRange(Path[0].second, Path[I].second)
  1631. << FixItHint::CreateReplacement(SourceRange(Path[0].second),
  1632. PrivateModule);
  1633. getDiagnostics().Report(Sub->DefinitionLoc,
  1634. diag::note_private_top_level_defined);
  1635. }
  1636. }
  1637. }
  1638. if (!Sub) {
  1639. // Attempt to perform typo correction to find a module name that works.
  1640. SmallVector<StringRef, 2> Best;
  1641. unsigned BestEditDistance = (std::numeric_limits<unsigned>::max)();
  1642. for (clang::Module::submodule_iterator J = Module->submodule_begin(),
  1643. JEnd = Module->submodule_end();
  1644. J != JEnd; ++J) {
  1645. unsigned ED = Name.edit_distance((*J)->Name,
  1646. /*AllowReplacements=*/true,
  1647. BestEditDistance);
  1648. if (ED <= BestEditDistance) {
  1649. if (ED < BestEditDistance) {
  1650. Best.clear();
  1651. BestEditDistance = ED;
  1652. }
  1653. Best.push_back((*J)->Name);
  1654. }
  1655. }
  1656. // If there was a clear winner, user it.
  1657. if (Best.size() == 1) {
  1658. getDiagnostics().Report(Path[I].second,
  1659. diag::err_no_submodule_suggest)
  1660. << Path[I].first << Module->getFullModuleName() << Best[0]
  1661. << SourceRange(Path[0].second, Path[I-1].second)
  1662. << FixItHint::CreateReplacement(SourceRange(Path[I].second),
  1663. Best[0]);
  1664. Sub = Module->findSubmodule(Best[0]);
  1665. }
  1666. }
  1667. if (!Sub) {
  1668. // No submodule by this name. Complain, and don't look for further
  1669. // submodules.
  1670. getDiagnostics().Report(Path[I].second, diag::err_no_submodule)
  1671. << Path[I].first << Module->getFullModuleName()
  1672. << SourceRange(Path[0].second, Path[I-1].second);
  1673. break;
  1674. }
  1675. Module = Sub;
  1676. }
  1677. }
  1678. // Make the named module visible, if it's not already part of the module
  1679. // we are parsing.
  1680. if (ModuleName != getLangOpts().CurrentModule) {
  1681. if (!Module->IsFromModuleFile && !MapPrivateSubModToTopLevel) {
  1682. // We have an umbrella header or directory that doesn't actually include
  1683. // all of the headers within the directory it covers. Complain about
  1684. // this missing submodule and recover by forgetting that we ever saw
  1685. // this submodule.
  1686. // FIXME: Should we detect this at module load time? It seems fairly
  1687. // expensive (and rare).
  1688. getDiagnostics().Report(ImportLoc, diag::warn_missing_submodule)
  1689. << Module->getFullModuleName()
  1690. << SourceRange(Path.front().second, Path.back().second);
  1691. return ModuleLoadResult::MissingExpected;
  1692. }
  1693. // Check whether this module is available.
  1694. if (Preprocessor::checkModuleIsAvailable(getLangOpts(), getTarget(),
  1695. getDiagnostics(), Module)) {
  1696. getDiagnostics().Report(ImportLoc, diag::note_module_import_here)
  1697. << SourceRange(Path.front().second, Path.back().second);
  1698. LastModuleImportLoc = ImportLoc;
  1699. LastModuleImportResult = ModuleLoadResult();
  1700. return ModuleLoadResult();
  1701. }
  1702. ModuleManager->makeModuleVisible(Module, Visibility, ImportLoc);
  1703. }
  1704. // Check for any configuration macros that have changed.
  1705. clang::Module *TopModule = Module->getTopLevelModule();
  1706. for (unsigned I = 0, N = TopModule->ConfigMacros.size(); I != N; ++I) {
  1707. checkConfigMacro(getPreprocessor(), TopModule->ConfigMacros[I],
  1708. Module, ImportLoc);
  1709. }
  1710. // Resolve any remaining module using export_as for this one.
  1711. getPreprocessor()
  1712. .getHeaderSearchInfo()
  1713. .getModuleMap()
  1714. .resolveLinkAsDependencies(TopModule);
  1715. LastModuleImportLoc = ImportLoc;
  1716. LastModuleImportResult = ModuleLoadResult(Module);
  1717. return LastModuleImportResult;
  1718. }
  1719. void CompilerInstance::loadModuleFromSource(SourceLocation ImportLoc,
  1720. StringRef ModuleName,
  1721. StringRef Source) {
  1722. // Avoid creating filenames with special characters.
  1723. SmallString<128> CleanModuleName(ModuleName);
  1724. for (auto &C : CleanModuleName)
  1725. if (!isAlphanumeric(C))
  1726. C = '_';
  1727. // FIXME: Using a randomized filename here means that our intermediate .pcm
  1728. // output is nondeterministic (as .pcm files refer to each other by name).
  1729. // Can this affect the output in any way?
  1730. SmallString<128> ModuleFileName;
  1731. if (std::error_code EC = llvm::sys::fs::createTemporaryFile(
  1732. CleanModuleName, "pcm", ModuleFileName)) {
  1733. getDiagnostics().Report(ImportLoc, diag::err_fe_unable_to_open_output)
  1734. << ModuleFileName << EC.message();
  1735. return;
  1736. }
  1737. std::string ModuleMapFileName = (CleanModuleName + ".map").str();
  1738. FrontendInputFile Input(
  1739. ModuleMapFileName,
  1740. InputKind(getLanguageFromOptions(*Invocation->getLangOpts()),
  1741. InputKind::ModuleMap, /*Preprocessed*/true));
  1742. std::string NullTerminatedSource(Source.str());
  1743. auto PreBuildStep = [&](CompilerInstance &Other) {
  1744. // Create a virtual file containing our desired source.
  1745. // FIXME: We shouldn't need to do this.
  1746. const FileEntry *ModuleMapFile = Other.getFileManager().getVirtualFile(
  1747. ModuleMapFileName, NullTerminatedSource.size(), 0);
  1748. Other.getSourceManager().overrideFileContents(
  1749. ModuleMapFile,
  1750. llvm::MemoryBuffer::getMemBuffer(NullTerminatedSource.c_str()));
  1751. Other.BuiltModules = std::move(BuiltModules);
  1752. Other.DeleteBuiltModules = false;
  1753. };
  1754. auto PostBuildStep = [this](CompilerInstance &Other) {
  1755. BuiltModules = std::move(Other.BuiltModules);
  1756. };
  1757. // Build the module, inheriting any modules that we've built locally.
  1758. if (compileModuleImpl(*this, ImportLoc, ModuleName, Input, StringRef(),
  1759. ModuleFileName, PreBuildStep, PostBuildStep)) {
  1760. BuiltModules[ModuleName] = ModuleFileName.str();
  1761. llvm::sys::RemoveFileOnSignal(ModuleFileName);
  1762. }
  1763. }
  1764. void CompilerInstance::makeModuleVisible(Module *Mod,
  1765. Module::NameVisibilityKind Visibility,
  1766. SourceLocation ImportLoc) {
  1767. if (!ModuleManager)
  1768. createModuleManager();
  1769. if (!ModuleManager)
  1770. return;
  1771. ModuleManager->makeModuleVisible(Mod, Visibility, ImportLoc);
  1772. }
  1773. GlobalModuleIndex *CompilerInstance::loadGlobalModuleIndex(
  1774. SourceLocation TriggerLoc) {
  1775. if (getPreprocessor().getHeaderSearchInfo().getModuleCachePath().empty())
  1776. return nullptr;
  1777. if (!ModuleManager)
  1778. createModuleManager();
  1779. // Can't do anything if we don't have the module manager.
  1780. if (!ModuleManager)
  1781. return nullptr;
  1782. // Get an existing global index. This loads it if not already
  1783. // loaded.
  1784. ModuleManager->loadGlobalIndex();
  1785. GlobalModuleIndex *GlobalIndex = ModuleManager->getGlobalIndex();
  1786. // If the global index doesn't exist, create it.
  1787. if (!GlobalIndex && shouldBuildGlobalModuleIndex() && hasFileManager() &&
  1788. hasPreprocessor()) {
  1789. llvm::sys::fs::create_directories(
  1790. getPreprocessor().getHeaderSearchInfo().getModuleCachePath());
  1791. if (llvm::Error Err = GlobalModuleIndex::writeIndex(
  1792. getFileManager(), getPCHContainerReader(),
  1793. getPreprocessor().getHeaderSearchInfo().getModuleCachePath())) {
  1794. // FIXME this drops the error on the floor. This code is only used for
  1795. // typo correction and drops more than just this one source of errors
  1796. // (such as the directory creation failure above). It should handle the
  1797. // error.
  1798. consumeError(std::move(Err));
  1799. return nullptr;
  1800. }
  1801. ModuleManager->resetForReload();
  1802. ModuleManager->loadGlobalIndex();
  1803. GlobalIndex = ModuleManager->getGlobalIndex();
  1804. }
  1805. // For finding modules needing to be imported for fixit messages,
  1806. // we need to make the global index cover all modules, so we do that here.
  1807. if (!HaveFullGlobalModuleIndex && GlobalIndex && !buildingModule()) {
  1808. ModuleMap &MMap = getPreprocessor().getHeaderSearchInfo().getModuleMap();
  1809. bool RecreateIndex = false;
  1810. for (ModuleMap::module_iterator I = MMap.module_begin(),
  1811. E = MMap.module_end(); I != E; ++I) {
  1812. Module *TheModule = I->second;
  1813. const FileEntry *Entry = TheModule->getASTFile();
  1814. if (!Entry) {
  1815. SmallVector<std::pair<IdentifierInfo *, SourceLocation>, 2> Path;
  1816. Path.push_back(std::make_pair(
  1817. getPreprocessor().getIdentifierInfo(TheModule->Name), TriggerLoc));
  1818. std::reverse(Path.begin(), Path.end());
  1819. // Load a module as hidden. This also adds it to the global index.
  1820. loadModule(TheModule->DefinitionLoc, Path, Module::Hidden, false);
  1821. RecreateIndex = true;
  1822. }
  1823. }
  1824. if (RecreateIndex) {
  1825. if (llvm::Error Err = GlobalModuleIndex::writeIndex(
  1826. getFileManager(), getPCHContainerReader(),
  1827. getPreprocessor().getHeaderSearchInfo().getModuleCachePath())) {
  1828. // FIXME As above, this drops the error on the floor.
  1829. consumeError(std::move(Err));
  1830. return nullptr;
  1831. }
  1832. ModuleManager->resetForReload();
  1833. ModuleManager->loadGlobalIndex();
  1834. GlobalIndex = ModuleManager->getGlobalIndex();
  1835. }
  1836. HaveFullGlobalModuleIndex = true;
  1837. }
  1838. return GlobalIndex;
  1839. }
  1840. // Check global module index for missing imports.
  1841. bool
  1842. CompilerInstance::lookupMissingImports(StringRef Name,
  1843. SourceLocation TriggerLoc) {
  1844. // Look for the symbol in non-imported modules, but only if an error
  1845. // actually occurred.
  1846. if (!buildingModule()) {
  1847. // Load global module index, or retrieve a previously loaded one.
  1848. GlobalModuleIndex *GlobalIndex = loadGlobalModuleIndex(
  1849. TriggerLoc);
  1850. // Only if we have a global index.
  1851. if (GlobalIndex) {
  1852. GlobalModuleIndex::HitSet FoundModules;
  1853. // Find the modules that reference the identifier.
  1854. // Note that this only finds top-level modules.
  1855. // We'll let diagnoseTypo find the actual declaration module.
  1856. if (GlobalIndex->lookupIdentifier(Name, FoundModules))
  1857. return true;
  1858. }
  1859. }
  1860. return false;
  1861. }
  1862. void CompilerInstance::resetAndLeakSema() { llvm::BuryPointer(takeSema()); }
  1863. void CompilerInstance::setExternalSemaSource(
  1864. IntrusiveRefCntPtr<ExternalSemaSource> ESS) {
  1865. ExternalSemaSrc = std::move(ESS);
  1866. }