CompilerInstance.cpp 83 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146
  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, HSOpts.ValidateASTInputFilesContent,
  440. UseGlobalModuleIndex));
  441. // We need the external source to be set up before we read the AST, because
  442. // eagerly-deserialized declarations may use it.
  443. Context.setExternalSource(Reader.get());
  444. Reader->setDeserializationListener(
  445. static_cast<ASTDeserializationListener *>(DeserializationListener),
  446. /*TakeOwnership=*/OwnDeserializationListener);
  447. for (auto &Listener : DependencyCollectors)
  448. Listener->attachToASTReader(*Reader);
  449. switch (Reader->ReadAST(Path,
  450. Preamble ? serialization::MK_Preamble
  451. : serialization::MK_PCH,
  452. SourceLocation(),
  453. ASTReader::ARR_None)) {
  454. case ASTReader::Success:
  455. // Set the predefines buffer as suggested by the PCH reader. Typically, the
  456. // predefines buffer will be empty.
  457. PP.setPredefines(Reader->getSuggestedPredefines());
  458. return Reader;
  459. case ASTReader::Failure:
  460. // Unrecoverable failure: don't even try to process the input file.
  461. break;
  462. case ASTReader::Missing:
  463. case ASTReader::OutOfDate:
  464. case ASTReader::VersionMismatch:
  465. case ASTReader::ConfigurationMismatch:
  466. case ASTReader::HadErrors:
  467. // No suitable PCH file could be found. Return an error.
  468. break;
  469. }
  470. Context.setExternalSource(nullptr);
  471. return nullptr;
  472. }
  473. // Code Completion
  474. static bool EnableCodeCompletion(Preprocessor &PP,
  475. StringRef Filename,
  476. unsigned Line,
  477. unsigned Column) {
  478. // Tell the source manager to chop off the given file at a specific
  479. // line and column.
  480. auto Entry = PP.getFileManager().getFile(Filename);
  481. if (!Entry) {
  482. PP.getDiagnostics().Report(diag::err_fe_invalid_code_complete_file)
  483. << Filename;
  484. return true;
  485. }
  486. // Truncate the named file at the given line/column.
  487. PP.SetCodeCompletionPoint(*Entry, Line, Column);
  488. return false;
  489. }
  490. void CompilerInstance::createCodeCompletionConsumer() {
  491. const ParsedSourceLocation &Loc = getFrontendOpts().CodeCompletionAt;
  492. if (!CompletionConsumer) {
  493. setCodeCompletionConsumer(
  494. createCodeCompletionConsumer(getPreprocessor(),
  495. Loc.FileName, Loc.Line, Loc.Column,
  496. getFrontendOpts().CodeCompleteOpts,
  497. llvm::outs()));
  498. if (!CompletionConsumer)
  499. return;
  500. } else if (EnableCodeCompletion(getPreprocessor(), Loc.FileName,
  501. Loc.Line, Loc.Column)) {
  502. setCodeCompletionConsumer(nullptr);
  503. return;
  504. }
  505. }
  506. void CompilerInstance::createFrontendTimer() {
  507. FrontendTimerGroup.reset(
  508. new llvm::TimerGroup("frontend", "Clang front-end time report"));
  509. FrontendTimer.reset(
  510. new llvm::Timer("frontend", "Clang front-end timer",
  511. *FrontendTimerGroup));
  512. }
  513. CodeCompleteConsumer *
  514. CompilerInstance::createCodeCompletionConsumer(Preprocessor &PP,
  515. StringRef Filename,
  516. unsigned Line,
  517. unsigned Column,
  518. const CodeCompleteOptions &Opts,
  519. raw_ostream &OS) {
  520. if (EnableCodeCompletion(PP, Filename, Line, Column))
  521. return nullptr;
  522. // Set up the creation routine for code-completion.
  523. return new PrintingCodeCompleteConsumer(Opts, OS);
  524. }
  525. void CompilerInstance::createSema(TranslationUnitKind TUKind,
  526. CodeCompleteConsumer *CompletionConsumer) {
  527. TheSema.reset(new Sema(getPreprocessor(), getASTContext(), getASTConsumer(),
  528. TUKind, CompletionConsumer));
  529. // Attach the external sema source if there is any.
  530. if (ExternalSemaSrc) {
  531. TheSema->addExternalSource(ExternalSemaSrc.get());
  532. ExternalSemaSrc->InitializeSema(*TheSema);
  533. }
  534. }
  535. // Output Files
  536. void CompilerInstance::addOutputFile(OutputFile &&OutFile) {
  537. OutputFiles.push_back(std::move(OutFile));
  538. }
  539. void CompilerInstance::clearOutputFiles(bool EraseFiles) {
  540. for (OutputFile &OF : OutputFiles) {
  541. if (!OF.TempFilename.empty()) {
  542. if (EraseFiles) {
  543. llvm::sys::fs::remove(OF.TempFilename);
  544. } else {
  545. SmallString<128> NewOutFile(OF.Filename);
  546. // If '-working-directory' was passed, the output filename should be
  547. // relative to that.
  548. FileMgr->FixupRelativePath(NewOutFile);
  549. if (std::error_code ec =
  550. llvm::sys::fs::rename(OF.TempFilename, NewOutFile)) {
  551. getDiagnostics().Report(diag::err_unable_to_rename_temp)
  552. << OF.TempFilename << OF.Filename << ec.message();
  553. llvm::sys::fs::remove(OF.TempFilename);
  554. }
  555. }
  556. } else if (!OF.Filename.empty() && EraseFiles)
  557. llvm::sys::fs::remove(OF.Filename);
  558. }
  559. OutputFiles.clear();
  560. if (DeleteBuiltModules) {
  561. for (auto &Module : BuiltModules)
  562. llvm::sys::fs::remove(Module.second);
  563. BuiltModules.clear();
  564. }
  565. NonSeekStream.reset();
  566. }
  567. std::unique_ptr<raw_pwrite_stream>
  568. CompilerInstance::createDefaultOutputFile(bool Binary, StringRef InFile,
  569. StringRef Extension) {
  570. return createOutputFile(getFrontendOpts().OutputFile, Binary,
  571. /*RemoveFileOnSignal=*/true, InFile, Extension,
  572. /*UseTemporary=*/true);
  573. }
  574. std::unique_ptr<raw_pwrite_stream> CompilerInstance::createNullOutputFile() {
  575. return std::make_unique<llvm::raw_null_ostream>();
  576. }
  577. std::unique_ptr<raw_pwrite_stream>
  578. CompilerInstance::createOutputFile(StringRef OutputPath, bool Binary,
  579. bool RemoveFileOnSignal, StringRef InFile,
  580. StringRef Extension, bool UseTemporary,
  581. bool CreateMissingDirectories) {
  582. std::string OutputPathName, TempPathName;
  583. std::error_code EC;
  584. std::unique_ptr<raw_pwrite_stream> OS = createOutputFile(
  585. OutputPath, EC, Binary, RemoveFileOnSignal, InFile, Extension,
  586. UseTemporary, CreateMissingDirectories, &OutputPathName, &TempPathName);
  587. if (!OS) {
  588. getDiagnostics().Report(diag::err_fe_unable_to_open_output) << OutputPath
  589. << EC.message();
  590. return nullptr;
  591. }
  592. // Add the output file -- but don't try to remove "-", since this means we are
  593. // using stdin.
  594. addOutputFile(
  595. OutputFile((OutputPathName != "-") ? OutputPathName : "", TempPathName));
  596. return OS;
  597. }
  598. std::unique_ptr<llvm::raw_pwrite_stream> CompilerInstance::createOutputFile(
  599. StringRef OutputPath, std::error_code &Error, bool Binary,
  600. bool RemoveFileOnSignal, StringRef InFile, StringRef Extension,
  601. bool UseTemporary, bool CreateMissingDirectories,
  602. std::string *ResultPathName, std::string *TempPathName) {
  603. assert((!CreateMissingDirectories || UseTemporary) &&
  604. "CreateMissingDirectories is only allowed when using temporary files");
  605. std::string OutFile, TempFile;
  606. if (!OutputPath.empty()) {
  607. OutFile = OutputPath;
  608. } else if (InFile == "-") {
  609. OutFile = "-";
  610. } else if (!Extension.empty()) {
  611. SmallString<128> Path(InFile);
  612. llvm::sys::path::replace_extension(Path, Extension);
  613. OutFile = Path.str();
  614. } else {
  615. OutFile = "-";
  616. }
  617. std::unique_ptr<llvm::raw_fd_ostream> OS;
  618. std::string OSFile;
  619. if (UseTemporary) {
  620. if (OutFile == "-")
  621. UseTemporary = false;
  622. else {
  623. llvm::sys::fs::file_status Status;
  624. llvm::sys::fs::status(OutputPath, Status);
  625. if (llvm::sys::fs::exists(Status)) {
  626. // Fail early if we can't write to the final destination.
  627. if (!llvm::sys::fs::can_write(OutputPath)) {
  628. Error = make_error_code(llvm::errc::operation_not_permitted);
  629. return nullptr;
  630. }
  631. // Don't use a temporary if the output is a special file. This handles
  632. // things like '-o /dev/null'
  633. if (!llvm::sys::fs::is_regular_file(Status))
  634. UseTemporary = false;
  635. }
  636. }
  637. }
  638. if (UseTemporary) {
  639. // Create a temporary file.
  640. // Insert -%%%%%%%% before the extension (if any), and because some tools
  641. // (noticeable, clang's own GlobalModuleIndex.cpp) glob for build
  642. // artifacts, also append .tmp.
  643. StringRef OutputExtension = llvm::sys::path::extension(OutFile);
  644. SmallString<128> TempPath =
  645. StringRef(OutFile).drop_back(OutputExtension.size());
  646. TempPath += "-%%%%%%%%";
  647. TempPath += OutputExtension;
  648. TempPath += ".tmp";
  649. int fd;
  650. std::error_code EC =
  651. llvm::sys::fs::createUniqueFile(TempPath, fd, TempPath);
  652. if (CreateMissingDirectories &&
  653. EC == llvm::errc::no_such_file_or_directory) {
  654. StringRef Parent = llvm::sys::path::parent_path(OutputPath);
  655. EC = llvm::sys::fs::create_directories(Parent);
  656. if (!EC) {
  657. EC = llvm::sys::fs::createUniqueFile(TempPath, fd, TempPath);
  658. }
  659. }
  660. if (!EC) {
  661. OS.reset(new llvm::raw_fd_ostream(fd, /*shouldClose=*/true));
  662. OSFile = TempFile = TempPath.str();
  663. }
  664. // If we failed to create the temporary, fallback to writing to the file
  665. // directly. This handles the corner case where we cannot write to the
  666. // directory, but can write to the file.
  667. }
  668. if (!OS) {
  669. OSFile = OutFile;
  670. OS.reset(new llvm::raw_fd_ostream(
  671. OSFile, Error,
  672. (Binary ? llvm::sys::fs::OF_None : llvm::sys::fs::OF_Text)));
  673. if (Error)
  674. return nullptr;
  675. }
  676. // Make sure the out stream file gets removed if we crash.
  677. if (RemoveFileOnSignal)
  678. llvm::sys::RemoveFileOnSignal(OSFile);
  679. if (ResultPathName)
  680. *ResultPathName = OutFile;
  681. if (TempPathName)
  682. *TempPathName = TempFile;
  683. if (!Binary || OS->supportsSeeking())
  684. return std::move(OS);
  685. auto B = std::make_unique<llvm::buffer_ostream>(*OS);
  686. assert(!NonSeekStream);
  687. NonSeekStream = std::move(OS);
  688. return std::move(B);
  689. }
  690. // Initialization Utilities
  691. bool CompilerInstance::InitializeSourceManager(const FrontendInputFile &Input){
  692. return InitializeSourceManager(
  693. Input, getDiagnostics(), getFileManager(), getSourceManager(),
  694. hasPreprocessor() ? &getPreprocessor().getHeaderSearchInfo() : nullptr,
  695. getDependencyOutputOpts(), getFrontendOpts());
  696. }
  697. // static
  698. bool CompilerInstance::InitializeSourceManager(
  699. const FrontendInputFile &Input, DiagnosticsEngine &Diags,
  700. FileManager &FileMgr, SourceManager &SourceMgr, HeaderSearch *HS,
  701. DependencyOutputOptions &DepOpts, const FrontendOptions &Opts) {
  702. SrcMgr::CharacteristicKind Kind =
  703. Input.getKind().getFormat() == InputKind::ModuleMap
  704. ? Input.isSystem() ? SrcMgr::C_System_ModuleMap
  705. : SrcMgr::C_User_ModuleMap
  706. : Input.isSystem() ? SrcMgr::C_System : SrcMgr::C_User;
  707. if (Input.isBuffer()) {
  708. SourceMgr.setMainFileID(SourceMgr.createFileID(SourceManager::Unowned,
  709. Input.getBuffer(), Kind));
  710. assert(SourceMgr.getMainFileID().isValid() &&
  711. "Couldn't establish MainFileID!");
  712. return true;
  713. }
  714. StringRef InputFile = Input.getFile();
  715. // Figure out where to get and map in the main file.
  716. if (InputFile != "-") {
  717. auto FileOrErr = FileMgr.getFileRef(InputFile, /*OpenFile=*/true);
  718. if (!FileOrErr) {
  719. // FIXME: include the error in the diagnostic.
  720. consumeError(FileOrErr.takeError());
  721. Diags.Report(diag::err_fe_error_reading) << InputFile;
  722. return false;
  723. }
  724. FileEntryRef File = *FileOrErr;
  725. // The natural SourceManager infrastructure can't currently handle named
  726. // pipes, but we would at least like to accept them for the main
  727. // file. Detect them here, read them with the volatile flag so FileMgr will
  728. // pick up the correct size, and simply override their contents as we do for
  729. // STDIN.
  730. if (File.getFileEntry().isNamedPipe()) {
  731. auto MB =
  732. FileMgr.getBufferForFile(&File.getFileEntry(), /*isVolatile=*/true);
  733. if (MB) {
  734. // Create a new virtual file that will have the correct size.
  735. const FileEntry *FE =
  736. FileMgr.getVirtualFile(InputFile, (*MB)->getBufferSize(), 0);
  737. SourceMgr.overrideFileContents(FE, std::move(*MB));
  738. SourceMgr.setMainFileID(
  739. SourceMgr.createFileID(FE, SourceLocation(), Kind));
  740. } else {
  741. Diags.Report(diag::err_cannot_open_file) << InputFile
  742. << MB.getError().message();
  743. return false;
  744. }
  745. } else {
  746. SourceMgr.setMainFileID(
  747. SourceMgr.createFileID(File, SourceLocation(), Kind));
  748. }
  749. } else {
  750. llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> SBOrErr =
  751. llvm::MemoryBuffer::getSTDIN();
  752. if (std::error_code EC = SBOrErr.getError()) {
  753. Diags.Report(diag::err_fe_error_reading_stdin) << EC.message();
  754. return false;
  755. }
  756. std::unique_ptr<llvm::MemoryBuffer> SB = std::move(SBOrErr.get());
  757. const FileEntry *File = FileMgr.getVirtualFile(SB->getBufferIdentifier(),
  758. SB->getBufferSize(), 0);
  759. SourceMgr.setMainFileID(
  760. SourceMgr.createFileID(File, SourceLocation(), Kind));
  761. SourceMgr.overrideFileContents(File, std::move(SB));
  762. }
  763. assert(SourceMgr.getMainFileID().isValid() &&
  764. "Couldn't establish MainFileID!");
  765. return true;
  766. }
  767. // High-Level Operations
  768. bool CompilerInstance::ExecuteAction(FrontendAction &Act) {
  769. assert(hasDiagnostics() && "Diagnostics engine is not initialized!");
  770. assert(!getFrontendOpts().ShowHelp && "Client must handle '-help'!");
  771. assert(!getFrontendOpts().ShowVersion && "Client must handle '-version'!");
  772. // Mark this point as the bottom of the stack if we don't have somewhere
  773. // better. We generally expect frontend actions to be invoked with (nearly)
  774. // DesiredStackSpace available.
  775. noteBottomOfStack();
  776. // FIXME: Take this as an argument, once all the APIs we used have moved to
  777. // taking it as an input instead of hard-coding llvm::errs.
  778. raw_ostream &OS = llvm::errs();
  779. if (!Act.PrepareToExecute(*this))
  780. return false;
  781. // Create the target instance.
  782. setTarget(TargetInfo::CreateTargetInfo(getDiagnostics(),
  783. getInvocation().TargetOpts));
  784. if (!hasTarget())
  785. return false;
  786. // Create TargetInfo for the other side of CUDA and OpenMP compilation.
  787. if ((getLangOpts().CUDA || getLangOpts().OpenMPIsDevice) &&
  788. !getFrontendOpts().AuxTriple.empty()) {
  789. auto TO = std::make_shared<TargetOptions>();
  790. TO->Triple = llvm::Triple::normalize(getFrontendOpts().AuxTriple);
  791. TO->HostTriple = getTarget().getTriple().str();
  792. setAuxTarget(TargetInfo::CreateTargetInfo(getDiagnostics(), TO));
  793. }
  794. // Inform the target of the language options.
  795. //
  796. // FIXME: We shouldn't need to do this, the target should be immutable once
  797. // created. This complexity should be lifted elsewhere.
  798. getTarget().adjust(getLangOpts());
  799. // Adjust target options based on codegen options.
  800. getTarget().adjustTargetOptions(getCodeGenOpts(), getTargetOpts());
  801. if (auto *Aux = getAuxTarget())
  802. getTarget().setAuxTarget(Aux);
  803. // rewriter project will change target built-in bool type from its default.
  804. if (getFrontendOpts().ProgramAction == frontend::RewriteObjC)
  805. getTarget().noSignedCharForObjCBool();
  806. // Validate/process some options.
  807. if (getHeaderSearchOpts().Verbose)
  808. OS << "clang -cc1 version " CLANG_VERSION_STRING
  809. << " based upon " << BACKEND_PACKAGE_STRING
  810. << " default target " << llvm::sys::getDefaultTargetTriple() << "\n";
  811. if (getFrontendOpts().ShowTimers)
  812. createFrontendTimer();
  813. if (getFrontendOpts().ShowStats || !getFrontendOpts().StatsFile.empty())
  814. llvm::EnableStatistics(false);
  815. for (const FrontendInputFile &FIF : getFrontendOpts().Inputs) {
  816. // Reset the ID tables if we are reusing the SourceManager and parsing
  817. // regular files.
  818. if (hasSourceManager() && !Act.isModelParsingAction())
  819. getSourceManager().clearIDTables();
  820. if (Act.BeginSourceFile(*this, FIF)) {
  821. if (llvm::Error Err = Act.Execute()) {
  822. consumeError(std::move(Err)); // FIXME this drops errors on the floor.
  823. }
  824. Act.EndSourceFile();
  825. }
  826. }
  827. // Notify the diagnostic client that all files were processed.
  828. getDiagnostics().getClient()->finish();
  829. if (getDiagnosticOpts().ShowCarets) {
  830. // We can have multiple diagnostics sharing one diagnostic client.
  831. // Get the total number of warnings/errors from the client.
  832. unsigned NumWarnings = getDiagnostics().getClient()->getNumWarnings();
  833. unsigned NumErrors = getDiagnostics().getClient()->getNumErrors();
  834. if (NumWarnings)
  835. OS << NumWarnings << " warning" << (NumWarnings == 1 ? "" : "s");
  836. if (NumWarnings && NumErrors)
  837. OS << " and ";
  838. if (NumErrors)
  839. OS << NumErrors << " error" << (NumErrors == 1 ? "" : "s");
  840. if (NumWarnings || NumErrors) {
  841. OS << " generated";
  842. if (getLangOpts().CUDA) {
  843. if (!getLangOpts().CUDAIsDevice) {
  844. OS << " when compiling for host";
  845. } else {
  846. OS << " when compiling for " << getTargetOpts().CPU;
  847. }
  848. }
  849. OS << ".\n";
  850. }
  851. }
  852. if (getFrontendOpts().ShowStats) {
  853. if (hasFileManager()) {
  854. getFileManager().PrintStats();
  855. OS << '\n';
  856. }
  857. llvm::PrintStatistics(OS);
  858. }
  859. StringRef StatsFile = getFrontendOpts().StatsFile;
  860. if (!StatsFile.empty()) {
  861. std::error_code EC;
  862. auto StatS = std::make_unique<llvm::raw_fd_ostream>(
  863. StatsFile, EC, llvm::sys::fs::OF_Text);
  864. if (EC) {
  865. getDiagnostics().Report(diag::warn_fe_unable_to_open_stats_file)
  866. << StatsFile << EC.message();
  867. } else {
  868. llvm::PrintStatisticsJSON(*StatS);
  869. }
  870. }
  871. return !getDiagnostics().getClient()->getNumErrors();
  872. }
  873. /// Determine the appropriate source input kind based on language
  874. /// options.
  875. static Language getLanguageFromOptions(const LangOptions &LangOpts) {
  876. if (LangOpts.OpenCL)
  877. return Language::OpenCL;
  878. if (LangOpts.CUDA)
  879. return Language::CUDA;
  880. if (LangOpts.ObjC)
  881. return LangOpts.CPlusPlus ? Language::ObjCXX : Language::ObjC;
  882. return LangOpts.CPlusPlus ? Language::CXX : Language::C;
  883. }
  884. /// Compile a module file for the given module, using the options
  885. /// provided by the importing compiler instance. Returns true if the module
  886. /// was built without errors.
  887. static bool
  888. compileModuleImpl(CompilerInstance &ImportingInstance, SourceLocation ImportLoc,
  889. StringRef ModuleName, FrontendInputFile Input,
  890. StringRef OriginalModuleMapFile, StringRef ModuleFileName,
  891. llvm::function_ref<void(CompilerInstance &)> PreBuildStep =
  892. [](CompilerInstance &) {},
  893. llvm::function_ref<void(CompilerInstance &)> PostBuildStep =
  894. [](CompilerInstance &) {}) {
  895. llvm::TimeTraceScope TimeScope("Module Compile", ModuleName);
  896. // Construct a compiler invocation for creating this module.
  897. auto Invocation =
  898. std::make_shared<CompilerInvocation>(ImportingInstance.getInvocation());
  899. PreprocessorOptions &PPOpts = Invocation->getPreprocessorOpts();
  900. // For any options that aren't intended to affect how a module is built,
  901. // reset them to their default values.
  902. Invocation->getLangOpts()->resetNonModularOptions();
  903. PPOpts.resetNonModularOptions();
  904. // Remove any macro definitions that are explicitly ignored by the module.
  905. // They aren't supposed to affect how the module is built anyway.
  906. HeaderSearchOptions &HSOpts = Invocation->getHeaderSearchOpts();
  907. PPOpts.Macros.erase(
  908. std::remove_if(PPOpts.Macros.begin(), PPOpts.Macros.end(),
  909. [&HSOpts](const std::pair<std::string, bool> &def) {
  910. StringRef MacroDef = def.first;
  911. return HSOpts.ModulesIgnoreMacros.count(
  912. llvm::CachedHashString(MacroDef.split('=').first)) > 0;
  913. }),
  914. PPOpts.Macros.end());
  915. // If the original compiler invocation had -fmodule-name, pass it through.
  916. Invocation->getLangOpts()->ModuleName =
  917. ImportingInstance.getInvocation().getLangOpts()->ModuleName;
  918. // Note the name of the module we're building.
  919. Invocation->getLangOpts()->CurrentModule = ModuleName;
  920. // Make sure that the failed-module structure has been allocated in
  921. // the importing instance, and propagate the pointer to the newly-created
  922. // instance.
  923. PreprocessorOptions &ImportingPPOpts
  924. = ImportingInstance.getInvocation().getPreprocessorOpts();
  925. if (!ImportingPPOpts.FailedModules)
  926. ImportingPPOpts.FailedModules =
  927. std::make_shared<PreprocessorOptions::FailedModulesSet>();
  928. PPOpts.FailedModules = ImportingPPOpts.FailedModules;
  929. // If there is a module map file, build the module using the module map.
  930. // Set up the inputs/outputs so that we build the module from its umbrella
  931. // header.
  932. FrontendOptions &FrontendOpts = Invocation->getFrontendOpts();
  933. FrontendOpts.OutputFile = ModuleFileName.str();
  934. FrontendOpts.DisableFree = false;
  935. FrontendOpts.GenerateGlobalModuleIndex = false;
  936. FrontendOpts.BuildingImplicitModule = true;
  937. FrontendOpts.OriginalModuleMap = OriginalModuleMapFile;
  938. // Force implicitly-built modules to hash the content of the module file.
  939. HSOpts.ModulesHashContent = true;
  940. FrontendOpts.Inputs = {Input};
  941. // Don't free the remapped file buffers; they are owned by our caller.
  942. PPOpts.RetainRemappedFileBuffers = true;
  943. Invocation->getDiagnosticOpts().VerifyDiagnostics = 0;
  944. assert(ImportingInstance.getInvocation().getModuleHash() ==
  945. Invocation->getModuleHash() && "Module hash mismatch!");
  946. // Construct a compiler instance that will be used to actually create the
  947. // module. Since we're sharing an in-memory module cache,
  948. // CompilerInstance::CompilerInstance is responsible for finalizing the
  949. // buffers to prevent use-after-frees.
  950. CompilerInstance Instance(ImportingInstance.getPCHContainerOperations(),
  951. &ImportingInstance.getModuleCache());
  952. auto &Inv = *Invocation;
  953. Instance.setInvocation(std::move(Invocation));
  954. Instance.createDiagnostics(new ForwardingDiagnosticConsumer(
  955. ImportingInstance.getDiagnosticClient()),
  956. /*ShouldOwnClient=*/true);
  957. // Note that this module is part of the module build stack, so that we
  958. // can detect cycles in the module graph.
  959. Instance.setFileManager(&ImportingInstance.getFileManager());
  960. Instance.createSourceManager(Instance.getFileManager());
  961. SourceManager &SourceMgr = Instance.getSourceManager();
  962. SourceMgr.setModuleBuildStack(
  963. ImportingInstance.getSourceManager().getModuleBuildStack());
  964. SourceMgr.pushModuleBuildStack(ModuleName,
  965. FullSourceLoc(ImportLoc, ImportingInstance.getSourceManager()));
  966. // If we're collecting module dependencies, we need to share a collector
  967. // between all of the module CompilerInstances. Other than that, we don't
  968. // want to produce any dependency output from the module build.
  969. Instance.setModuleDepCollector(ImportingInstance.getModuleDepCollector());
  970. Inv.getDependencyOutputOpts() = DependencyOutputOptions();
  971. ImportingInstance.getDiagnostics().Report(ImportLoc,
  972. diag::remark_module_build)
  973. << ModuleName << ModuleFileName;
  974. PreBuildStep(Instance);
  975. // Execute the action to actually build the module in-place. Use a separate
  976. // thread so that we get a stack large enough.
  977. llvm::CrashRecoveryContext CRC;
  978. CRC.RunSafelyOnThread(
  979. [&]() {
  980. GenerateModuleFromModuleMapAction Action;
  981. Instance.ExecuteAction(Action);
  982. },
  983. DesiredStackSize);
  984. PostBuildStep(Instance);
  985. ImportingInstance.getDiagnostics().Report(ImportLoc,
  986. diag::remark_module_build_done)
  987. << ModuleName;
  988. // Delete the temporary module map file.
  989. // FIXME: Even though we're executing under crash protection, it would still
  990. // be nice to do this with RemoveFileOnSignal when we can. However, that
  991. // doesn't make sense for all clients, so clean this up manually.
  992. Instance.clearOutputFiles(/*EraseFiles=*/true);
  993. return !Instance.getDiagnostics().hasErrorOccurred();
  994. }
  995. static const FileEntry *getPublicModuleMap(const FileEntry *File,
  996. FileManager &FileMgr) {
  997. StringRef Filename = llvm::sys::path::filename(File->getName());
  998. SmallString<128> PublicFilename(File->getDir()->getName());
  999. if (Filename == "module_private.map")
  1000. llvm::sys::path::append(PublicFilename, "module.map");
  1001. else if (Filename == "module.private.modulemap")
  1002. llvm::sys::path::append(PublicFilename, "module.modulemap");
  1003. else
  1004. return nullptr;
  1005. if (auto FE = FileMgr.getFile(PublicFilename))
  1006. return *FE;
  1007. return nullptr;
  1008. }
  1009. /// Compile a module file for the given module, using the options
  1010. /// provided by the importing compiler instance. Returns true if the module
  1011. /// was built without errors.
  1012. static bool compileModuleImpl(CompilerInstance &ImportingInstance,
  1013. SourceLocation ImportLoc,
  1014. Module *Module,
  1015. StringRef ModuleFileName) {
  1016. InputKind IK(getLanguageFromOptions(ImportingInstance.getLangOpts()),
  1017. InputKind::ModuleMap);
  1018. // Get or create the module map that we'll use to build this module.
  1019. ModuleMap &ModMap
  1020. = ImportingInstance.getPreprocessor().getHeaderSearchInfo().getModuleMap();
  1021. bool Result;
  1022. if (const FileEntry *ModuleMapFile =
  1023. ModMap.getContainingModuleMapFile(Module)) {
  1024. // Canonicalize compilation to start with the public module map. This is
  1025. // vital for submodules declarations in the private module maps to be
  1026. // correctly parsed when depending on a top level module in the public one.
  1027. if (const FileEntry *PublicMMFile = getPublicModuleMap(
  1028. ModuleMapFile, ImportingInstance.getFileManager()))
  1029. ModuleMapFile = PublicMMFile;
  1030. // Use the module map where this module resides.
  1031. Result = compileModuleImpl(
  1032. ImportingInstance, ImportLoc, Module->getTopLevelModuleName(),
  1033. FrontendInputFile(ModuleMapFile->getName(), IK, +Module->IsSystem),
  1034. ModMap.getModuleMapFileForUniquing(Module)->getName(),
  1035. ModuleFileName);
  1036. } else {
  1037. // FIXME: We only need to fake up an input file here as a way of
  1038. // transporting the module's directory to the module map parser. We should
  1039. // be able to do that more directly, and parse from a memory buffer without
  1040. // inventing this file.
  1041. SmallString<128> FakeModuleMapFile(Module->Directory->getName());
  1042. llvm::sys::path::append(FakeModuleMapFile, "__inferred_module.map");
  1043. std::string InferredModuleMapContent;
  1044. llvm::raw_string_ostream OS(InferredModuleMapContent);
  1045. Module->print(OS);
  1046. OS.flush();
  1047. Result = compileModuleImpl(
  1048. ImportingInstance, ImportLoc, Module->getTopLevelModuleName(),
  1049. FrontendInputFile(FakeModuleMapFile, IK, +Module->IsSystem),
  1050. ModMap.getModuleMapFileForUniquing(Module)->getName(),
  1051. ModuleFileName,
  1052. [&](CompilerInstance &Instance) {
  1053. std::unique_ptr<llvm::MemoryBuffer> ModuleMapBuffer =
  1054. llvm::MemoryBuffer::getMemBuffer(InferredModuleMapContent);
  1055. ModuleMapFile = Instance.getFileManager().getVirtualFile(
  1056. FakeModuleMapFile, InferredModuleMapContent.size(), 0);
  1057. Instance.getSourceManager().overrideFileContents(
  1058. ModuleMapFile, std::move(ModuleMapBuffer));
  1059. });
  1060. }
  1061. // We've rebuilt a module. If we're allowed to generate or update the global
  1062. // module index, record that fact in the importing compiler instance.
  1063. if (ImportingInstance.getFrontendOpts().GenerateGlobalModuleIndex) {
  1064. ImportingInstance.setBuildGlobalModuleIndex(true);
  1065. }
  1066. return Result;
  1067. }
  1068. static bool compileAndLoadModule(CompilerInstance &ImportingInstance,
  1069. SourceLocation ImportLoc,
  1070. SourceLocation ModuleNameLoc, Module *Module,
  1071. StringRef ModuleFileName) {
  1072. DiagnosticsEngine &Diags = ImportingInstance.getDiagnostics();
  1073. auto diagnoseBuildFailure = [&] {
  1074. Diags.Report(ModuleNameLoc, diag::err_module_not_built)
  1075. << Module->Name << SourceRange(ImportLoc, ModuleNameLoc);
  1076. };
  1077. // FIXME: have LockFileManager return an error_code so that we can
  1078. // avoid the mkdir when the directory already exists.
  1079. StringRef Dir = llvm::sys::path::parent_path(ModuleFileName);
  1080. llvm::sys::fs::create_directories(Dir);
  1081. while (1) {
  1082. unsigned ModuleLoadCapabilities = ASTReader::ARR_Missing;
  1083. llvm::LockFileManager Locked(ModuleFileName);
  1084. switch (Locked) {
  1085. case llvm::LockFileManager::LFS_Error:
  1086. // ModuleCache takes care of correctness and locks are only necessary for
  1087. // performance. Fallback to building the module in case of any lock
  1088. // related errors.
  1089. Diags.Report(ModuleNameLoc, diag::remark_module_lock_failure)
  1090. << Module->Name << Locked.getErrorMessage();
  1091. // Clear out any potential leftover.
  1092. Locked.unsafeRemoveLockFile();
  1093. LLVM_FALLTHROUGH;
  1094. case llvm::LockFileManager::LFS_Owned:
  1095. // We're responsible for building the module ourselves.
  1096. if (!compileModuleImpl(ImportingInstance, ModuleNameLoc, Module,
  1097. ModuleFileName)) {
  1098. diagnoseBuildFailure();
  1099. return false;
  1100. }
  1101. break;
  1102. case llvm::LockFileManager::LFS_Shared:
  1103. // Someone else is responsible for building the module. Wait for them to
  1104. // finish.
  1105. switch (Locked.waitForUnlock()) {
  1106. case llvm::LockFileManager::Res_Success:
  1107. ModuleLoadCapabilities |= ASTReader::ARR_OutOfDate;
  1108. break;
  1109. case llvm::LockFileManager::Res_OwnerDied:
  1110. continue; // try again to get the lock.
  1111. case llvm::LockFileManager::Res_Timeout:
  1112. // Since ModuleCache takes care of correctness, we try waiting for
  1113. // another process to complete the build so clang does not do it done
  1114. // twice. If case of timeout, build it ourselves.
  1115. Diags.Report(ModuleNameLoc, diag::remark_module_lock_timeout)
  1116. << Module->Name;
  1117. // Clear the lock file so that future invocations can make progress.
  1118. Locked.unsafeRemoveLockFile();
  1119. continue;
  1120. }
  1121. break;
  1122. }
  1123. // Try to read the module file, now that we've compiled it.
  1124. ASTReader::ASTReadResult ReadResult =
  1125. ImportingInstance.getModuleManager()->ReadAST(
  1126. ModuleFileName, serialization::MK_ImplicitModule, ImportLoc,
  1127. ModuleLoadCapabilities);
  1128. if (ReadResult == ASTReader::OutOfDate &&
  1129. Locked == llvm::LockFileManager::LFS_Shared) {
  1130. // The module may be out of date in the presence of file system races,
  1131. // or if one of its imports depends on header search paths that are not
  1132. // consistent with this ImportingInstance. Try again...
  1133. continue;
  1134. } else if (ReadResult == ASTReader::Missing) {
  1135. diagnoseBuildFailure();
  1136. } else if (ReadResult != ASTReader::Success &&
  1137. !Diags.hasErrorOccurred()) {
  1138. // The ASTReader didn't diagnose the error, so conservatively report it.
  1139. diagnoseBuildFailure();
  1140. }
  1141. return ReadResult == ASTReader::Success;
  1142. }
  1143. }
  1144. /// Diagnose differences between the current definition of the given
  1145. /// configuration macro and the definition provided on the command line.
  1146. static void checkConfigMacro(Preprocessor &PP, StringRef ConfigMacro,
  1147. Module *Mod, SourceLocation ImportLoc) {
  1148. IdentifierInfo *Id = PP.getIdentifierInfo(ConfigMacro);
  1149. SourceManager &SourceMgr = PP.getSourceManager();
  1150. // If this identifier has never had a macro definition, then it could
  1151. // not have changed.
  1152. if (!Id->hadMacroDefinition())
  1153. return;
  1154. auto *LatestLocalMD = PP.getLocalMacroDirectiveHistory(Id);
  1155. // Find the macro definition from the command line.
  1156. MacroInfo *CmdLineDefinition = nullptr;
  1157. for (auto *MD = LatestLocalMD; MD; MD = MD->getPrevious()) {
  1158. // We only care about the predefines buffer.
  1159. FileID FID = SourceMgr.getFileID(MD->getLocation());
  1160. if (FID.isInvalid() || FID != PP.getPredefinesFileID())
  1161. continue;
  1162. if (auto *DMD = dyn_cast<DefMacroDirective>(MD))
  1163. CmdLineDefinition = DMD->getMacroInfo();
  1164. break;
  1165. }
  1166. auto *CurrentDefinition = PP.getMacroInfo(Id);
  1167. if (CurrentDefinition == CmdLineDefinition) {
  1168. // Macro matches. Nothing to do.
  1169. } else if (!CurrentDefinition) {
  1170. // This macro was defined on the command line, then #undef'd later.
  1171. // Complain.
  1172. PP.Diag(ImportLoc, diag::warn_module_config_macro_undef)
  1173. << true << ConfigMacro << Mod->getFullModuleName();
  1174. auto LatestDef = LatestLocalMD->getDefinition();
  1175. assert(LatestDef.isUndefined() &&
  1176. "predefined macro went away with no #undef?");
  1177. PP.Diag(LatestDef.getUndefLocation(), diag::note_module_def_undef_here)
  1178. << true;
  1179. return;
  1180. } else if (!CmdLineDefinition) {
  1181. // There was no definition for this macro in the predefines buffer,
  1182. // but there was a local definition. Complain.
  1183. PP.Diag(ImportLoc, diag::warn_module_config_macro_undef)
  1184. << false << ConfigMacro << Mod->getFullModuleName();
  1185. PP.Diag(CurrentDefinition->getDefinitionLoc(),
  1186. diag::note_module_def_undef_here)
  1187. << false;
  1188. } else if (!CurrentDefinition->isIdenticalTo(*CmdLineDefinition, PP,
  1189. /*Syntactically=*/true)) {
  1190. // The macro definitions differ.
  1191. PP.Diag(ImportLoc, diag::warn_module_config_macro_undef)
  1192. << false << ConfigMacro << Mod->getFullModuleName();
  1193. PP.Diag(CurrentDefinition->getDefinitionLoc(),
  1194. diag::note_module_def_undef_here)
  1195. << false;
  1196. }
  1197. }
  1198. /// Write a new timestamp file with the given path.
  1199. static void writeTimestampFile(StringRef TimestampFile) {
  1200. std::error_code EC;
  1201. llvm::raw_fd_ostream Out(TimestampFile.str(), EC, llvm::sys::fs::OF_None);
  1202. }
  1203. /// Prune the module cache of modules that haven't been accessed in
  1204. /// a long time.
  1205. static void pruneModuleCache(const HeaderSearchOptions &HSOpts) {
  1206. struct stat StatBuf;
  1207. llvm::SmallString<128> TimestampFile;
  1208. TimestampFile = HSOpts.ModuleCachePath;
  1209. assert(!TimestampFile.empty());
  1210. llvm::sys::path::append(TimestampFile, "modules.timestamp");
  1211. // Try to stat() the timestamp file.
  1212. if (::stat(TimestampFile.c_str(), &StatBuf)) {
  1213. // If the timestamp file wasn't there, create one now.
  1214. if (errno == ENOENT) {
  1215. writeTimestampFile(TimestampFile);
  1216. }
  1217. return;
  1218. }
  1219. // Check whether the time stamp is older than our pruning interval.
  1220. // If not, do nothing.
  1221. time_t TimeStampModTime = StatBuf.st_mtime;
  1222. time_t CurrentTime = time(nullptr);
  1223. if (CurrentTime - TimeStampModTime <= time_t(HSOpts.ModuleCachePruneInterval))
  1224. return;
  1225. // Write a new timestamp file so that nobody else attempts to prune.
  1226. // There is a benign race condition here, if two Clang instances happen to
  1227. // notice at the same time that the timestamp is out-of-date.
  1228. writeTimestampFile(TimestampFile);
  1229. // Walk the entire module cache, looking for unused module files and module
  1230. // indices.
  1231. std::error_code EC;
  1232. SmallString<128> ModuleCachePathNative;
  1233. llvm::sys::path::native(HSOpts.ModuleCachePath, ModuleCachePathNative);
  1234. for (llvm::sys::fs::directory_iterator Dir(ModuleCachePathNative, EC), DirEnd;
  1235. Dir != DirEnd && !EC; Dir.increment(EC)) {
  1236. // If we don't have a directory, there's nothing to look into.
  1237. if (!llvm::sys::fs::is_directory(Dir->path()))
  1238. continue;
  1239. // Walk all of the files within this directory.
  1240. for (llvm::sys::fs::directory_iterator File(Dir->path(), EC), FileEnd;
  1241. File != FileEnd && !EC; File.increment(EC)) {
  1242. // We only care about module and global module index files.
  1243. StringRef Extension = llvm::sys::path::extension(File->path());
  1244. if (Extension != ".pcm" && Extension != ".timestamp" &&
  1245. llvm::sys::path::filename(File->path()) != "modules.idx")
  1246. continue;
  1247. // Look at this file. If we can't stat it, there's nothing interesting
  1248. // there.
  1249. if (::stat(File->path().c_str(), &StatBuf))
  1250. continue;
  1251. // If the file has been used recently enough, leave it there.
  1252. time_t FileAccessTime = StatBuf.st_atime;
  1253. if (CurrentTime - FileAccessTime <=
  1254. time_t(HSOpts.ModuleCachePruneAfter)) {
  1255. continue;
  1256. }
  1257. // Remove the file.
  1258. llvm::sys::fs::remove(File->path());
  1259. // Remove the timestamp file.
  1260. std::string TimpestampFilename = File->path() + ".timestamp";
  1261. llvm::sys::fs::remove(TimpestampFilename);
  1262. }
  1263. // If we removed all of the files in the directory, remove the directory
  1264. // itself.
  1265. if (llvm::sys::fs::directory_iterator(Dir->path(), EC) ==
  1266. llvm::sys::fs::directory_iterator() && !EC)
  1267. llvm::sys::fs::remove(Dir->path());
  1268. }
  1269. }
  1270. void CompilerInstance::createModuleManager() {
  1271. if (!ModuleManager) {
  1272. if (!hasASTContext())
  1273. createASTContext();
  1274. // If we're implicitly building modules but not currently recursively
  1275. // building a module, check whether we need to prune the module cache.
  1276. if (getSourceManager().getModuleBuildStack().empty() &&
  1277. !getPreprocessor().getHeaderSearchInfo().getModuleCachePath().empty() &&
  1278. getHeaderSearchOpts().ModuleCachePruneInterval > 0 &&
  1279. getHeaderSearchOpts().ModuleCachePruneAfter > 0) {
  1280. pruneModuleCache(getHeaderSearchOpts());
  1281. }
  1282. HeaderSearchOptions &HSOpts = getHeaderSearchOpts();
  1283. std::string Sysroot = HSOpts.Sysroot;
  1284. const PreprocessorOptions &PPOpts = getPreprocessorOpts();
  1285. std::unique_ptr<llvm::Timer> ReadTimer;
  1286. if (FrontendTimerGroup)
  1287. ReadTimer = std::make_unique<llvm::Timer>("reading_modules",
  1288. "Reading modules",
  1289. *FrontendTimerGroup);
  1290. ModuleManager = new ASTReader(
  1291. getPreprocessor(), getModuleCache(), &getASTContext(),
  1292. getPCHContainerReader(), getFrontendOpts().ModuleFileExtensions,
  1293. Sysroot.empty() ? "" : Sysroot.c_str(), PPOpts.DisablePCHValidation,
  1294. /*AllowASTWithCompilerErrors=*/false,
  1295. /*AllowConfigurationMismatch=*/false,
  1296. HSOpts.ModulesValidateSystemHeaders,
  1297. HSOpts.ValidateASTInputFilesContent,
  1298. getFrontendOpts().UseGlobalModuleIndex, std::move(ReadTimer));
  1299. if (hasASTConsumer()) {
  1300. ModuleManager->setDeserializationListener(
  1301. getASTConsumer().GetASTDeserializationListener());
  1302. getASTContext().setASTMutationListener(
  1303. getASTConsumer().GetASTMutationListener());
  1304. }
  1305. getASTContext().setExternalSource(ModuleManager);
  1306. if (hasSema())
  1307. ModuleManager->InitializeSema(getSema());
  1308. if (hasASTConsumer())
  1309. ModuleManager->StartTranslationUnit(&getASTConsumer());
  1310. for (auto &Listener : DependencyCollectors)
  1311. Listener->attachToASTReader(*ModuleManager);
  1312. }
  1313. }
  1314. bool CompilerInstance::loadModuleFile(StringRef FileName) {
  1315. llvm::Timer Timer;
  1316. if (FrontendTimerGroup)
  1317. Timer.init("preloading." + FileName.str(), "Preloading " + FileName.str(),
  1318. *FrontendTimerGroup);
  1319. llvm::TimeRegion TimeLoading(FrontendTimerGroup ? &Timer : nullptr);
  1320. // Helper to recursively read the module names for all modules we're adding.
  1321. // We mark these as known and redirect any attempt to load that module to
  1322. // the files we were handed.
  1323. struct ReadModuleNames : ASTReaderListener {
  1324. CompilerInstance &CI;
  1325. llvm::SmallVector<IdentifierInfo*, 8> LoadedModules;
  1326. ReadModuleNames(CompilerInstance &CI) : CI(CI) {}
  1327. void ReadModuleName(StringRef ModuleName) override {
  1328. LoadedModules.push_back(
  1329. CI.getPreprocessor().getIdentifierInfo(ModuleName));
  1330. }
  1331. void registerAll() {
  1332. for (auto *II : LoadedModules) {
  1333. CI.KnownModules[II] = CI.getPreprocessor()
  1334. .getHeaderSearchInfo()
  1335. .getModuleMap()
  1336. .findModule(II->getName());
  1337. }
  1338. LoadedModules.clear();
  1339. }
  1340. void markAllUnavailable() {
  1341. for (auto *II : LoadedModules) {
  1342. if (Module *M = CI.getPreprocessor()
  1343. .getHeaderSearchInfo()
  1344. .getModuleMap()
  1345. .findModule(II->getName())) {
  1346. M->HasIncompatibleModuleFile = true;
  1347. // Mark module as available if the only reason it was unavailable
  1348. // was missing headers.
  1349. SmallVector<Module *, 2> Stack;
  1350. Stack.push_back(M);
  1351. while (!Stack.empty()) {
  1352. Module *Current = Stack.pop_back_val();
  1353. if (Current->IsMissingRequirement) continue;
  1354. Current->IsAvailable = true;
  1355. Stack.insert(Stack.end(),
  1356. Current->submodule_begin(), Current->submodule_end());
  1357. }
  1358. }
  1359. }
  1360. LoadedModules.clear();
  1361. }
  1362. };
  1363. // If we don't already have an ASTReader, create one now.
  1364. if (!ModuleManager)
  1365. createModuleManager();
  1366. // If -Wmodule-file-config-mismatch is mapped as an error or worse, allow the
  1367. // ASTReader to diagnose it, since it can produce better errors that we can.
  1368. bool ConfigMismatchIsRecoverable =
  1369. getDiagnostics().getDiagnosticLevel(diag::warn_module_config_mismatch,
  1370. SourceLocation())
  1371. <= DiagnosticsEngine::Warning;
  1372. auto Listener = std::make_unique<ReadModuleNames>(*this);
  1373. auto &ListenerRef = *Listener;
  1374. ASTReader::ListenerScope ReadModuleNamesListener(*ModuleManager,
  1375. std::move(Listener));
  1376. // Try to load the module file.
  1377. switch (ModuleManager->ReadAST(
  1378. FileName, serialization::MK_ExplicitModule, SourceLocation(),
  1379. ConfigMismatchIsRecoverable ? ASTReader::ARR_ConfigurationMismatch : 0)) {
  1380. case ASTReader::Success:
  1381. // We successfully loaded the module file; remember the set of provided
  1382. // modules so that we don't try to load implicit modules for them.
  1383. ListenerRef.registerAll();
  1384. return true;
  1385. case ASTReader::ConfigurationMismatch:
  1386. // Ignore unusable module files.
  1387. getDiagnostics().Report(SourceLocation(), diag::warn_module_config_mismatch)
  1388. << FileName;
  1389. // All modules provided by any files we tried and failed to load are now
  1390. // unavailable; includes of those modules should now be handled textually.
  1391. ListenerRef.markAllUnavailable();
  1392. return true;
  1393. default:
  1394. return false;
  1395. }
  1396. }
  1397. ModuleLoadResult
  1398. CompilerInstance::loadModule(SourceLocation ImportLoc,
  1399. ModuleIdPath Path,
  1400. Module::NameVisibilityKind Visibility,
  1401. bool IsInclusionDirective) {
  1402. // Determine what file we're searching from.
  1403. StringRef ModuleName = Path[0].first->getName();
  1404. SourceLocation ModuleNameLoc = Path[0].second;
  1405. // If we've already handled this import, just return the cached result.
  1406. // This one-element cache is important to eliminate redundant diagnostics
  1407. // when both the preprocessor and parser see the same import declaration.
  1408. if (ImportLoc.isValid() && LastModuleImportLoc == ImportLoc) {
  1409. // Make the named module visible.
  1410. if (LastModuleImportResult && ModuleName != getLangOpts().CurrentModule)
  1411. ModuleManager->makeModuleVisible(LastModuleImportResult, Visibility,
  1412. ImportLoc);
  1413. return LastModuleImportResult;
  1414. }
  1415. clang::Module *Module = nullptr;
  1416. // If we don't already have information on this module, load the module now.
  1417. llvm::DenseMap<const IdentifierInfo *, clang::Module *>::iterator Known
  1418. = KnownModules.find(Path[0].first);
  1419. if (Known != KnownModules.end()) {
  1420. // Retrieve the cached top-level module.
  1421. Module = Known->second;
  1422. } else if (ModuleName == getLangOpts().CurrentModule) {
  1423. // This is the module we're building.
  1424. Module = PP->getHeaderSearchInfo().lookupModule(
  1425. ModuleName, /*AllowSearch*/ true,
  1426. /*AllowExtraModuleMapSearch*/ !IsInclusionDirective);
  1427. /// FIXME: perhaps we should (a) look for a module using the module name
  1428. // to file map (PrebuiltModuleFiles) and (b) diagnose if still not found?
  1429. //if (Module == nullptr) {
  1430. // getDiagnostics().Report(ModuleNameLoc, diag::err_module_not_found)
  1431. // << ModuleName;
  1432. // ModuleBuildFailed = true;
  1433. // return ModuleLoadResult();
  1434. //}
  1435. Known = KnownModules.insert(std::make_pair(Path[0].first, Module)).first;
  1436. } else {
  1437. // Search for a module with the given name.
  1438. Module = PP->getHeaderSearchInfo().lookupModule(ModuleName, true,
  1439. !IsInclusionDirective);
  1440. HeaderSearchOptions &HSOpts =
  1441. PP->getHeaderSearchInfo().getHeaderSearchOpts();
  1442. std::string ModuleFileName;
  1443. enum ModuleSource {
  1444. ModuleNotFound, ModuleCache, PrebuiltModulePath, ModuleBuildPragma
  1445. } Source = ModuleNotFound;
  1446. // Check to see if the module has been built as part of this compilation
  1447. // via a module build pragma.
  1448. auto BuiltModuleIt = BuiltModules.find(ModuleName);
  1449. if (BuiltModuleIt != BuiltModules.end()) {
  1450. ModuleFileName = BuiltModuleIt->second;
  1451. Source = ModuleBuildPragma;
  1452. }
  1453. // Try to load the module from the prebuilt module path.
  1454. if (Source == ModuleNotFound && (!HSOpts.PrebuiltModuleFiles.empty() ||
  1455. !HSOpts.PrebuiltModulePaths.empty())) {
  1456. ModuleFileName =
  1457. PP->getHeaderSearchInfo().getPrebuiltModuleFileName(ModuleName);
  1458. if (!ModuleFileName.empty())
  1459. Source = PrebuiltModulePath;
  1460. }
  1461. // Try to load the module from the module cache.
  1462. if (Source == ModuleNotFound && Module) {
  1463. ModuleFileName = PP->getHeaderSearchInfo().getCachedModuleFileName(Module);
  1464. Source = ModuleCache;
  1465. }
  1466. if (Source == ModuleNotFound) {
  1467. // We can't find a module, error out here.
  1468. getDiagnostics().Report(ModuleNameLoc, diag::err_module_not_found)
  1469. << ModuleName << SourceRange(ImportLoc, ModuleNameLoc);
  1470. ModuleBuildFailed = true;
  1471. return ModuleLoadResult();
  1472. }
  1473. if (ModuleFileName.empty()) {
  1474. if (Module && Module->HasIncompatibleModuleFile) {
  1475. // We tried and failed to load a module file for this module. Fall
  1476. // back to textual inclusion for its headers.
  1477. return ModuleLoadResult::ConfigMismatch;
  1478. }
  1479. getDiagnostics().Report(ModuleNameLoc, diag::err_module_build_disabled)
  1480. << ModuleName;
  1481. ModuleBuildFailed = true;
  1482. return ModuleLoadResult();
  1483. }
  1484. // If we don't already have an ASTReader, create one now.
  1485. if (!ModuleManager)
  1486. createModuleManager();
  1487. llvm::Timer Timer;
  1488. if (FrontendTimerGroup)
  1489. Timer.init("loading." + ModuleFileName, "Loading " + ModuleFileName,
  1490. *FrontendTimerGroup);
  1491. llvm::TimeRegion TimeLoading(FrontendTimerGroup ? &Timer : nullptr);
  1492. llvm::TimeTraceScope TimeScope("Module Load", ModuleName);
  1493. // Try to load the module file. If we are not trying to load from the
  1494. // module cache, we don't know how to rebuild modules.
  1495. unsigned ARRFlags = Source == ModuleCache ?
  1496. ASTReader::ARR_OutOfDate | ASTReader::ARR_Missing :
  1497. Source == PrebuiltModulePath ?
  1498. 0 :
  1499. ASTReader::ARR_ConfigurationMismatch;
  1500. switch (ModuleManager->ReadAST(ModuleFileName,
  1501. Source == PrebuiltModulePath
  1502. ? serialization::MK_PrebuiltModule
  1503. : Source == ModuleBuildPragma
  1504. ? serialization::MK_ExplicitModule
  1505. : serialization::MK_ImplicitModule,
  1506. ImportLoc, ARRFlags)) {
  1507. case ASTReader::Success: {
  1508. if (Source != ModuleCache && !Module) {
  1509. Module = PP->getHeaderSearchInfo().lookupModule(ModuleName, true,
  1510. !IsInclusionDirective);
  1511. auto ModuleFile = FileMgr->getFile(ModuleFileName);
  1512. if (!Module || !Module->getASTFile() ||
  1513. !ModuleFile || (*ModuleFile != Module->getASTFile())) {
  1514. // Error out if Module does not refer to the file in the prebuilt
  1515. // module path.
  1516. getDiagnostics().Report(ModuleNameLoc, diag::err_module_prebuilt)
  1517. << ModuleName;
  1518. ModuleBuildFailed = true;
  1519. KnownModules[Path[0].first] = nullptr;
  1520. return ModuleLoadResult();
  1521. }
  1522. }
  1523. break;
  1524. }
  1525. case ASTReader::OutOfDate:
  1526. case ASTReader::Missing: {
  1527. if (Source != ModuleCache) {
  1528. // We don't know the desired configuration for this module and don't
  1529. // necessarily even have a module map. Since ReadAST already produces
  1530. // diagnostics for these two cases, we simply error out here.
  1531. ModuleBuildFailed = true;
  1532. KnownModules[Path[0].first] = nullptr;
  1533. return ModuleLoadResult();
  1534. }
  1535. // The module file is missing or out-of-date. Build it.
  1536. assert(Module && "missing module file");
  1537. // Check whether there is a cycle in the module graph.
  1538. ModuleBuildStack ModPath = getSourceManager().getModuleBuildStack();
  1539. ModuleBuildStack::iterator Pos = ModPath.begin(), PosEnd = ModPath.end();
  1540. for (; Pos != PosEnd; ++Pos) {
  1541. if (Pos->first == ModuleName)
  1542. break;
  1543. }
  1544. if (Pos != PosEnd) {
  1545. SmallString<256> CyclePath;
  1546. for (; Pos != PosEnd; ++Pos) {
  1547. CyclePath += Pos->first;
  1548. CyclePath += " -> ";
  1549. }
  1550. CyclePath += ModuleName;
  1551. getDiagnostics().Report(ModuleNameLoc, diag::err_module_cycle)
  1552. << ModuleName << CyclePath;
  1553. return ModuleLoadResult();
  1554. }
  1555. // Check whether we have already attempted to build this module (but
  1556. // failed).
  1557. if (getPreprocessorOpts().FailedModules &&
  1558. getPreprocessorOpts().FailedModules->hasAlreadyFailed(ModuleName)) {
  1559. getDiagnostics().Report(ModuleNameLoc, diag::err_module_not_built)
  1560. << ModuleName
  1561. << SourceRange(ImportLoc, ModuleNameLoc);
  1562. ModuleBuildFailed = true;
  1563. return ModuleLoadResult();
  1564. }
  1565. // Try to compile and then load the module.
  1566. if (!compileAndLoadModule(*this, ImportLoc, ModuleNameLoc, Module,
  1567. ModuleFileName)) {
  1568. assert(getDiagnostics().hasErrorOccurred() &&
  1569. "undiagnosed error in compileAndLoadModule");
  1570. if (getPreprocessorOpts().FailedModules)
  1571. getPreprocessorOpts().FailedModules->addFailed(ModuleName);
  1572. KnownModules[Path[0].first] = nullptr;
  1573. ModuleBuildFailed = true;
  1574. return ModuleLoadResult();
  1575. }
  1576. // Okay, we've rebuilt and now loaded the module.
  1577. break;
  1578. }
  1579. case ASTReader::ConfigurationMismatch:
  1580. if (Source == PrebuiltModulePath)
  1581. // FIXME: We shouldn't be setting HadFatalFailure below if we only
  1582. // produce a warning here!
  1583. getDiagnostics().Report(SourceLocation(),
  1584. diag::warn_module_config_mismatch)
  1585. << ModuleFileName;
  1586. // Fall through to error out.
  1587. LLVM_FALLTHROUGH;
  1588. case ASTReader::VersionMismatch:
  1589. case ASTReader::HadErrors:
  1590. ModuleLoader::HadFatalFailure = true;
  1591. // FIXME: The ASTReader will already have complained, but can we shoehorn
  1592. // that diagnostic information into a more useful form?
  1593. KnownModules[Path[0].first] = nullptr;
  1594. return ModuleLoadResult();
  1595. case ASTReader::Failure:
  1596. ModuleLoader::HadFatalFailure = true;
  1597. // Already complained, but note now that we failed.
  1598. KnownModules[Path[0].first] = nullptr;
  1599. ModuleBuildFailed = true;
  1600. return ModuleLoadResult();
  1601. }
  1602. // Cache the result of this top-level module lookup for later.
  1603. Known = KnownModules.insert(std::make_pair(Path[0].first, Module)).first;
  1604. }
  1605. // If we never found the module, fail.
  1606. if (!Module)
  1607. return ModuleLoadResult();
  1608. // Verify that the rest of the module path actually corresponds to
  1609. // a submodule.
  1610. bool MapPrivateSubModToTopLevel = false;
  1611. if (Path.size() > 1) {
  1612. for (unsigned I = 1, N = Path.size(); I != N; ++I) {
  1613. StringRef Name = Path[I].first->getName();
  1614. clang::Module *Sub = Module->findSubmodule(Name);
  1615. // If the user is requesting Foo.Private and it doesn't exist, try to
  1616. // match Foo_Private and emit a warning asking for the user to write
  1617. // @import Foo_Private instead. FIXME: remove this when existing clients
  1618. // migrate off of Foo.Private syntax.
  1619. if (!Sub && PP->getLangOpts().ImplicitModules && Name == "Private" &&
  1620. Module == Module->getTopLevelModule()) {
  1621. SmallString<128> PrivateModule(Module->Name);
  1622. PrivateModule.append("_Private");
  1623. SmallVector<std::pair<IdentifierInfo *, SourceLocation>, 2> PrivPath;
  1624. auto &II = PP->getIdentifierTable().get(
  1625. PrivateModule, PP->getIdentifierInfo(Module->Name)->getTokenID());
  1626. PrivPath.push_back(std::make_pair(&II, Path[0].second));
  1627. if (PP->getHeaderSearchInfo().lookupModule(PrivateModule, true,
  1628. !IsInclusionDirective))
  1629. Sub =
  1630. loadModule(ImportLoc, PrivPath, Visibility, IsInclusionDirective);
  1631. if (Sub) {
  1632. MapPrivateSubModToTopLevel = true;
  1633. if (!getDiagnostics().isIgnored(
  1634. diag::warn_no_priv_submodule_use_toplevel, ImportLoc)) {
  1635. getDiagnostics().Report(Path[I].second,
  1636. diag::warn_no_priv_submodule_use_toplevel)
  1637. << Path[I].first << Module->getFullModuleName() << PrivateModule
  1638. << SourceRange(Path[0].second, Path[I].second)
  1639. << FixItHint::CreateReplacement(SourceRange(Path[0].second),
  1640. PrivateModule);
  1641. getDiagnostics().Report(Sub->DefinitionLoc,
  1642. diag::note_private_top_level_defined);
  1643. }
  1644. }
  1645. }
  1646. if (!Sub) {
  1647. // Attempt to perform typo correction to find a module name that works.
  1648. SmallVector<StringRef, 2> Best;
  1649. unsigned BestEditDistance = (std::numeric_limits<unsigned>::max)();
  1650. for (clang::Module::submodule_iterator J = Module->submodule_begin(),
  1651. JEnd = Module->submodule_end();
  1652. J != JEnd; ++J) {
  1653. unsigned ED = Name.edit_distance((*J)->Name,
  1654. /*AllowReplacements=*/true,
  1655. BestEditDistance);
  1656. if (ED <= BestEditDistance) {
  1657. if (ED < BestEditDistance) {
  1658. Best.clear();
  1659. BestEditDistance = ED;
  1660. }
  1661. Best.push_back((*J)->Name);
  1662. }
  1663. }
  1664. // If there was a clear winner, user it.
  1665. if (Best.size() == 1) {
  1666. getDiagnostics().Report(Path[I].second,
  1667. diag::err_no_submodule_suggest)
  1668. << Path[I].first << Module->getFullModuleName() << Best[0]
  1669. << SourceRange(Path[0].second, Path[I-1].second)
  1670. << FixItHint::CreateReplacement(SourceRange(Path[I].second),
  1671. Best[0]);
  1672. Sub = Module->findSubmodule(Best[0]);
  1673. }
  1674. }
  1675. if (!Sub) {
  1676. // No submodule by this name. Complain, and don't look for further
  1677. // submodules.
  1678. getDiagnostics().Report(Path[I].second, diag::err_no_submodule)
  1679. << Path[I].first << Module->getFullModuleName()
  1680. << SourceRange(Path[0].second, Path[I-1].second);
  1681. break;
  1682. }
  1683. Module = Sub;
  1684. }
  1685. }
  1686. // Make the named module visible, if it's not already part of the module
  1687. // we are parsing.
  1688. if (ModuleName != getLangOpts().CurrentModule) {
  1689. if (!Module->IsFromModuleFile && !MapPrivateSubModToTopLevel) {
  1690. // We have an umbrella header or directory that doesn't actually include
  1691. // all of the headers within the directory it covers. Complain about
  1692. // this missing submodule and recover by forgetting that we ever saw
  1693. // this submodule.
  1694. // FIXME: Should we detect this at module load time? It seems fairly
  1695. // expensive (and rare).
  1696. getDiagnostics().Report(ImportLoc, diag::warn_missing_submodule)
  1697. << Module->getFullModuleName()
  1698. << SourceRange(Path.front().second, Path.back().second);
  1699. return ModuleLoadResult::MissingExpected;
  1700. }
  1701. // Check whether this module is available.
  1702. if (Preprocessor::checkModuleIsAvailable(getLangOpts(), getTarget(),
  1703. getDiagnostics(), Module)) {
  1704. getDiagnostics().Report(ImportLoc, diag::note_module_import_here)
  1705. << SourceRange(Path.front().second, Path.back().second);
  1706. LastModuleImportLoc = ImportLoc;
  1707. LastModuleImportResult = ModuleLoadResult();
  1708. return ModuleLoadResult();
  1709. }
  1710. ModuleManager->makeModuleVisible(Module, Visibility, ImportLoc);
  1711. }
  1712. // Check for any configuration macros that have changed.
  1713. clang::Module *TopModule = Module->getTopLevelModule();
  1714. for (unsigned I = 0, N = TopModule->ConfigMacros.size(); I != N; ++I) {
  1715. checkConfigMacro(getPreprocessor(), TopModule->ConfigMacros[I],
  1716. Module, ImportLoc);
  1717. }
  1718. // Resolve any remaining module using export_as for this one.
  1719. getPreprocessor()
  1720. .getHeaderSearchInfo()
  1721. .getModuleMap()
  1722. .resolveLinkAsDependencies(TopModule);
  1723. LastModuleImportLoc = ImportLoc;
  1724. LastModuleImportResult = ModuleLoadResult(Module);
  1725. return LastModuleImportResult;
  1726. }
  1727. void CompilerInstance::loadModuleFromSource(SourceLocation ImportLoc,
  1728. StringRef ModuleName,
  1729. StringRef Source) {
  1730. // Avoid creating filenames with special characters.
  1731. SmallString<128> CleanModuleName(ModuleName);
  1732. for (auto &C : CleanModuleName)
  1733. if (!isAlphanumeric(C))
  1734. C = '_';
  1735. // FIXME: Using a randomized filename here means that our intermediate .pcm
  1736. // output is nondeterministic (as .pcm files refer to each other by name).
  1737. // Can this affect the output in any way?
  1738. SmallString<128> ModuleFileName;
  1739. if (std::error_code EC = llvm::sys::fs::createTemporaryFile(
  1740. CleanModuleName, "pcm", ModuleFileName)) {
  1741. getDiagnostics().Report(ImportLoc, diag::err_fe_unable_to_open_output)
  1742. << ModuleFileName << EC.message();
  1743. return;
  1744. }
  1745. std::string ModuleMapFileName = (CleanModuleName + ".map").str();
  1746. FrontendInputFile Input(
  1747. ModuleMapFileName,
  1748. InputKind(getLanguageFromOptions(*Invocation->getLangOpts()),
  1749. InputKind::ModuleMap, /*Preprocessed*/true));
  1750. std::string NullTerminatedSource(Source.str());
  1751. auto PreBuildStep = [&](CompilerInstance &Other) {
  1752. // Create a virtual file containing our desired source.
  1753. // FIXME: We shouldn't need to do this.
  1754. const FileEntry *ModuleMapFile = Other.getFileManager().getVirtualFile(
  1755. ModuleMapFileName, NullTerminatedSource.size(), 0);
  1756. Other.getSourceManager().overrideFileContents(
  1757. ModuleMapFile,
  1758. llvm::MemoryBuffer::getMemBuffer(NullTerminatedSource.c_str()));
  1759. Other.BuiltModules = std::move(BuiltModules);
  1760. Other.DeleteBuiltModules = false;
  1761. };
  1762. auto PostBuildStep = [this](CompilerInstance &Other) {
  1763. BuiltModules = std::move(Other.BuiltModules);
  1764. };
  1765. // Build the module, inheriting any modules that we've built locally.
  1766. if (compileModuleImpl(*this, ImportLoc, ModuleName, Input, StringRef(),
  1767. ModuleFileName, PreBuildStep, PostBuildStep)) {
  1768. BuiltModules[ModuleName] = ModuleFileName.str();
  1769. llvm::sys::RemoveFileOnSignal(ModuleFileName);
  1770. }
  1771. }
  1772. void CompilerInstance::makeModuleVisible(Module *Mod,
  1773. Module::NameVisibilityKind Visibility,
  1774. SourceLocation ImportLoc) {
  1775. if (!ModuleManager)
  1776. createModuleManager();
  1777. if (!ModuleManager)
  1778. return;
  1779. ModuleManager->makeModuleVisible(Mod, Visibility, ImportLoc);
  1780. }
  1781. GlobalModuleIndex *CompilerInstance::loadGlobalModuleIndex(
  1782. SourceLocation TriggerLoc) {
  1783. if (getPreprocessor().getHeaderSearchInfo().getModuleCachePath().empty())
  1784. return nullptr;
  1785. if (!ModuleManager)
  1786. createModuleManager();
  1787. // Can't do anything if we don't have the module manager.
  1788. if (!ModuleManager)
  1789. return nullptr;
  1790. // Get an existing global index. This loads it if not already
  1791. // loaded.
  1792. ModuleManager->loadGlobalIndex();
  1793. GlobalModuleIndex *GlobalIndex = ModuleManager->getGlobalIndex();
  1794. // If the global index doesn't exist, create it.
  1795. if (!GlobalIndex && shouldBuildGlobalModuleIndex() && hasFileManager() &&
  1796. hasPreprocessor()) {
  1797. llvm::sys::fs::create_directories(
  1798. getPreprocessor().getHeaderSearchInfo().getModuleCachePath());
  1799. if (llvm::Error Err = GlobalModuleIndex::writeIndex(
  1800. getFileManager(), getPCHContainerReader(),
  1801. getPreprocessor().getHeaderSearchInfo().getModuleCachePath())) {
  1802. // FIXME this drops the error on the floor. This code is only used for
  1803. // typo correction and drops more than just this one source of errors
  1804. // (such as the directory creation failure above). It should handle the
  1805. // error.
  1806. consumeError(std::move(Err));
  1807. return nullptr;
  1808. }
  1809. ModuleManager->resetForReload();
  1810. ModuleManager->loadGlobalIndex();
  1811. GlobalIndex = ModuleManager->getGlobalIndex();
  1812. }
  1813. // For finding modules needing to be imported for fixit messages,
  1814. // we need to make the global index cover all modules, so we do that here.
  1815. if (!HaveFullGlobalModuleIndex && GlobalIndex && !buildingModule()) {
  1816. ModuleMap &MMap = getPreprocessor().getHeaderSearchInfo().getModuleMap();
  1817. bool RecreateIndex = false;
  1818. for (ModuleMap::module_iterator I = MMap.module_begin(),
  1819. E = MMap.module_end(); I != E; ++I) {
  1820. Module *TheModule = I->second;
  1821. const FileEntry *Entry = TheModule->getASTFile();
  1822. if (!Entry) {
  1823. SmallVector<std::pair<IdentifierInfo *, SourceLocation>, 2> Path;
  1824. Path.push_back(std::make_pair(
  1825. getPreprocessor().getIdentifierInfo(TheModule->Name), TriggerLoc));
  1826. std::reverse(Path.begin(), Path.end());
  1827. // Load a module as hidden. This also adds it to the global index.
  1828. loadModule(TheModule->DefinitionLoc, Path, Module::Hidden, false);
  1829. RecreateIndex = true;
  1830. }
  1831. }
  1832. if (RecreateIndex) {
  1833. if (llvm::Error Err = GlobalModuleIndex::writeIndex(
  1834. getFileManager(), getPCHContainerReader(),
  1835. getPreprocessor().getHeaderSearchInfo().getModuleCachePath())) {
  1836. // FIXME As above, this drops the error on the floor.
  1837. consumeError(std::move(Err));
  1838. return nullptr;
  1839. }
  1840. ModuleManager->resetForReload();
  1841. ModuleManager->loadGlobalIndex();
  1842. GlobalIndex = ModuleManager->getGlobalIndex();
  1843. }
  1844. HaveFullGlobalModuleIndex = true;
  1845. }
  1846. return GlobalIndex;
  1847. }
  1848. // Check global module index for missing imports.
  1849. bool
  1850. CompilerInstance::lookupMissingImports(StringRef Name,
  1851. SourceLocation TriggerLoc) {
  1852. // Look for the symbol in non-imported modules, but only if an error
  1853. // actually occurred.
  1854. if (!buildingModule()) {
  1855. // Load global module index, or retrieve a previously loaded one.
  1856. GlobalModuleIndex *GlobalIndex = loadGlobalModuleIndex(
  1857. TriggerLoc);
  1858. // Only if we have a global index.
  1859. if (GlobalIndex) {
  1860. GlobalModuleIndex::HitSet FoundModules;
  1861. // Find the modules that reference the identifier.
  1862. // Note that this only finds top-level modules.
  1863. // We'll let diagnoseTypo find the actual declaration module.
  1864. if (GlobalIndex->lookupIdentifier(Name, FoundModules))
  1865. return true;
  1866. }
  1867. }
  1868. return false;
  1869. }
  1870. void CompilerInstance::resetAndLeakSema() { llvm::BuryPointer(takeSema()); }
  1871. void CompilerInstance::setExternalSemaSource(
  1872. IntrusiveRefCntPtr<ExternalSemaSource> ESS) {
  1873. ExternalSemaSrc = std::move(ESS);
  1874. }