CompilerInstance.cpp 82 KB

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