CompilerInstance.cpp 82 KB

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