CompilerInstance.cpp 68 KB

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