CompilerInstance.cpp 82 KB

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