CompilerInstance.cpp 82 KB

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