CompilerInstance.cpp 82 KB

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