CompilerInstance.cpp 74 KB

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