CompilerInstance.cpp 88 KB

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