CompilerInstance.cpp 60 KB

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