CompilerInstance.cpp 66 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754
  1. //===--- CompilerInstance.cpp ---------------------------------------------===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. #include "clang/Frontend/CompilerInstance.h"
  10. #include "clang/AST/ASTConsumer.h"
  11. #include "clang/AST/ASTContext.h"
  12. #include "clang/AST/Decl.h"
  13. #include "clang/Basic/Diagnostic.h"
  14. #include "clang/Basic/FileManager.h"
  15. #include "clang/Basic/SourceManager.h"
  16. #include "clang/Basic/TargetInfo.h"
  17. #include "clang/Basic/Version.h"
  18. #include "clang/Config/config.h"
  19. #include "clang/Frontend/ChainedDiagnosticConsumer.h"
  20. #include "clang/Frontend/FrontendAction.h"
  21. #include "clang/Frontend/FrontendActions.h"
  22. #include "clang/Frontend/FrontendDiagnostic.h"
  23. #include "clang/Frontend/LogDiagnosticPrinter.h"
  24. #include "clang/Frontend/SerializedDiagnosticPrinter.h"
  25. #include "clang/Frontend/TextDiagnosticPrinter.h"
  26. #include "clang/Frontend/Utils.h"
  27. #include "clang/Frontend/VerifyDiagnosticConsumer.h"
  28. #include "clang/Lex/HeaderSearch.h"
  29. #include "clang/Lex/PTHManager.h"
  30. #include "clang/Lex/Preprocessor.h"
  31. #include "clang/Sema/CodeCompleteConsumer.h"
  32. #include "clang/Sema/Sema.h"
  33. #include "clang/Serialization/ASTReader.h"
  34. #include "clang/Serialization/GlobalModuleIndex.h"
  35. #include "llvm/ADT/Statistic.h"
  36. #include "llvm/Support/CrashRecoveryContext.h"
  37. #include "llvm/Support/Errc.h"
  38. #include "llvm/Support/FileSystem.h"
  39. #include "llvm/Support/Host.h"
  40. #include "llvm/Support/LockFileManager.h"
  41. #include "llvm/Support/MemoryBuffer.h"
  42. #include "llvm/Support/Path.h"
  43. #include "llvm/Support/Program.h"
  44. #include "llvm/Support/Signals.h"
  45. #include "llvm/Support/Timer.h"
  46. #include "llvm/Support/raw_ostream.h"
  47. #include <sys/stat.h>
  48. #include <system_error>
  49. #include <time.h>
  50. using namespace clang;
  51. CompilerInstance::CompilerInstance(bool BuildingModule)
  52. : ModuleLoader(BuildingModule),
  53. Invocation(new CompilerInvocation()), ModuleManager(nullptr),
  54. BuildGlobalModuleIndex(false), HaveFullGlobalModuleIndex(false),
  55. ModuleBuildFailed(false) {
  56. }
  57. CompilerInstance::~CompilerInstance() {
  58. assert(OutputFiles.empty() && "Still output files in flight?");
  59. }
  60. void CompilerInstance::setInvocation(CompilerInvocation *Value) {
  61. Invocation = Value;
  62. }
  63. bool CompilerInstance::shouldBuildGlobalModuleIndex() const {
  64. return (BuildGlobalModuleIndex ||
  65. (ModuleManager && ModuleManager->isGlobalIndexUnavailable() &&
  66. getFrontendOpts().GenerateGlobalModuleIndex)) &&
  67. !ModuleBuildFailed;
  68. }
  69. void CompilerInstance::setDiagnostics(DiagnosticsEngine *Value) {
  70. Diagnostics = Value;
  71. }
  72. void CompilerInstance::setTarget(TargetInfo *Value) {
  73. Target = Value;
  74. }
  75. void CompilerInstance::setFileManager(FileManager *Value) {
  76. FileMgr = Value;
  77. if (Value)
  78. VirtualFileSystem = Value->getVirtualFileSystem();
  79. else
  80. VirtualFileSystem.reset();
  81. }
  82. void CompilerInstance::setSourceManager(SourceManager *Value) {
  83. SourceMgr = Value;
  84. }
  85. void CompilerInstance::setPreprocessor(Preprocessor *Value) { PP = Value; }
  86. void CompilerInstance::setASTContext(ASTContext *Value) { Context = Value; }
  87. void CompilerInstance::setSema(Sema *S) {
  88. TheSema.reset(S);
  89. }
  90. void CompilerInstance::setASTConsumer(std::unique_ptr<ASTConsumer> Value) {
  91. Consumer = std::move(Value);
  92. }
  93. void CompilerInstance::setCodeCompletionConsumer(CodeCompleteConsumer *Value) {
  94. CompletionConsumer.reset(Value);
  95. }
  96. std::unique_ptr<Sema> CompilerInstance::takeSema() {
  97. return std::move(TheSema);
  98. }
  99. IntrusiveRefCntPtr<ASTReader> CompilerInstance::getModuleManager() const {
  100. return ModuleManager;
  101. }
  102. void CompilerInstance::setModuleManager(IntrusiveRefCntPtr<ASTReader> Reader) {
  103. ModuleManager = Reader;
  104. }
  105. std::shared_ptr<ModuleDependencyCollector>
  106. CompilerInstance::getModuleDepCollector() const {
  107. return ModuleDepCollector;
  108. }
  109. void CompilerInstance::setModuleDepCollector(
  110. std::shared_ptr<ModuleDependencyCollector> Collector) {
  111. ModuleDepCollector = Collector;
  112. }
  113. // Diagnostics
  114. static void SetUpDiagnosticLog(DiagnosticOptions *DiagOpts,
  115. const CodeGenOptions *CodeGenOpts,
  116. DiagnosticsEngine &Diags) {
  117. std::error_code EC;
  118. std::unique_ptr<raw_ostream> StreamOwner;
  119. raw_ostream *OS = &llvm::errs();
  120. if (DiagOpts->DiagnosticLogFile != "-") {
  121. // Create the output stream.
  122. auto FileOS = llvm::make_unique<llvm::raw_fd_ostream>(
  123. DiagOpts->DiagnosticLogFile, EC,
  124. llvm::sys::fs::F_Append | llvm::sys::fs::F_Text);
  125. if (EC) {
  126. Diags.Report(diag::warn_fe_cc_log_diagnostics_failure)
  127. << DiagOpts->DiagnosticLogFile << EC.message();
  128. } else {
  129. FileOS->SetUnbuffered();
  130. FileOS->SetUseAtomicWrites(true);
  131. OS = FileOS.get();
  132. StreamOwner = std::move(FileOS);
  133. }
  134. }
  135. // Chain in the diagnostic client which will log the diagnostics.
  136. auto Logger = llvm::make_unique<LogDiagnosticPrinter>(*OS, DiagOpts,
  137. std::move(StreamOwner));
  138. if (CodeGenOpts)
  139. Logger->setDwarfDebugFlags(CodeGenOpts->DwarfDebugFlags);
  140. assert(Diags.ownsClient());
  141. Diags.setClient(
  142. new ChainedDiagnosticConsumer(Diags.takeClient(), std::move(Logger)));
  143. }
  144. static void SetupSerializedDiagnostics(DiagnosticOptions *DiagOpts,
  145. DiagnosticsEngine &Diags,
  146. StringRef OutputFile) {
  147. auto SerializedConsumer =
  148. clang::serialized_diags::create(OutputFile, DiagOpts);
  149. if (Diags.ownsClient()) {
  150. Diags.setClient(new ChainedDiagnosticConsumer(
  151. Diags.takeClient(), std::move(SerializedConsumer)));
  152. } else {
  153. Diags.setClient(new ChainedDiagnosticConsumer(
  154. Diags.getClient(), std::move(SerializedConsumer)));
  155. }
  156. }
  157. void CompilerInstance::createDiagnostics(DiagnosticConsumer *Client,
  158. bool ShouldOwnClient) {
  159. Diagnostics = createDiagnostics(&getDiagnosticOpts(), Client,
  160. ShouldOwnClient, &getCodeGenOpts());
  161. }
  162. IntrusiveRefCntPtr<DiagnosticsEngine>
  163. CompilerInstance::createDiagnostics(DiagnosticOptions *Opts,
  164. DiagnosticConsumer *Client,
  165. bool ShouldOwnClient,
  166. const CodeGenOptions *CodeGenOpts) {
  167. IntrusiveRefCntPtr<DiagnosticIDs> DiagID(new DiagnosticIDs());
  168. IntrusiveRefCntPtr<DiagnosticsEngine>
  169. Diags(new DiagnosticsEngine(DiagID, Opts));
  170. // Create the diagnostic client for reporting errors or for
  171. // implementing -verify.
  172. if (Client) {
  173. Diags->setClient(Client, ShouldOwnClient);
  174. } else
  175. Diags->setClient(new TextDiagnosticPrinter(llvm::errs(), Opts));
  176. // Chain in -verify checker, if requested.
  177. if (Opts->VerifyDiagnostics)
  178. Diags->setClient(new VerifyDiagnosticConsumer(*Diags));
  179. // Chain in -diagnostic-log-file dumper, if requested.
  180. if (!Opts->DiagnosticLogFile.empty())
  181. SetUpDiagnosticLog(Opts, CodeGenOpts, *Diags);
  182. if (!Opts->DiagnosticSerializationFile.empty())
  183. SetupSerializedDiagnostics(Opts, *Diags,
  184. Opts->DiagnosticSerializationFile);
  185. // Configure our handling of diagnostics.
  186. ProcessWarningOptions(*Diags, *Opts);
  187. return Diags;
  188. }
  189. // File Manager
  190. void CompilerInstance::createFileManager() {
  191. if (!hasVirtualFileSystem()) {
  192. // TODO: choose the virtual file system based on the CompilerInvocation.
  193. setVirtualFileSystem(vfs::getRealFileSystem());
  194. }
  195. FileMgr = new FileManager(getFileSystemOpts(), VirtualFileSystem);
  196. }
  197. // Source Manager
  198. void CompilerInstance::createSourceManager(FileManager &FileMgr) {
  199. SourceMgr = new SourceManager(getDiagnostics(), FileMgr);
  200. }
  201. // Initialize the remapping of files to alternative contents, e.g.,
  202. // those specified through other files.
  203. static void InitializeFileRemapping(DiagnosticsEngine &Diags,
  204. SourceManager &SourceMgr,
  205. FileManager &FileMgr,
  206. const PreprocessorOptions &InitOpts) {
  207. // Remap files in the source manager (with buffers).
  208. for (const auto &RB : InitOpts.RemappedFileBuffers) {
  209. // Create the file entry for the file that we're mapping from.
  210. const FileEntry *FromFile =
  211. FileMgr.getVirtualFile(RB.first, RB.second->getBufferSize(), 0);
  212. if (!FromFile) {
  213. Diags.Report(diag::err_fe_remap_missing_from_file) << RB.first;
  214. if (!InitOpts.RetainRemappedFileBuffers)
  215. delete RB.second;
  216. continue;
  217. }
  218. // Override the contents of the "from" file with the contents of
  219. // the "to" file.
  220. SourceMgr.overrideFileContents(FromFile, RB.second,
  221. InitOpts.RetainRemappedFileBuffers);
  222. }
  223. // Remap files in the source manager (with other files).
  224. for (const auto &RF : InitOpts.RemappedFiles) {
  225. // Find the file that we're mapping to.
  226. const FileEntry *ToFile = FileMgr.getFile(RF.second);
  227. if (!ToFile) {
  228. Diags.Report(diag::err_fe_remap_missing_to_file) << RF.first << RF.second;
  229. continue;
  230. }
  231. // Create the file entry for the file that we're mapping from.
  232. const FileEntry *FromFile =
  233. FileMgr.getVirtualFile(RF.first, ToFile->getSize(), 0);
  234. if (!FromFile) {
  235. Diags.Report(diag::err_fe_remap_missing_from_file) << RF.first;
  236. continue;
  237. }
  238. // Override the contents of the "from" file with the contents of
  239. // the "to" file.
  240. SourceMgr.overrideFileContents(FromFile, ToFile);
  241. }
  242. SourceMgr.setOverridenFilesKeepOriginalName(
  243. InitOpts.RemappedFilesKeepOriginalName);
  244. }
  245. // Preprocessor
  246. void CompilerInstance::createPreprocessor(TranslationUnitKind TUKind) {
  247. const PreprocessorOptions &PPOpts = getPreprocessorOpts();
  248. // Create a PTH manager if we are using some form of a token cache.
  249. PTHManager *PTHMgr = nullptr;
  250. if (!PPOpts.TokenCache.empty())
  251. PTHMgr = PTHManager::Create(PPOpts.TokenCache, getDiagnostics());
  252. // Create the Preprocessor.
  253. HeaderSearch *HeaderInfo = new HeaderSearch(&getHeaderSearchOpts(),
  254. getSourceManager(),
  255. getDiagnostics(),
  256. getLangOpts(),
  257. &getTarget());
  258. PP = new Preprocessor(&getPreprocessorOpts(), getDiagnostics(), getLangOpts(),
  259. getSourceManager(), *HeaderInfo, *this, PTHMgr,
  260. /*OwnsHeaderSearch=*/true, TUKind);
  261. PP->Initialize(getTarget());
  262. // Note that this is different then passing PTHMgr to Preprocessor's ctor.
  263. // That argument is used as the IdentifierInfoLookup argument to
  264. // IdentifierTable's ctor.
  265. if (PTHMgr) {
  266. PTHMgr->setPreprocessor(&*PP);
  267. PP->setPTHManager(PTHMgr);
  268. }
  269. if (PPOpts.DetailedRecord)
  270. PP->createPreprocessingRecord();
  271. // Apply remappings to the source manager.
  272. InitializeFileRemapping(PP->getDiagnostics(), PP->getSourceManager(),
  273. PP->getFileManager(), PPOpts);
  274. // Predefine macros and configure the preprocessor.
  275. InitializePreprocessor(*PP, PPOpts, getFrontendOpts());
  276. // Initialize the header search object.
  277. ApplyHeaderSearchOptions(PP->getHeaderSearchInfo(), getHeaderSearchOpts(),
  278. PP->getLangOpts(), PP->getTargetInfo().getTriple());
  279. PP->setPreprocessedOutput(getPreprocessorOutputOpts().ShowCPP);
  280. if (PP->getLangOpts().Modules)
  281. PP->getHeaderSearchInfo().setModuleCachePath(getSpecificModuleCachePath());
  282. // Handle generating dependencies, if requested.
  283. const DependencyOutputOptions &DepOpts = getDependencyOutputOpts();
  284. if (!DepOpts.OutputFile.empty())
  285. TheDependencyFileGenerator.reset(
  286. DependencyFileGenerator::CreateAndAttachToPreprocessor(*PP, DepOpts));
  287. if (!DepOpts.DOTOutputFile.empty())
  288. AttachDependencyGraphGen(*PP, DepOpts.DOTOutputFile,
  289. getHeaderSearchOpts().Sysroot);
  290. for (auto &Listener : DependencyCollectors)
  291. Listener->attachToPreprocessor(*PP);
  292. // If we don't have a collector, but we are collecting module dependencies,
  293. // then we're the top level compiler instance and need to create one.
  294. if (!ModuleDepCollector && !DepOpts.ModuleDependencyOutputDir.empty())
  295. ModuleDepCollector = std::make_shared<ModuleDependencyCollector>(
  296. DepOpts.ModuleDependencyOutputDir);
  297. // Handle generating header include information, if requested.
  298. if (DepOpts.ShowHeaderIncludes)
  299. AttachHeaderIncludeGen(*PP);
  300. if (!DepOpts.HeaderIncludeOutputFile.empty()) {
  301. StringRef OutputPath = DepOpts.HeaderIncludeOutputFile;
  302. if (OutputPath == "-")
  303. OutputPath = "";
  304. AttachHeaderIncludeGen(*PP, /*ShowAllHeaders=*/true, OutputPath,
  305. /*ShowDepth=*/false);
  306. }
  307. if (DepOpts.PrintShowIncludes) {
  308. AttachHeaderIncludeGen(*PP, /*ShowAllHeaders=*/false, /*OutputPath=*/"",
  309. /*ShowDepth=*/true, /*MSStyle=*/true);
  310. }
  311. }
  312. std::string CompilerInstance::getSpecificModuleCachePath() {
  313. // Set up the module path, including the hash for the
  314. // module-creation options.
  315. SmallString<256> SpecificModuleCache(
  316. getHeaderSearchOpts().ModuleCachePath);
  317. if (!getHeaderSearchOpts().DisableModuleHash)
  318. llvm::sys::path::append(SpecificModuleCache,
  319. getInvocation().getModuleHash());
  320. return SpecificModuleCache.str();
  321. }
  322. // ASTContext
  323. void CompilerInstance::createASTContext() {
  324. Preprocessor &PP = getPreprocessor();
  325. Context = new ASTContext(getLangOpts(), PP.getSourceManager(),
  326. PP.getIdentifierTable(), PP.getSelectorTable(),
  327. PP.getBuiltinInfo());
  328. Context->InitBuiltinTypes(getTarget());
  329. }
  330. // ExternalASTSource
  331. void CompilerInstance::createPCHExternalASTSource(
  332. StringRef Path, bool DisablePCHValidation, bool AllowPCHWithCompilerErrors,
  333. void *DeserializationListener, bool OwnDeserializationListener) {
  334. bool Preamble = getPreprocessorOpts().PrecompiledPreambleBytes.first != 0;
  335. ModuleManager = createPCHExternalASTSource(
  336. Path, getHeaderSearchOpts().Sysroot, DisablePCHValidation,
  337. AllowPCHWithCompilerErrors, getPreprocessor(), getASTContext(),
  338. DeserializationListener, OwnDeserializationListener, Preamble,
  339. getFrontendOpts().UseGlobalModuleIndex);
  340. }
  341. IntrusiveRefCntPtr<ASTReader> CompilerInstance::createPCHExternalASTSource(
  342. StringRef Path, const std::string &Sysroot, bool DisablePCHValidation,
  343. bool AllowPCHWithCompilerErrors, Preprocessor &PP, ASTContext &Context,
  344. void *DeserializationListener, bool OwnDeserializationListener,
  345. bool Preamble, bool UseGlobalModuleIndex) {
  346. HeaderSearchOptions &HSOpts = PP.getHeaderSearchInfo().getHeaderSearchOpts();
  347. IntrusiveRefCntPtr<ASTReader> Reader(
  348. new ASTReader(PP, Context, Sysroot.empty() ? "" : Sysroot.c_str(),
  349. DisablePCHValidation, AllowPCHWithCompilerErrors,
  350. /*AllowConfigurationMismatch*/ false,
  351. HSOpts.ModulesValidateSystemHeaders, UseGlobalModuleIndex));
  352. // We need the external source to be set up before we read the AST, because
  353. // eagerly-deserialized declarations may use it.
  354. Context.setExternalSource(Reader.get());
  355. Reader->setDeserializationListener(
  356. static_cast<ASTDeserializationListener *>(DeserializationListener),
  357. /*TakeOwnership=*/OwnDeserializationListener);
  358. switch (Reader->ReadAST(Path,
  359. Preamble ? serialization::MK_Preamble
  360. : serialization::MK_PCH,
  361. SourceLocation(),
  362. ASTReader::ARR_None)) {
  363. case ASTReader::Success:
  364. // Set the predefines buffer as suggested by the PCH reader. Typically, the
  365. // predefines buffer will be empty.
  366. PP.setPredefines(Reader->getSuggestedPredefines());
  367. return Reader;
  368. case ASTReader::Failure:
  369. // Unrecoverable failure: don't even try to process the input file.
  370. break;
  371. case ASTReader::Missing:
  372. case ASTReader::OutOfDate:
  373. case ASTReader::VersionMismatch:
  374. case ASTReader::ConfigurationMismatch:
  375. case ASTReader::HadErrors:
  376. // No suitable PCH file could be found. Return an error.
  377. break;
  378. }
  379. Context.setExternalSource(nullptr);
  380. return nullptr;
  381. }
  382. // Code Completion
  383. static bool EnableCodeCompletion(Preprocessor &PP,
  384. const std::string &Filename,
  385. unsigned Line,
  386. unsigned Column) {
  387. // Tell the source manager to chop off the given file at a specific
  388. // line and column.
  389. const FileEntry *Entry = PP.getFileManager().getFile(Filename);
  390. if (!Entry) {
  391. PP.getDiagnostics().Report(diag::err_fe_invalid_code_complete_file)
  392. << Filename;
  393. return true;
  394. }
  395. // Truncate the named file at the given line/column.
  396. PP.SetCodeCompletionPoint(Entry, Line, Column);
  397. return false;
  398. }
  399. void CompilerInstance::createCodeCompletionConsumer() {
  400. const ParsedSourceLocation &Loc = getFrontendOpts().CodeCompletionAt;
  401. if (!CompletionConsumer) {
  402. setCodeCompletionConsumer(
  403. createCodeCompletionConsumer(getPreprocessor(),
  404. Loc.FileName, Loc.Line, Loc.Column,
  405. getFrontendOpts().CodeCompleteOpts,
  406. llvm::outs()));
  407. if (!CompletionConsumer)
  408. return;
  409. } else if (EnableCodeCompletion(getPreprocessor(), Loc.FileName,
  410. Loc.Line, Loc.Column)) {
  411. setCodeCompletionConsumer(nullptr);
  412. return;
  413. }
  414. if (CompletionConsumer->isOutputBinary() &&
  415. llvm::sys::ChangeStdoutToBinary()) {
  416. getPreprocessor().getDiagnostics().Report(diag::err_fe_stdout_binary);
  417. setCodeCompletionConsumer(nullptr);
  418. }
  419. }
  420. void CompilerInstance::createFrontendTimer() {
  421. FrontendTimer.reset(new llvm::Timer("Clang front-end timer"));
  422. }
  423. CodeCompleteConsumer *
  424. CompilerInstance::createCodeCompletionConsumer(Preprocessor &PP,
  425. const std::string &Filename,
  426. unsigned Line,
  427. unsigned Column,
  428. const CodeCompleteOptions &Opts,
  429. raw_ostream &OS) {
  430. if (EnableCodeCompletion(PP, Filename, Line, Column))
  431. return nullptr;
  432. // Set up the creation routine for code-completion.
  433. return new PrintingCodeCompleteConsumer(Opts, OS);
  434. }
  435. void CompilerInstance::createSema(TranslationUnitKind TUKind,
  436. CodeCompleteConsumer *CompletionConsumer) {
  437. TheSema.reset(new Sema(getPreprocessor(), getASTContext(), getASTConsumer(),
  438. TUKind, CompletionConsumer));
  439. }
  440. // Output Files
  441. void CompilerInstance::addOutputFile(OutputFile &&OutFile) {
  442. assert(OutFile.OS && "Attempt to add empty stream to output list!");
  443. OutputFiles.push_back(std::move(OutFile));
  444. }
  445. void CompilerInstance::clearOutputFiles(bool EraseFiles) {
  446. for (OutputFile &OF : OutputFiles) {
  447. // Manually close the stream before we rename it.
  448. OF.OS.reset();
  449. if (!OF.TempFilename.empty()) {
  450. if (EraseFiles) {
  451. llvm::sys::fs::remove(OF.TempFilename);
  452. } else {
  453. SmallString<128> NewOutFile(OF.Filename);
  454. // If '-working-directory' was passed, the output filename should be
  455. // relative to that.
  456. FileMgr->FixupRelativePath(NewOutFile);
  457. if (std::error_code ec =
  458. llvm::sys::fs::rename(OF.TempFilename, NewOutFile)) {
  459. getDiagnostics().Report(diag::err_unable_to_rename_temp)
  460. << OF.TempFilename << OF.Filename << ec.message();
  461. llvm::sys::fs::remove(OF.TempFilename);
  462. }
  463. }
  464. } else if (!OF.Filename.empty() && EraseFiles)
  465. llvm::sys::fs::remove(OF.Filename);
  466. }
  467. OutputFiles.clear();
  468. NonSeekStream.reset();
  469. }
  470. raw_pwrite_stream *
  471. CompilerInstance::createDefaultOutputFile(bool Binary, StringRef InFile,
  472. StringRef Extension) {
  473. return createOutputFile(getFrontendOpts().OutputFile, Binary,
  474. /*RemoveFileOnSignal=*/true, InFile, Extension,
  475. /*UseTemporary=*/true);
  476. }
  477. llvm::raw_null_ostream *CompilerInstance::createNullOutputFile() {
  478. auto OS = llvm::make_unique<llvm::raw_null_ostream>();
  479. llvm::raw_null_ostream *Ret = OS.get();
  480. addOutputFile(OutputFile("", "", std::move(OS)));
  481. return Ret;
  482. }
  483. raw_pwrite_stream *
  484. CompilerInstance::createOutputFile(StringRef OutputPath, bool Binary,
  485. bool RemoveFileOnSignal, StringRef InFile,
  486. StringRef Extension, bool UseTemporary,
  487. bool CreateMissingDirectories) {
  488. std::string OutputPathName, TempPathName;
  489. std::error_code EC;
  490. std::unique_ptr<raw_pwrite_stream> OS = createOutputFile(
  491. OutputPath, EC, Binary, RemoveFileOnSignal, InFile, Extension,
  492. UseTemporary, CreateMissingDirectories, &OutputPathName, &TempPathName);
  493. if (!OS) {
  494. getDiagnostics().Report(diag::err_fe_unable_to_open_output) << OutputPath
  495. << EC.message();
  496. return nullptr;
  497. }
  498. raw_pwrite_stream *Ret = OS.get();
  499. // Add the output file -- but don't try to remove "-", since this means we are
  500. // using stdin.
  501. addOutputFile(OutputFile((OutputPathName != "-") ? OutputPathName : "",
  502. TempPathName, std::move(OS)));
  503. return Ret;
  504. }
  505. std::unique_ptr<llvm::raw_pwrite_stream> CompilerInstance::createOutputFile(
  506. StringRef OutputPath, std::error_code &Error, bool Binary,
  507. bool RemoveFileOnSignal, StringRef InFile, StringRef Extension,
  508. bool UseTemporary, bool CreateMissingDirectories,
  509. std::string *ResultPathName, std::string *TempPathName) {
  510. assert((!CreateMissingDirectories || UseTemporary) &&
  511. "CreateMissingDirectories is only allowed when using temporary files");
  512. std::string OutFile, TempFile;
  513. if (!OutputPath.empty()) {
  514. OutFile = OutputPath;
  515. } else if (InFile == "-") {
  516. OutFile = "-";
  517. } else if (!Extension.empty()) {
  518. SmallString<128> Path(InFile);
  519. llvm::sys::path::replace_extension(Path, Extension);
  520. OutFile = Path.str();
  521. } else {
  522. OutFile = "-";
  523. }
  524. std::unique_ptr<llvm::raw_fd_ostream> OS;
  525. std::string OSFile;
  526. if (UseTemporary) {
  527. if (OutFile == "-")
  528. UseTemporary = false;
  529. else {
  530. llvm::sys::fs::file_status Status;
  531. llvm::sys::fs::status(OutputPath, Status);
  532. if (llvm::sys::fs::exists(Status)) {
  533. // Fail early if we can't write to the final destination.
  534. if (!llvm::sys::fs::can_write(OutputPath))
  535. return nullptr;
  536. // Don't use a temporary if the output is a special file. This handles
  537. // things like '-o /dev/null'
  538. if (!llvm::sys::fs::is_regular_file(Status))
  539. UseTemporary = false;
  540. }
  541. }
  542. }
  543. if (UseTemporary) {
  544. // Create a temporary file.
  545. SmallString<128> TempPath;
  546. TempPath = OutFile;
  547. TempPath += "-%%%%%%%%";
  548. int fd;
  549. std::error_code EC =
  550. llvm::sys::fs::createUniqueFile(TempPath, fd, TempPath);
  551. if (CreateMissingDirectories &&
  552. EC == llvm::errc::no_such_file_or_directory) {
  553. StringRef Parent = llvm::sys::path::parent_path(OutputPath);
  554. EC = llvm::sys::fs::create_directories(Parent);
  555. if (!EC) {
  556. EC = llvm::sys::fs::createUniqueFile(TempPath, fd, TempPath);
  557. }
  558. }
  559. if (!EC) {
  560. OS.reset(new llvm::raw_fd_ostream(fd, /*shouldClose=*/true));
  561. OSFile = TempFile = TempPath.str();
  562. }
  563. // If we failed to create the temporary, fallback to writing to the file
  564. // directly. This handles the corner case where we cannot write to the
  565. // directory, but can write to the file.
  566. }
  567. if (!OS) {
  568. OSFile = OutFile;
  569. OS.reset(new llvm::raw_fd_ostream(
  570. OSFile, Error,
  571. (Binary ? llvm::sys::fs::F_None : llvm::sys::fs::F_Text)));
  572. if (Error)
  573. return nullptr;
  574. }
  575. // Make sure the out stream file gets removed if we crash.
  576. if (RemoveFileOnSignal)
  577. llvm::sys::RemoveFileOnSignal(OSFile);
  578. if (ResultPathName)
  579. *ResultPathName = OutFile;
  580. if (TempPathName)
  581. *TempPathName = TempFile;
  582. if (!Binary || OS->supportsSeeking())
  583. return std::move(OS);
  584. auto B = llvm::make_unique<llvm::buffer_ostream>(*OS);
  585. assert(!NonSeekStream);
  586. NonSeekStream = std::move(OS);
  587. return std::move(B);
  588. }
  589. // Initialization Utilities
  590. bool CompilerInstance::InitializeSourceManager(const FrontendInputFile &Input){
  591. return InitializeSourceManager(Input, getDiagnostics(),
  592. getFileManager(), getSourceManager(),
  593. getFrontendOpts());
  594. }
  595. bool CompilerInstance::InitializeSourceManager(const FrontendInputFile &Input,
  596. DiagnosticsEngine &Diags,
  597. FileManager &FileMgr,
  598. SourceManager &SourceMgr,
  599. const FrontendOptions &Opts) {
  600. SrcMgr::CharacteristicKind
  601. Kind = Input.isSystem() ? SrcMgr::C_System : SrcMgr::C_User;
  602. if (Input.isBuffer()) {
  603. SourceMgr.setMainFileID(SourceMgr.createFileID(
  604. std::unique_ptr<llvm::MemoryBuffer>(Input.getBuffer()), Kind));
  605. assert(!SourceMgr.getMainFileID().isInvalid() &&
  606. "Couldn't establish MainFileID!");
  607. return true;
  608. }
  609. StringRef InputFile = Input.getFile();
  610. // Figure out where to get and map in the main file.
  611. if (InputFile != "-") {
  612. const FileEntry *File = FileMgr.getFile(InputFile, /*OpenFile=*/true);
  613. if (!File) {
  614. Diags.Report(diag::err_fe_error_reading) << InputFile;
  615. return false;
  616. }
  617. // The natural SourceManager infrastructure can't currently handle named
  618. // pipes, but we would at least like to accept them for the main
  619. // file. Detect them here, read them with the volatile flag so FileMgr will
  620. // pick up the correct size, and simply override their contents as we do for
  621. // STDIN.
  622. if (File->isNamedPipe()) {
  623. auto MB = FileMgr.getBufferForFile(File, /*isVolatile=*/true);
  624. if (MB) {
  625. // Create a new virtual file that will have the correct size.
  626. File = FileMgr.getVirtualFile(InputFile, (*MB)->getBufferSize(), 0);
  627. SourceMgr.overrideFileContents(File, std::move(*MB));
  628. } else {
  629. Diags.Report(diag::err_cannot_open_file) << InputFile
  630. << MB.getError().message();
  631. return false;
  632. }
  633. }
  634. SourceMgr.setMainFileID(
  635. SourceMgr.createFileID(File, SourceLocation(), Kind));
  636. } else {
  637. llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> SBOrErr =
  638. llvm::MemoryBuffer::getSTDIN();
  639. if (std::error_code EC = SBOrErr.getError()) {
  640. Diags.Report(diag::err_fe_error_reading_stdin) << EC.message();
  641. return false;
  642. }
  643. std::unique_ptr<llvm::MemoryBuffer> SB = std::move(SBOrErr.get());
  644. const FileEntry *File = FileMgr.getVirtualFile(SB->getBufferIdentifier(),
  645. SB->getBufferSize(), 0);
  646. SourceMgr.setMainFileID(
  647. SourceMgr.createFileID(File, SourceLocation(), Kind));
  648. SourceMgr.overrideFileContents(File, std::move(SB));
  649. }
  650. assert(!SourceMgr.getMainFileID().isInvalid() &&
  651. "Couldn't establish MainFileID!");
  652. return true;
  653. }
  654. // High-Level Operations
  655. bool CompilerInstance::ExecuteAction(FrontendAction &Act) {
  656. assert(hasDiagnostics() && "Diagnostics engine is not initialized!");
  657. assert(!getFrontendOpts().ShowHelp && "Client must handle '-help'!");
  658. assert(!getFrontendOpts().ShowVersion && "Client must handle '-version'!");
  659. // FIXME: Take this as an argument, once all the APIs we used have moved to
  660. // taking it as an input instead of hard-coding llvm::errs.
  661. raw_ostream &OS = llvm::errs();
  662. // Create the target instance.
  663. setTarget(TargetInfo::CreateTargetInfo(getDiagnostics(),
  664. getInvocation().TargetOpts));
  665. if (!hasTarget())
  666. return false;
  667. // Inform the target of the language options.
  668. //
  669. // FIXME: We shouldn't need to do this, the target should be immutable once
  670. // created. This complexity should be lifted elsewhere.
  671. getTarget().adjust(getLangOpts());
  672. // rewriter project will change target built-in bool type from its default.
  673. if (getFrontendOpts().ProgramAction == frontend::RewriteObjC)
  674. getTarget().noSignedCharForObjCBool();
  675. // Validate/process some options.
  676. if (getHeaderSearchOpts().Verbose)
  677. OS << "clang -cc1 version " CLANG_VERSION_STRING
  678. << " based upon " << BACKEND_PACKAGE_STRING
  679. << " default target " << llvm::sys::getDefaultTargetTriple() << "\n";
  680. if (getFrontendOpts().ShowTimers)
  681. createFrontendTimer();
  682. if (getFrontendOpts().ShowStats)
  683. llvm::EnableStatistics();
  684. for (unsigned i = 0, e = getFrontendOpts().Inputs.size(); i != e; ++i) {
  685. // Reset the ID tables if we are reusing the SourceManager and parsing
  686. // regular files.
  687. if (hasSourceManager() && !Act.isModelParsingAction())
  688. getSourceManager().clearIDTables();
  689. if (Act.BeginSourceFile(*this, getFrontendOpts().Inputs[i])) {
  690. Act.Execute();
  691. Act.EndSourceFile();
  692. }
  693. }
  694. // Notify the diagnostic client that all files were processed.
  695. getDiagnostics().getClient()->finish();
  696. if (getDiagnosticOpts().ShowCarets) {
  697. // We can have multiple diagnostics sharing one diagnostic client.
  698. // Get the total number of warnings/errors from the client.
  699. unsigned NumWarnings = getDiagnostics().getClient()->getNumWarnings();
  700. unsigned NumErrors = getDiagnostics().getClient()->getNumErrors();
  701. if (NumWarnings)
  702. OS << NumWarnings << " warning" << (NumWarnings == 1 ? "" : "s");
  703. if (NumWarnings && NumErrors)
  704. OS << " and ";
  705. if (NumErrors)
  706. OS << NumErrors << " error" << (NumErrors == 1 ? "" : "s");
  707. if (NumWarnings || NumErrors)
  708. OS << " generated.\n";
  709. }
  710. if (getFrontendOpts().ShowStats && hasFileManager()) {
  711. getFileManager().PrintStats();
  712. OS << "\n";
  713. }
  714. return !getDiagnostics().getClient()->getNumErrors();
  715. }
  716. /// \brief Determine the appropriate source input kind based on language
  717. /// options.
  718. static InputKind getSourceInputKindFromOptions(const LangOptions &LangOpts) {
  719. if (LangOpts.OpenCL)
  720. return IK_OpenCL;
  721. if (LangOpts.CUDA)
  722. return IK_CUDA;
  723. if (LangOpts.ObjC1)
  724. return LangOpts.CPlusPlus? IK_ObjCXX : IK_ObjC;
  725. return LangOpts.CPlusPlus? IK_CXX : IK_C;
  726. }
  727. /// \brief Compile a module file for the given module, using the options
  728. /// provided by the importing compiler instance. Returns true if the module
  729. /// was built without errors.
  730. static bool compileModuleImpl(CompilerInstance &ImportingInstance,
  731. SourceLocation ImportLoc,
  732. Module *Module,
  733. StringRef ModuleFileName) {
  734. ModuleMap &ModMap
  735. = ImportingInstance.getPreprocessor().getHeaderSearchInfo().getModuleMap();
  736. // Construct a compiler invocation for creating this module.
  737. IntrusiveRefCntPtr<CompilerInvocation> Invocation
  738. (new CompilerInvocation(ImportingInstance.getInvocation()));
  739. PreprocessorOptions &PPOpts = Invocation->getPreprocessorOpts();
  740. // For any options that aren't intended to affect how a module is built,
  741. // reset them to their default values.
  742. Invocation->getLangOpts()->resetNonModularOptions();
  743. PPOpts.resetNonModularOptions();
  744. // Remove any macro definitions that are explicitly ignored by the module.
  745. // They aren't supposed to affect how the module is built anyway.
  746. const HeaderSearchOptions &HSOpts = Invocation->getHeaderSearchOpts();
  747. PPOpts.Macros.erase(
  748. std::remove_if(PPOpts.Macros.begin(), PPOpts.Macros.end(),
  749. [&HSOpts](const std::pair<std::string, bool> &def) {
  750. StringRef MacroDef = def.first;
  751. return HSOpts.ModulesIgnoreMacros.count(MacroDef.split('=').first) > 0;
  752. }),
  753. PPOpts.Macros.end());
  754. // Note the name of the module we're building.
  755. Invocation->getLangOpts()->CurrentModule = Module->getTopLevelModuleName();
  756. // Make sure that the failed-module structure has been allocated in
  757. // the importing instance, and propagate the pointer to the newly-created
  758. // instance.
  759. PreprocessorOptions &ImportingPPOpts
  760. = ImportingInstance.getInvocation().getPreprocessorOpts();
  761. if (!ImportingPPOpts.FailedModules)
  762. ImportingPPOpts.FailedModules = new PreprocessorOptions::FailedModulesSet;
  763. PPOpts.FailedModules = ImportingPPOpts.FailedModules;
  764. // If there is a module map file, build the module using the module map.
  765. // Set up the inputs/outputs so that we build the module from its umbrella
  766. // header.
  767. FrontendOptions &FrontendOpts = Invocation->getFrontendOpts();
  768. FrontendOpts.OutputFile = ModuleFileName.str();
  769. FrontendOpts.DisableFree = false;
  770. FrontendOpts.GenerateGlobalModuleIndex = false;
  771. FrontendOpts.Inputs.clear();
  772. InputKind IK = getSourceInputKindFromOptions(*Invocation->getLangOpts());
  773. // Don't free the remapped file buffers; they are owned by our caller.
  774. PPOpts.RetainRemappedFileBuffers = true;
  775. Invocation->getDiagnosticOpts().VerifyDiagnostics = 0;
  776. assert(ImportingInstance.getInvocation().getModuleHash() ==
  777. Invocation->getModuleHash() && "Module hash mismatch!");
  778. // Construct a compiler instance that will be used to actually create the
  779. // module.
  780. CompilerInstance Instance(/*BuildingModule=*/true);
  781. Instance.setInvocation(&*Invocation);
  782. Instance.createDiagnostics(new ForwardingDiagnosticConsumer(
  783. ImportingInstance.getDiagnosticClient()),
  784. /*ShouldOwnClient=*/true);
  785. Instance.setVirtualFileSystem(&ImportingInstance.getVirtualFileSystem());
  786. // Note that this module is part of the module build stack, so that we
  787. // can detect cycles in the module graph.
  788. Instance.setFileManager(&ImportingInstance.getFileManager());
  789. Instance.createSourceManager(Instance.getFileManager());
  790. SourceManager &SourceMgr = Instance.getSourceManager();
  791. SourceMgr.setModuleBuildStack(
  792. ImportingInstance.getSourceManager().getModuleBuildStack());
  793. SourceMgr.pushModuleBuildStack(Module->getTopLevelModuleName(),
  794. FullSourceLoc(ImportLoc, ImportingInstance.getSourceManager()));
  795. // If we're collecting module dependencies, we need to share a collector
  796. // between all of the module CompilerInstances.
  797. Instance.setModuleDepCollector(ImportingInstance.getModuleDepCollector());
  798. // Get or create the module map that we'll use to build this module.
  799. std::string InferredModuleMapContent;
  800. if (const FileEntry *ModuleMapFile =
  801. ModMap.getContainingModuleMapFile(Module)) {
  802. // Use the module map where this module resides.
  803. FrontendOpts.Inputs.push_back(
  804. FrontendInputFile(ModuleMapFile->getName(), IK));
  805. } else {
  806. llvm::raw_string_ostream OS(InferredModuleMapContent);
  807. Module->print(OS);
  808. OS.flush();
  809. FrontendOpts.Inputs.push_back(
  810. FrontendInputFile("__inferred_module.map", IK));
  811. std::unique_ptr<llvm::MemoryBuffer> ModuleMapBuffer =
  812. llvm::MemoryBuffer::getMemBuffer(InferredModuleMapContent);
  813. ModuleMapFile = Instance.getFileManager().getVirtualFile(
  814. "__inferred_module.map", InferredModuleMapContent.size(), 0);
  815. SourceMgr.overrideFileContents(ModuleMapFile, std::move(ModuleMapBuffer));
  816. }
  817. // Construct a module-generating action. Passing through the module map is
  818. // safe because the FileManager is shared between the compiler instances.
  819. GenerateModuleAction CreateModuleAction(
  820. ModMap.getModuleMapFileForUniquing(Module), Module->IsSystem);
  821. ImportingInstance.getDiagnostics().Report(ImportLoc,
  822. diag::remark_module_build)
  823. << Module->Name << ModuleFileName;
  824. // Execute the action to actually build the module in-place. Use a separate
  825. // thread so that we get a stack large enough.
  826. const unsigned ThreadStackSize = 8 << 20;
  827. llvm::CrashRecoveryContext CRC;
  828. CRC.RunSafelyOnThread([&]() { Instance.ExecuteAction(CreateModuleAction); },
  829. ThreadStackSize);
  830. ImportingInstance.getDiagnostics().Report(ImportLoc,
  831. diag::remark_module_build_done)
  832. << Module->Name;
  833. // Delete the temporary module map file.
  834. // FIXME: Even though we're executing under crash protection, it would still
  835. // be nice to do this with RemoveFileOnSignal when we can. However, that
  836. // doesn't make sense for all clients, so clean this up manually.
  837. Instance.clearOutputFiles(/*EraseFiles=*/true);
  838. // We've rebuilt a module. If we're allowed to generate or update the global
  839. // module index, record that fact in the importing compiler instance.
  840. if (ImportingInstance.getFrontendOpts().GenerateGlobalModuleIndex) {
  841. ImportingInstance.setBuildGlobalModuleIndex(true);
  842. }
  843. return !Instance.getDiagnostics().hasErrorOccurred();
  844. }
  845. static bool compileAndLoadModule(CompilerInstance &ImportingInstance,
  846. SourceLocation ImportLoc,
  847. SourceLocation ModuleNameLoc, Module *Module,
  848. StringRef ModuleFileName) {
  849. DiagnosticsEngine &Diags = ImportingInstance.getDiagnostics();
  850. auto diagnoseBuildFailure = [&] {
  851. Diags.Report(ModuleNameLoc, diag::err_module_not_built)
  852. << Module->Name << SourceRange(ImportLoc, ModuleNameLoc);
  853. };
  854. // FIXME: have LockFileManager return an error_code so that we can
  855. // avoid the mkdir when the directory already exists.
  856. StringRef Dir = llvm::sys::path::parent_path(ModuleFileName);
  857. llvm::sys::fs::create_directories(Dir);
  858. while (1) {
  859. unsigned ModuleLoadCapabilities = ASTReader::ARR_Missing;
  860. llvm::LockFileManager Locked(ModuleFileName);
  861. switch (Locked) {
  862. case llvm::LockFileManager::LFS_Error:
  863. Diags.Report(ModuleNameLoc, diag::err_module_lock_failure)
  864. << Module->Name;
  865. return false;
  866. case llvm::LockFileManager::LFS_Owned:
  867. // We're responsible for building the module ourselves.
  868. if (!compileModuleImpl(ImportingInstance, ModuleNameLoc, Module,
  869. ModuleFileName)) {
  870. diagnoseBuildFailure();
  871. return false;
  872. }
  873. break;
  874. case llvm::LockFileManager::LFS_Shared:
  875. // Someone else is responsible for building the module. Wait for them to
  876. // finish.
  877. switch (Locked.waitForUnlock()) {
  878. case llvm::LockFileManager::Res_Success:
  879. ModuleLoadCapabilities |= ASTReader::ARR_OutOfDate;
  880. break;
  881. case llvm::LockFileManager::Res_OwnerDied:
  882. continue; // try again to get the lock.
  883. case llvm::LockFileManager::Res_Timeout:
  884. Diags.Report(ModuleNameLoc, diag::err_module_lock_timeout)
  885. << Module->Name;
  886. // Clear the lock file so that future invokations can make progress.
  887. Locked.unsafeRemoveLockFile();
  888. return false;
  889. }
  890. break;
  891. }
  892. // Try to read the module file, now that we've compiled it.
  893. ASTReader::ASTReadResult ReadResult =
  894. ImportingInstance.getModuleManager()->ReadAST(
  895. ModuleFileName, serialization::MK_ImplicitModule, ImportLoc,
  896. ModuleLoadCapabilities);
  897. if (ReadResult == ASTReader::OutOfDate &&
  898. Locked == llvm::LockFileManager::LFS_Shared) {
  899. // The module may be out of date in the presence of file system races,
  900. // or if one of its imports depends on header search paths that are not
  901. // consistent with this ImportingInstance. Try again...
  902. continue;
  903. } else if (ReadResult == ASTReader::Missing) {
  904. diagnoseBuildFailure();
  905. } else if (ReadResult != ASTReader::Success &&
  906. !Diags.hasErrorOccurred()) {
  907. // The ASTReader didn't diagnose the error, so conservatively report it.
  908. diagnoseBuildFailure();
  909. }
  910. return ReadResult == ASTReader::Success;
  911. }
  912. }
  913. /// \brief Diagnose differences between the current definition of the given
  914. /// configuration macro and the definition provided on the command line.
  915. static void checkConfigMacro(Preprocessor &PP, StringRef ConfigMacro,
  916. Module *Mod, SourceLocation ImportLoc) {
  917. IdentifierInfo *Id = PP.getIdentifierInfo(ConfigMacro);
  918. SourceManager &SourceMgr = PP.getSourceManager();
  919. // If this identifier has never had a macro definition, then it could
  920. // not have changed.
  921. if (!Id->hadMacroDefinition())
  922. return;
  923. // If this identifier does not currently have a macro definition,
  924. // check whether it had one on the command line.
  925. if (!Id->hasMacroDefinition()) {
  926. MacroDirective::DefInfo LatestDef =
  927. PP.getMacroDirectiveHistory(Id)->getDefinition();
  928. for (MacroDirective::DefInfo Def = LatestDef; Def;
  929. Def = Def.getPreviousDefinition()) {
  930. FileID FID = SourceMgr.getFileID(Def.getLocation());
  931. if (FID.isInvalid())
  932. continue;
  933. // We only care about the predefines buffer.
  934. if (FID != PP.getPredefinesFileID())
  935. continue;
  936. // This macro was defined on the command line, then #undef'd later.
  937. // Complain.
  938. PP.Diag(ImportLoc, diag::warn_module_config_macro_undef)
  939. << true << ConfigMacro << Mod->getFullModuleName();
  940. if (LatestDef.isUndefined())
  941. PP.Diag(LatestDef.getUndefLocation(), diag::note_module_def_undef_here)
  942. << true;
  943. return;
  944. }
  945. // Okay: no definition in the predefines buffer.
  946. return;
  947. }
  948. // This identifier has a macro definition. Check whether we had a definition
  949. // on the command line.
  950. MacroDirective::DefInfo LatestDef =
  951. PP.getMacroDirectiveHistory(Id)->getDefinition();
  952. MacroDirective::DefInfo PredefinedDef;
  953. for (MacroDirective::DefInfo Def = LatestDef; Def;
  954. Def = Def.getPreviousDefinition()) {
  955. FileID FID = SourceMgr.getFileID(Def.getLocation());
  956. if (FID.isInvalid())
  957. continue;
  958. // We only care about the predefines buffer.
  959. if (FID != PP.getPredefinesFileID())
  960. continue;
  961. PredefinedDef = Def;
  962. break;
  963. }
  964. // If there was no definition for this macro in the predefines buffer,
  965. // complain.
  966. if (!PredefinedDef ||
  967. (!PredefinedDef.getLocation().isValid() &&
  968. PredefinedDef.getUndefLocation().isValid())) {
  969. PP.Diag(ImportLoc, diag::warn_module_config_macro_undef)
  970. << false << ConfigMacro << Mod->getFullModuleName();
  971. PP.Diag(LatestDef.getLocation(), diag::note_module_def_undef_here)
  972. << false;
  973. return;
  974. }
  975. // If the current macro definition is the same as the predefined macro
  976. // definition, it's okay.
  977. if (LatestDef.getMacroInfo() == PredefinedDef.getMacroInfo() ||
  978. LatestDef.getMacroInfo()->isIdenticalTo(*PredefinedDef.getMacroInfo(),PP,
  979. /*Syntactically=*/true))
  980. return;
  981. // The macro definitions differ.
  982. PP.Diag(ImportLoc, diag::warn_module_config_macro_undef)
  983. << false << ConfigMacro << Mod->getFullModuleName();
  984. PP.Diag(LatestDef.getLocation(), diag::note_module_def_undef_here)
  985. << false;
  986. }
  987. /// \brief Write a new timestamp file with the given path.
  988. static void writeTimestampFile(StringRef TimestampFile) {
  989. std::error_code EC;
  990. llvm::raw_fd_ostream Out(TimestampFile.str(), EC, llvm::sys::fs::F_None);
  991. }
  992. /// \brief Prune the module cache of modules that haven't been accessed in
  993. /// a long time.
  994. static void pruneModuleCache(const HeaderSearchOptions &HSOpts) {
  995. struct stat StatBuf;
  996. llvm::SmallString<128> TimestampFile;
  997. TimestampFile = HSOpts.ModuleCachePath;
  998. llvm::sys::path::append(TimestampFile, "modules.timestamp");
  999. // Try to stat() the timestamp file.
  1000. if (::stat(TimestampFile.c_str(), &StatBuf)) {
  1001. // If the timestamp file wasn't there, create one now.
  1002. if (errno == ENOENT) {
  1003. writeTimestampFile(TimestampFile);
  1004. }
  1005. return;
  1006. }
  1007. // Check whether the time stamp is older than our pruning interval.
  1008. // If not, do nothing.
  1009. time_t TimeStampModTime = StatBuf.st_mtime;
  1010. time_t CurrentTime = time(nullptr);
  1011. if (CurrentTime - TimeStampModTime <= time_t(HSOpts.ModuleCachePruneInterval))
  1012. return;
  1013. // Write a new timestamp file so that nobody else attempts to prune.
  1014. // There is a benign race condition here, if two Clang instances happen to
  1015. // notice at the same time that the timestamp is out-of-date.
  1016. writeTimestampFile(TimestampFile);
  1017. // Walk the entire module cache, looking for unused module files and module
  1018. // indices.
  1019. std::error_code EC;
  1020. SmallString<128> ModuleCachePathNative;
  1021. llvm::sys::path::native(HSOpts.ModuleCachePath, ModuleCachePathNative);
  1022. for (llvm::sys::fs::directory_iterator Dir(ModuleCachePathNative, EC), DirEnd;
  1023. Dir != DirEnd && !EC; Dir.increment(EC)) {
  1024. // If we don't have a directory, there's nothing to look into.
  1025. if (!llvm::sys::fs::is_directory(Dir->path()))
  1026. continue;
  1027. // Walk all of the files within this directory.
  1028. for (llvm::sys::fs::directory_iterator File(Dir->path(), EC), FileEnd;
  1029. File != FileEnd && !EC; File.increment(EC)) {
  1030. // We only care about module and global module index files.
  1031. StringRef Extension = llvm::sys::path::extension(File->path());
  1032. if (Extension != ".pcm" && Extension != ".timestamp" &&
  1033. llvm::sys::path::filename(File->path()) != "modules.idx")
  1034. continue;
  1035. // Look at this file. If we can't stat it, there's nothing interesting
  1036. // there.
  1037. if (::stat(File->path().c_str(), &StatBuf))
  1038. continue;
  1039. // If the file has been used recently enough, leave it there.
  1040. time_t FileAccessTime = StatBuf.st_atime;
  1041. if (CurrentTime - FileAccessTime <=
  1042. time_t(HSOpts.ModuleCachePruneAfter)) {
  1043. continue;
  1044. }
  1045. // Remove the file.
  1046. llvm::sys::fs::remove(File->path());
  1047. // Remove the timestamp file.
  1048. std::string TimpestampFilename = File->path() + ".timestamp";
  1049. llvm::sys::fs::remove(TimpestampFilename);
  1050. }
  1051. // If we removed all of the files in the directory, remove the directory
  1052. // itself.
  1053. if (llvm::sys::fs::directory_iterator(Dir->path(), EC) ==
  1054. llvm::sys::fs::directory_iterator() && !EC)
  1055. llvm::sys::fs::remove(Dir->path());
  1056. }
  1057. }
  1058. void CompilerInstance::createModuleManager() {
  1059. if (!ModuleManager) {
  1060. if (!hasASTContext())
  1061. createASTContext();
  1062. // If we're implicitly building modules but not currently recursively
  1063. // building a module, check whether we need to prune the module cache.
  1064. if (getLangOpts().ImplicitModules &&
  1065. getSourceManager().getModuleBuildStack().empty() &&
  1066. getHeaderSearchOpts().ModuleCachePruneInterval > 0 &&
  1067. getHeaderSearchOpts().ModuleCachePruneAfter > 0) {
  1068. pruneModuleCache(getHeaderSearchOpts());
  1069. }
  1070. HeaderSearchOptions &HSOpts = getHeaderSearchOpts();
  1071. std::string Sysroot = HSOpts.Sysroot;
  1072. const PreprocessorOptions &PPOpts = getPreprocessorOpts();
  1073. ModuleManager = new ASTReader(getPreprocessor(), *Context,
  1074. Sysroot.empty() ? "" : Sysroot.c_str(),
  1075. PPOpts.DisablePCHValidation,
  1076. /*AllowASTWithCompilerErrors=*/false,
  1077. /*AllowConfigurationMismatch=*/false,
  1078. HSOpts.ModulesValidateSystemHeaders,
  1079. getFrontendOpts().UseGlobalModuleIndex);
  1080. if (hasASTConsumer()) {
  1081. ModuleManager->setDeserializationListener(
  1082. getASTConsumer().GetASTDeserializationListener());
  1083. getASTContext().setASTMutationListener(
  1084. getASTConsumer().GetASTMutationListener());
  1085. }
  1086. getASTContext().setExternalSource(ModuleManager);
  1087. if (hasSema())
  1088. ModuleManager->InitializeSema(getSema());
  1089. if (hasASTConsumer())
  1090. ModuleManager->StartTranslationUnit(&getASTConsumer());
  1091. }
  1092. }
  1093. bool CompilerInstance::loadModuleFile(StringRef FileName) {
  1094. // Helper to recursively read the module names for all modules we're adding.
  1095. // We mark these as known and redirect any attempt to load that module to
  1096. // the files we were handed.
  1097. struct ReadModuleNames : ASTReaderListener {
  1098. CompilerInstance &CI;
  1099. std::vector<StringRef> ModuleFileStack;
  1100. std::vector<StringRef> ModuleNameStack;
  1101. bool Failed;
  1102. bool TopFileIsModule;
  1103. ReadModuleNames(CompilerInstance &CI)
  1104. : CI(CI), Failed(false), TopFileIsModule(false) {}
  1105. bool needsImportVisitation() const override { return true; }
  1106. void visitImport(StringRef FileName) override {
  1107. if (!CI.ExplicitlyLoadedModuleFiles.insert(FileName).second) {
  1108. if (ModuleFileStack.size() == 0)
  1109. TopFileIsModule = true;
  1110. return;
  1111. }
  1112. ModuleFileStack.push_back(FileName);
  1113. ModuleNameStack.push_back(StringRef());
  1114. if (ASTReader::readASTFileControlBlock(FileName, CI.getFileManager(),
  1115. *this)) {
  1116. CI.getDiagnostics().Report(
  1117. SourceLocation(), CI.getFileManager().getBufferForFile(FileName)
  1118. ? diag::err_module_file_invalid
  1119. : diag::err_module_file_not_found)
  1120. << FileName;
  1121. for (int I = ModuleFileStack.size() - 2; I >= 0; --I)
  1122. CI.getDiagnostics().Report(SourceLocation(),
  1123. diag::note_module_file_imported_by)
  1124. << ModuleFileStack[I]
  1125. << !ModuleNameStack[I].empty() << ModuleNameStack[I];
  1126. Failed = true;
  1127. }
  1128. ModuleNameStack.pop_back();
  1129. ModuleFileStack.pop_back();
  1130. }
  1131. void ReadModuleName(StringRef ModuleName) override {
  1132. if (ModuleFileStack.size() == 1)
  1133. TopFileIsModule = true;
  1134. ModuleNameStack.back() = ModuleName;
  1135. auto &ModuleFile = CI.ModuleFileOverrides[ModuleName];
  1136. if (!ModuleFile.empty() &&
  1137. CI.getFileManager().getFile(ModuleFile) !=
  1138. CI.getFileManager().getFile(ModuleFileStack.back()))
  1139. CI.getDiagnostics().Report(SourceLocation(),
  1140. diag::err_conflicting_module_files)
  1141. << ModuleName << ModuleFile << ModuleFileStack.back();
  1142. ModuleFile = ModuleFileStack.back();
  1143. }
  1144. } RMN(*this);
  1145. // If we don't already have an ASTReader, create one now.
  1146. if (!ModuleManager)
  1147. createModuleManager();
  1148. // Tell the module manager about this module file.
  1149. if (getModuleManager()->getModuleManager().addKnownModuleFile(FileName)) {
  1150. getDiagnostics().Report(SourceLocation(), diag::err_module_file_not_found)
  1151. << FileName;
  1152. return false;
  1153. }
  1154. // Build our mapping of module names to module files from this file
  1155. // and its imports.
  1156. RMN.visitImport(FileName);
  1157. if (RMN.Failed)
  1158. return false;
  1159. // If we never found a module name for the top file, then it's not a module,
  1160. // it's a PCH or preamble or something.
  1161. if (!RMN.TopFileIsModule) {
  1162. getDiagnostics().Report(SourceLocation(), diag::err_module_file_not_module)
  1163. << FileName;
  1164. return false;
  1165. }
  1166. return true;
  1167. }
  1168. ModuleLoadResult
  1169. CompilerInstance::loadModule(SourceLocation ImportLoc,
  1170. ModuleIdPath Path,
  1171. Module::NameVisibilityKind Visibility,
  1172. bool IsInclusionDirective) {
  1173. // Determine what file we're searching from.
  1174. StringRef ModuleName = Path[0].first->getName();
  1175. SourceLocation ModuleNameLoc = Path[0].second;
  1176. // If we've already handled this import, just return the cached result.
  1177. // This one-element cache is important to eliminate redundant diagnostics
  1178. // when both the preprocessor and parser see the same import declaration.
  1179. if (!ImportLoc.isInvalid() && LastModuleImportLoc == ImportLoc) {
  1180. // Make the named module visible.
  1181. if (LastModuleImportResult && ModuleName != getLangOpts().CurrentModule &&
  1182. ModuleName != getLangOpts().ImplementationOfModule)
  1183. ModuleManager->makeModuleVisible(LastModuleImportResult, Visibility,
  1184. ImportLoc, /*Complain=*/false);
  1185. return LastModuleImportResult;
  1186. }
  1187. clang::Module *Module = nullptr;
  1188. // If we don't already have information on this module, load the module now.
  1189. llvm::DenseMap<const IdentifierInfo *, clang::Module *>::iterator Known
  1190. = KnownModules.find(Path[0].first);
  1191. if (Known != KnownModules.end()) {
  1192. // Retrieve the cached top-level module.
  1193. Module = Known->second;
  1194. } else if (ModuleName == getLangOpts().CurrentModule ||
  1195. ModuleName == getLangOpts().ImplementationOfModule) {
  1196. // This is the module we're building.
  1197. Module = PP->getHeaderSearchInfo().lookupModule(ModuleName);
  1198. Known = KnownModules.insert(std::make_pair(Path[0].first, Module)).first;
  1199. } else {
  1200. // Search for a module with the given name.
  1201. Module = PP->getHeaderSearchInfo().lookupModule(ModuleName);
  1202. if (!Module) {
  1203. getDiagnostics().Report(ModuleNameLoc, diag::err_module_not_found)
  1204. << ModuleName
  1205. << SourceRange(ImportLoc, ModuleNameLoc);
  1206. ModuleBuildFailed = true;
  1207. return ModuleLoadResult();
  1208. }
  1209. auto Override = ModuleFileOverrides.find(ModuleName);
  1210. bool Explicit = Override != ModuleFileOverrides.end();
  1211. if (!Explicit && !getLangOpts().ImplicitModules) {
  1212. getDiagnostics().Report(ModuleNameLoc, diag::err_module_build_disabled)
  1213. << ModuleName;
  1214. ModuleBuildFailed = true;
  1215. return ModuleLoadResult();
  1216. }
  1217. std::string ModuleFileName =
  1218. Explicit ? Override->second
  1219. : PP->getHeaderSearchInfo().getModuleFileName(Module);
  1220. // If we don't already have an ASTReader, create one now.
  1221. if (!ModuleManager)
  1222. createModuleManager();
  1223. if (TheDependencyFileGenerator)
  1224. TheDependencyFileGenerator->AttachToASTReader(*ModuleManager);
  1225. if (ModuleDepCollector)
  1226. ModuleDepCollector->attachToASTReader(*ModuleManager);
  1227. for (auto &Listener : DependencyCollectors)
  1228. Listener->attachToASTReader(*ModuleManager);
  1229. // Try to load the module file.
  1230. unsigned ARRFlags =
  1231. Explicit ? 0 : ASTReader::ARR_OutOfDate | ASTReader::ARR_Missing;
  1232. switch (ModuleManager->ReadAST(ModuleFileName,
  1233. Explicit ? serialization::MK_ExplicitModule
  1234. : serialization::MK_ImplicitModule,
  1235. ImportLoc, ARRFlags)) {
  1236. case ASTReader::Success:
  1237. break;
  1238. case ASTReader::OutOfDate:
  1239. case ASTReader::Missing: {
  1240. if (Explicit) {
  1241. // ReadAST has already complained for us.
  1242. ModuleLoader::HadFatalFailure = true;
  1243. KnownModules[Path[0].first] = nullptr;
  1244. return ModuleLoadResult();
  1245. }
  1246. // The module file is missing or out-of-date. Build it.
  1247. assert(Module && "missing module file");
  1248. // Check whether there is a cycle in the module graph.
  1249. ModuleBuildStack ModPath = getSourceManager().getModuleBuildStack();
  1250. ModuleBuildStack::iterator Pos = ModPath.begin(), PosEnd = ModPath.end();
  1251. for (; Pos != PosEnd; ++Pos) {
  1252. if (Pos->first == ModuleName)
  1253. break;
  1254. }
  1255. if (Pos != PosEnd) {
  1256. SmallString<256> CyclePath;
  1257. for (; Pos != PosEnd; ++Pos) {
  1258. CyclePath += Pos->first;
  1259. CyclePath += " -> ";
  1260. }
  1261. CyclePath += ModuleName;
  1262. getDiagnostics().Report(ModuleNameLoc, diag::err_module_cycle)
  1263. << ModuleName << CyclePath;
  1264. return ModuleLoadResult();
  1265. }
  1266. // Check whether we have already attempted to build this module (but
  1267. // failed).
  1268. if (getPreprocessorOpts().FailedModules &&
  1269. getPreprocessorOpts().FailedModules->hasAlreadyFailed(ModuleName)) {
  1270. getDiagnostics().Report(ModuleNameLoc, diag::err_module_not_built)
  1271. << ModuleName
  1272. << SourceRange(ImportLoc, ModuleNameLoc);
  1273. ModuleBuildFailed = true;
  1274. return ModuleLoadResult();
  1275. }
  1276. // Try to compile and then load the module.
  1277. if (!compileAndLoadModule(*this, ImportLoc, ModuleNameLoc, Module,
  1278. ModuleFileName)) {
  1279. assert(getDiagnostics().hasErrorOccurred() &&
  1280. "undiagnosed error in compileAndLoadModule");
  1281. if (getPreprocessorOpts().FailedModules)
  1282. getPreprocessorOpts().FailedModules->addFailed(ModuleName);
  1283. KnownModules[Path[0].first] = nullptr;
  1284. ModuleBuildFailed = true;
  1285. return ModuleLoadResult();
  1286. }
  1287. // Okay, we've rebuilt and now loaded the module.
  1288. break;
  1289. }
  1290. case ASTReader::VersionMismatch:
  1291. case ASTReader::ConfigurationMismatch:
  1292. case ASTReader::HadErrors:
  1293. ModuleLoader::HadFatalFailure = true;
  1294. // FIXME: The ASTReader will already have complained, but can we showhorn
  1295. // that diagnostic information into a more useful form?
  1296. KnownModules[Path[0].first] = nullptr;
  1297. return ModuleLoadResult();
  1298. case ASTReader::Failure:
  1299. ModuleLoader::HadFatalFailure = true;
  1300. // Already complained, but note now that we failed.
  1301. KnownModules[Path[0].first] = nullptr;
  1302. ModuleBuildFailed = true;
  1303. return ModuleLoadResult();
  1304. }
  1305. // Cache the result of this top-level module lookup for later.
  1306. Known = KnownModules.insert(std::make_pair(Path[0].first, Module)).first;
  1307. }
  1308. // If we never found the module, fail.
  1309. if (!Module)
  1310. return ModuleLoadResult();
  1311. // Verify that the rest of the module path actually corresponds to
  1312. // a submodule.
  1313. if (Path.size() > 1) {
  1314. for (unsigned I = 1, N = Path.size(); I != N; ++I) {
  1315. StringRef Name = Path[I].first->getName();
  1316. clang::Module *Sub = Module->findSubmodule(Name);
  1317. if (!Sub) {
  1318. // Attempt to perform typo correction to find a module name that works.
  1319. SmallVector<StringRef, 2> Best;
  1320. unsigned BestEditDistance = (std::numeric_limits<unsigned>::max)();
  1321. for (clang::Module::submodule_iterator J = Module->submodule_begin(),
  1322. JEnd = Module->submodule_end();
  1323. J != JEnd; ++J) {
  1324. unsigned ED = Name.edit_distance((*J)->Name,
  1325. /*AllowReplacements=*/true,
  1326. BestEditDistance);
  1327. if (ED <= BestEditDistance) {
  1328. if (ED < BestEditDistance) {
  1329. Best.clear();
  1330. BestEditDistance = ED;
  1331. }
  1332. Best.push_back((*J)->Name);
  1333. }
  1334. }
  1335. // If there was a clear winner, user it.
  1336. if (Best.size() == 1) {
  1337. getDiagnostics().Report(Path[I].second,
  1338. diag::err_no_submodule_suggest)
  1339. << Path[I].first << Module->getFullModuleName() << Best[0]
  1340. << SourceRange(Path[0].second, Path[I-1].second)
  1341. << FixItHint::CreateReplacement(SourceRange(Path[I].second),
  1342. Best[0]);
  1343. Sub = Module->findSubmodule(Best[0]);
  1344. }
  1345. }
  1346. if (!Sub) {
  1347. // No submodule by this name. Complain, and don't look for further
  1348. // submodules.
  1349. getDiagnostics().Report(Path[I].second, diag::err_no_submodule)
  1350. << Path[I].first << Module->getFullModuleName()
  1351. << SourceRange(Path[0].second, Path[I-1].second);
  1352. break;
  1353. }
  1354. Module = Sub;
  1355. }
  1356. }
  1357. // Don't make the module visible if we are in the implementation.
  1358. if (ModuleName == getLangOpts().ImplementationOfModule)
  1359. return ModuleLoadResult(Module, false);
  1360. // Make the named module visible, if it's not already part of the module
  1361. // we are parsing.
  1362. if (ModuleName != getLangOpts().CurrentModule) {
  1363. if (!Module->IsFromModuleFile) {
  1364. // We have an umbrella header or directory that doesn't actually include
  1365. // all of the headers within the directory it covers. Complain about
  1366. // this missing submodule and recover by forgetting that we ever saw
  1367. // this submodule.
  1368. // FIXME: Should we detect this at module load time? It seems fairly
  1369. // expensive (and rare).
  1370. getDiagnostics().Report(ImportLoc, diag::warn_missing_submodule)
  1371. << Module->getFullModuleName()
  1372. << SourceRange(Path.front().second, Path.back().second);
  1373. return ModuleLoadResult(nullptr, true);
  1374. }
  1375. // Check whether this module is available.
  1376. clang::Module::Requirement Requirement;
  1377. clang::Module::UnresolvedHeaderDirective MissingHeader;
  1378. if (!Module->isAvailable(getLangOpts(), getTarget(), Requirement,
  1379. MissingHeader)) {
  1380. if (MissingHeader.FileNameLoc.isValid()) {
  1381. getDiagnostics().Report(MissingHeader.FileNameLoc,
  1382. diag::err_module_header_missing)
  1383. << MissingHeader.IsUmbrella << MissingHeader.FileName;
  1384. } else {
  1385. getDiagnostics().Report(ImportLoc, diag::err_module_unavailable)
  1386. << Module->getFullModuleName()
  1387. << Requirement.second << Requirement.first
  1388. << SourceRange(Path.front().second, Path.back().second);
  1389. }
  1390. LastModuleImportLoc = ImportLoc;
  1391. LastModuleImportResult = ModuleLoadResult();
  1392. return ModuleLoadResult();
  1393. }
  1394. ModuleManager->makeModuleVisible(Module, Visibility, ImportLoc,
  1395. /*Complain=*/true);
  1396. }
  1397. // Check for any configuration macros that have changed.
  1398. clang::Module *TopModule = Module->getTopLevelModule();
  1399. for (unsigned I = 0, N = TopModule->ConfigMacros.size(); I != N; ++I) {
  1400. checkConfigMacro(getPreprocessor(), TopModule->ConfigMacros[I],
  1401. Module, ImportLoc);
  1402. }
  1403. // Determine whether we're in the #include buffer for a module. The #includes
  1404. // in that buffer do not qualify as module imports; they're just an
  1405. // implementation detail of us building the module.
  1406. bool IsInModuleIncludes = !getLangOpts().CurrentModule.empty() &&
  1407. getSourceManager().getFileID(ImportLoc) ==
  1408. getSourceManager().getMainFileID();
  1409. // If this module import was due to an inclusion directive, create an
  1410. // implicit import declaration to capture it in the AST.
  1411. if (IsInclusionDirective && hasASTContext() && !IsInModuleIncludes) {
  1412. TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl();
  1413. ImportDecl *ImportD = ImportDecl::CreateImplicit(getASTContext(), TU,
  1414. ImportLoc, Module,
  1415. Path.back().second);
  1416. TU->addDecl(ImportD);
  1417. if (Consumer)
  1418. Consumer->HandleImplicitImportDecl(ImportD);
  1419. }
  1420. LastModuleImportLoc = ImportLoc;
  1421. LastModuleImportResult = ModuleLoadResult(Module, false);
  1422. return LastModuleImportResult;
  1423. }
  1424. void CompilerInstance::makeModuleVisible(Module *Mod,
  1425. Module::NameVisibilityKind Visibility,
  1426. SourceLocation ImportLoc,
  1427. bool Complain){
  1428. ModuleManager->makeModuleVisible(Mod, Visibility, ImportLoc, Complain);
  1429. }
  1430. GlobalModuleIndex *CompilerInstance::loadGlobalModuleIndex(
  1431. SourceLocation TriggerLoc) {
  1432. if (!ModuleManager)
  1433. createModuleManager();
  1434. // Can't do anything if we don't have the module manager.
  1435. if (!ModuleManager)
  1436. return nullptr;
  1437. // Get an existing global index. This loads it if not already
  1438. // loaded.
  1439. ModuleManager->loadGlobalIndex();
  1440. GlobalModuleIndex *GlobalIndex = ModuleManager->getGlobalIndex();
  1441. // If the global index doesn't exist, create it.
  1442. if (!GlobalIndex && shouldBuildGlobalModuleIndex() && hasFileManager() &&
  1443. hasPreprocessor()) {
  1444. llvm::sys::fs::create_directories(
  1445. getPreprocessor().getHeaderSearchInfo().getModuleCachePath());
  1446. GlobalModuleIndex::writeIndex(
  1447. getFileManager(),
  1448. getPreprocessor().getHeaderSearchInfo().getModuleCachePath());
  1449. ModuleManager->resetForReload();
  1450. ModuleManager->loadGlobalIndex();
  1451. GlobalIndex = ModuleManager->getGlobalIndex();
  1452. }
  1453. // For finding modules needing to be imported for fixit messages,
  1454. // we need to make the global index cover all modules, so we do that here.
  1455. if (!HaveFullGlobalModuleIndex && GlobalIndex && !buildingModule()) {
  1456. ModuleMap &MMap = getPreprocessor().getHeaderSearchInfo().getModuleMap();
  1457. bool RecreateIndex = false;
  1458. for (ModuleMap::module_iterator I = MMap.module_begin(),
  1459. E = MMap.module_end(); I != E; ++I) {
  1460. Module *TheModule = I->second;
  1461. const FileEntry *Entry = TheModule->getASTFile();
  1462. if (!Entry) {
  1463. SmallVector<std::pair<IdentifierInfo *, SourceLocation>, 2> Path;
  1464. Path.push_back(std::make_pair(
  1465. getPreprocessor().getIdentifierInfo(TheModule->Name), TriggerLoc));
  1466. std::reverse(Path.begin(), Path.end());
  1467. // Load a module as hidden. This also adds it to the global index.
  1468. loadModule(TheModule->DefinitionLoc, Path,
  1469. Module::Hidden, false);
  1470. RecreateIndex = true;
  1471. }
  1472. }
  1473. if (RecreateIndex) {
  1474. GlobalModuleIndex::writeIndex(
  1475. getFileManager(),
  1476. getPreprocessor().getHeaderSearchInfo().getModuleCachePath());
  1477. ModuleManager->resetForReload();
  1478. ModuleManager->loadGlobalIndex();
  1479. GlobalIndex = ModuleManager->getGlobalIndex();
  1480. }
  1481. HaveFullGlobalModuleIndex = true;
  1482. }
  1483. return GlobalIndex;
  1484. }
  1485. // Check global module index for missing imports.
  1486. bool
  1487. CompilerInstance::lookupMissingImports(StringRef Name,
  1488. SourceLocation TriggerLoc) {
  1489. // Look for the symbol in non-imported modules, but only if an error
  1490. // actually occurred.
  1491. if (!buildingModule()) {
  1492. // Load global module index, or retrieve a previously loaded one.
  1493. GlobalModuleIndex *GlobalIndex = loadGlobalModuleIndex(
  1494. TriggerLoc);
  1495. // Only if we have a global index.
  1496. if (GlobalIndex) {
  1497. GlobalModuleIndex::HitSet FoundModules;
  1498. // Find the modules that reference the identifier.
  1499. // Note that this only finds top-level modules.
  1500. // We'll let diagnoseTypo find the actual declaration module.
  1501. if (GlobalIndex->lookupIdentifier(Name, FoundModules))
  1502. return true;
  1503. }
  1504. }
  1505. return false;
  1506. }
  1507. void CompilerInstance::resetAndLeakSema() { BuryPointer(takeSema()); }