CompilerInstance.cpp 82 KB

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