CompilerInstance.cpp 73 KB

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