CompilerInstance.cpp 73 KB

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