CompilerInstance.cpp 78 KB

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