CompilerInstance.cpp 83 KB

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