LTOBackend.cpp 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543
  1. //===-LTOBackend.cpp - LLVM Link Time Optimizer Backend -------------------===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // This file implements the "backend" phase of LTO, i.e. it performs
  10. // optimization and code generation on a loaded module. It is generally used
  11. // internally by the LTO class but can also be used independently, for example
  12. // to implement a standalone ThinLTO backend.
  13. //
  14. //===----------------------------------------------------------------------===//
  15. #include "llvm/LTO/LTOBackend.h"
  16. #include "llvm/Analysis/AliasAnalysis.h"
  17. #include "llvm/Analysis/CGSCCPassManager.h"
  18. #include "llvm/Analysis/TargetLibraryInfo.h"
  19. #include "llvm/Analysis/TargetTransformInfo.h"
  20. #include "llvm/Bitcode/BitcodeReader.h"
  21. #include "llvm/Bitcode/BitcodeWriter.h"
  22. #include "llvm/IR/LegacyPassManager.h"
  23. #include "llvm/IR/PassManager.h"
  24. #include "llvm/IR/RemarkStreamer.h"
  25. #include "llvm/IR/Verifier.h"
  26. #include "llvm/LTO/LTO.h"
  27. #include "llvm/MC/SubtargetFeature.h"
  28. #include "llvm/Object/ModuleSymbolTable.h"
  29. #include "llvm/Passes/PassBuilder.h"
  30. #include "llvm/Support/Error.h"
  31. #include "llvm/Support/FileSystem.h"
  32. #include "llvm/Support/MemoryBuffer.h"
  33. #include "llvm/Support/Path.h"
  34. #include "llvm/Support/Program.h"
  35. #include "llvm/Support/TargetRegistry.h"
  36. #include "llvm/Support/ThreadPool.h"
  37. #include "llvm/Support/raw_ostream.h"
  38. #include "llvm/Target/TargetMachine.h"
  39. #include "llvm/Transforms/IPO.h"
  40. #include "llvm/Transforms/IPO/PassManagerBuilder.h"
  41. #include "llvm/Transforms/Scalar/LoopPassManager.h"
  42. #include "llvm/Transforms/Utils/FunctionImportUtils.h"
  43. #include "llvm/Transforms/Utils/SplitModule.h"
  44. using namespace llvm;
  45. using namespace lto;
  46. LLVM_ATTRIBUTE_NORETURN static void reportOpenError(StringRef Path, Twine Msg) {
  47. errs() << "failed to open " << Path << ": " << Msg << '\n';
  48. errs().flush();
  49. exit(1);
  50. }
  51. Error Config::addSaveTemps(std::string OutputFileName,
  52. bool UseInputModulePath) {
  53. ShouldDiscardValueNames = false;
  54. std::error_code EC;
  55. ResolutionFile = llvm::make_unique<raw_fd_ostream>(
  56. OutputFileName + "resolution.txt", EC, sys::fs::OpenFlags::OF_Text);
  57. if (EC)
  58. return errorCodeToError(EC);
  59. auto setHook = [&](std::string PathSuffix, ModuleHookFn &Hook) {
  60. // Keep track of the hook provided by the linker, which also needs to run.
  61. ModuleHookFn LinkerHook = Hook;
  62. Hook = [=](unsigned Task, const Module &M) {
  63. // If the linker's hook returned false, we need to pass that result
  64. // through.
  65. if (LinkerHook && !LinkerHook(Task, M))
  66. return false;
  67. std::string PathPrefix;
  68. // If this is the combined module (not a ThinLTO backend compile) or the
  69. // user hasn't requested using the input module's path, emit to a file
  70. // named from the provided OutputFileName with the Task ID appended.
  71. if (M.getModuleIdentifier() == "ld-temp.o" || !UseInputModulePath) {
  72. PathPrefix = OutputFileName;
  73. if (Task != (unsigned)-1)
  74. PathPrefix += utostr(Task) + ".";
  75. } else
  76. PathPrefix = M.getModuleIdentifier() + ".";
  77. std::string Path = PathPrefix + PathSuffix + ".bc";
  78. std::error_code EC;
  79. raw_fd_ostream OS(Path, EC, sys::fs::OpenFlags::OF_None);
  80. // Because -save-temps is a debugging feature, we report the error
  81. // directly and exit.
  82. if (EC)
  83. reportOpenError(Path, EC.message());
  84. WriteBitcodeToFile(M, OS, /*ShouldPreserveUseListOrder=*/false);
  85. return true;
  86. };
  87. };
  88. setHook("0.preopt", PreOptModuleHook);
  89. setHook("1.promote", PostPromoteModuleHook);
  90. setHook("2.internalize", PostInternalizeModuleHook);
  91. setHook("3.import", PostImportModuleHook);
  92. setHook("4.opt", PostOptModuleHook);
  93. setHook("5.precodegen", PreCodeGenModuleHook);
  94. CombinedIndexHook = [=](const ModuleSummaryIndex &Index) {
  95. std::string Path = OutputFileName + "index.bc";
  96. std::error_code EC;
  97. raw_fd_ostream OS(Path, EC, sys::fs::OpenFlags::OF_None);
  98. // Because -save-temps is a debugging feature, we report the error
  99. // directly and exit.
  100. if (EC)
  101. reportOpenError(Path, EC.message());
  102. WriteIndexToFile(Index, OS);
  103. Path = OutputFileName + "index.dot";
  104. raw_fd_ostream OSDot(Path, EC, sys::fs::OpenFlags::OF_None);
  105. if (EC)
  106. reportOpenError(Path, EC.message());
  107. Index.exportToDot(OSDot);
  108. return true;
  109. };
  110. return Error::success();
  111. }
  112. namespace {
  113. std::unique_ptr<TargetMachine>
  114. createTargetMachine(Config &Conf, const Target *TheTarget, Module &M) {
  115. StringRef TheTriple = M.getTargetTriple();
  116. SubtargetFeatures Features;
  117. Features.getDefaultSubtargetFeatures(Triple(TheTriple));
  118. for (const std::string &A : Conf.MAttrs)
  119. Features.AddFeature(A);
  120. Reloc::Model RelocModel;
  121. if (Conf.RelocModel)
  122. RelocModel = *Conf.RelocModel;
  123. else
  124. RelocModel =
  125. M.getPICLevel() == PICLevel::NotPIC ? Reloc::Static : Reloc::PIC_;
  126. Optional<CodeModel::Model> CodeModel;
  127. if (Conf.CodeModel)
  128. CodeModel = *Conf.CodeModel;
  129. else
  130. CodeModel = M.getCodeModel();
  131. return std::unique_ptr<TargetMachine>(TheTarget->createTargetMachine(
  132. TheTriple, Conf.CPU, Features.getString(), Conf.Options, RelocModel,
  133. CodeModel, Conf.CGOptLevel));
  134. }
  135. static void runNewPMPasses(Config &Conf, Module &Mod, TargetMachine *TM,
  136. unsigned OptLevel, bool IsThinLTO,
  137. ModuleSummaryIndex *ExportSummary,
  138. const ModuleSummaryIndex *ImportSummary) {
  139. Optional<PGOOptions> PGOOpt;
  140. if (!Conf.SampleProfile.empty())
  141. PGOOpt = PGOOptions(Conf.SampleProfile, "", Conf.ProfileRemapping,
  142. PGOOptions::SampleUse, PGOOptions::NoCSAction, true);
  143. else if (Conf.RunCSIRInstr) {
  144. PGOOpt = PGOOptions("", Conf.CSIRProfile, Conf.ProfileRemapping,
  145. PGOOptions::IRUse, PGOOptions::CSIRInstr);
  146. } else if (!Conf.CSIRProfile.empty()) {
  147. PGOOpt = PGOOptions(Conf.CSIRProfile, "", Conf.ProfileRemapping,
  148. PGOOptions::IRUse, PGOOptions::CSIRUse);
  149. }
  150. PassBuilder PB(TM, PipelineTuningOptions(), PGOOpt);
  151. AAManager AA;
  152. // Parse a custom AA pipeline if asked to.
  153. if (auto Err = PB.parseAAPipeline(AA, "default"))
  154. report_fatal_error("Error parsing default AA pipeline");
  155. LoopAnalysisManager LAM(Conf.DebugPassManager);
  156. FunctionAnalysisManager FAM(Conf.DebugPassManager);
  157. CGSCCAnalysisManager CGAM(Conf.DebugPassManager);
  158. ModuleAnalysisManager MAM(Conf.DebugPassManager);
  159. // Register the AA manager first so that our version is the one used.
  160. FAM.registerPass([&] { return std::move(AA); });
  161. // Register all the basic analyses with the managers.
  162. PB.registerModuleAnalyses(MAM);
  163. PB.registerCGSCCAnalyses(CGAM);
  164. PB.registerFunctionAnalyses(FAM);
  165. PB.registerLoopAnalyses(LAM);
  166. PB.crossRegisterProxies(LAM, FAM, CGAM, MAM);
  167. ModulePassManager MPM(Conf.DebugPassManager);
  168. // FIXME (davide): verify the input.
  169. PassBuilder::OptimizationLevel OL;
  170. switch (OptLevel) {
  171. default:
  172. llvm_unreachable("Invalid optimization level");
  173. case 0:
  174. OL = PassBuilder::O0;
  175. break;
  176. case 1:
  177. OL = PassBuilder::O1;
  178. break;
  179. case 2:
  180. OL = PassBuilder::O2;
  181. break;
  182. case 3:
  183. OL = PassBuilder::O3;
  184. break;
  185. }
  186. if (IsThinLTO)
  187. MPM = PB.buildThinLTODefaultPipeline(OL, Conf.DebugPassManager,
  188. ImportSummary);
  189. else
  190. MPM = PB.buildLTODefaultPipeline(OL, Conf.DebugPassManager, ExportSummary);
  191. MPM.run(Mod, MAM);
  192. // FIXME (davide): verify the output.
  193. }
  194. static void runNewPMCustomPasses(Module &Mod, TargetMachine *TM,
  195. std::string PipelineDesc,
  196. std::string AAPipelineDesc,
  197. bool DisableVerify) {
  198. PassBuilder PB(TM);
  199. AAManager AA;
  200. // Parse a custom AA pipeline if asked to.
  201. if (!AAPipelineDesc.empty())
  202. if (auto Err = PB.parseAAPipeline(AA, AAPipelineDesc))
  203. report_fatal_error("unable to parse AA pipeline description '" +
  204. AAPipelineDesc + "': " + toString(std::move(Err)));
  205. LoopAnalysisManager LAM;
  206. FunctionAnalysisManager FAM;
  207. CGSCCAnalysisManager CGAM;
  208. ModuleAnalysisManager MAM;
  209. // Register the AA manager first so that our version is the one used.
  210. FAM.registerPass([&] { return std::move(AA); });
  211. // Register all the basic analyses with the managers.
  212. PB.registerModuleAnalyses(MAM);
  213. PB.registerCGSCCAnalyses(CGAM);
  214. PB.registerFunctionAnalyses(FAM);
  215. PB.registerLoopAnalyses(LAM);
  216. PB.crossRegisterProxies(LAM, FAM, CGAM, MAM);
  217. ModulePassManager MPM;
  218. // Always verify the input.
  219. MPM.addPass(VerifierPass());
  220. // Now, add all the passes we've been requested to.
  221. if (auto Err = PB.parsePassPipeline(MPM, PipelineDesc))
  222. report_fatal_error("unable to parse pass pipeline description '" +
  223. PipelineDesc + "': " + toString(std::move(Err)));
  224. if (!DisableVerify)
  225. MPM.addPass(VerifierPass());
  226. MPM.run(Mod, MAM);
  227. }
  228. static void runOldPMPasses(Config &Conf, Module &Mod, TargetMachine *TM,
  229. bool IsThinLTO, ModuleSummaryIndex *ExportSummary,
  230. const ModuleSummaryIndex *ImportSummary) {
  231. legacy::PassManager passes;
  232. passes.add(createTargetTransformInfoWrapperPass(TM->getTargetIRAnalysis()));
  233. PassManagerBuilder PMB;
  234. PMB.LibraryInfo = new TargetLibraryInfoImpl(Triple(TM->getTargetTriple()));
  235. PMB.Inliner = createFunctionInliningPass();
  236. PMB.ExportSummary = ExportSummary;
  237. PMB.ImportSummary = ImportSummary;
  238. // Unconditionally verify input since it is not verified before this
  239. // point and has unknown origin.
  240. PMB.VerifyInput = true;
  241. PMB.VerifyOutput = !Conf.DisableVerify;
  242. PMB.LoopVectorize = true;
  243. PMB.SLPVectorize = true;
  244. PMB.OptLevel = Conf.OptLevel;
  245. PMB.PGOSampleUse = Conf.SampleProfile;
  246. PMB.EnablePGOCSInstrGen = Conf.RunCSIRInstr;
  247. if (!Conf.RunCSIRInstr && !Conf.CSIRProfile.empty()) {
  248. PMB.EnablePGOCSInstrUse = true;
  249. PMB.PGOInstrUse = Conf.CSIRProfile;
  250. }
  251. if (IsThinLTO)
  252. PMB.populateThinLTOPassManager(passes);
  253. else
  254. PMB.populateLTOPassManager(passes);
  255. passes.run(Mod);
  256. }
  257. bool opt(Config &Conf, TargetMachine *TM, unsigned Task, Module &Mod,
  258. bool IsThinLTO, ModuleSummaryIndex *ExportSummary,
  259. const ModuleSummaryIndex *ImportSummary) {
  260. // FIXME: Plumb the combined index into the new pass manager.
  261. if (!Conf.OptPipeline.empty())
  262. runNewPMCustomPasses(Mod, TM, Conf.OptPipeline, Conf.AAPipeline,
  263. Conf.DisableVerify);
  264. else if (Conf.UseNewPM)
  265. runNewPMPasses(Conf, Mod, TM, Conf.OptLevel, IsThinLTO, ExportSummary,
  266. ImportSummary);
  267. else
  268. runOldPMPasses(Conf, Mod, TM, IsThinLTO, ExportSummary, ImportSummary);
  269. return !Conf.PostOptModuleHook || Conf.PostOptModuleHook(Task, Mod);
  270. }
  271. void codegen(Config &Conf, TargetMachine *TM, AddStreamFn AddStream,
  272. unsigned Task, Module &Mod) {
  273. if (Conf.PreCodeGenModuleHook && !Conf.PreCodeGenModuleHook(Task, Mod))
  274. return;
  275. std::unique_ptr<ToolOutputFile> DwoOut;
  276. SmallString<1024> DwoFile(Conf.SplitDwarfOutput);
  277. if (!Conf.DwoDir.empty()) {
  278. std::error_code EC;
  279. if (auto EC = llvm::sys::fs::create_directories(Conf.DwoDir))
  280. report_fatal_error("Failed to create directory " + Conf.DwoDir + ": " +
  281. EC.message());
  282. DwoFile = Conf.DwoDir;
  283. sys::path::append(DwoFile, std::to_string(Task) + ".dwo");
  284. TM->Options.MCOptions.SplitDwarfFile = DwoFile.str().str();
  285. } else
  286. TM->Options.MCOptions.SplitDwarfFile = Conf.SplitDwarfFile;
  287. if (!DwoFile.empty()) {
  288. std::error_code EC;
  289. DwoOut = llvm::make_unique<ToolOutputFile>(DwoFile, EC, sys::fs::OF_None);
  290. if (EC)
  291. report_fatal_error("Failed to open " + DwoFile + ": " + EC.message());
  292. }
  293. auto Stream = AddStream(Task);
  294. legacy::PassManager CodeGenPasses;
  295. if (TM->addPassesToEmitFile(CodeGenPasses, *Stream->OS,
  296. DwoOut ? &DwoOut->os() : nullptr,
  297. Conf.CGFileType))
  298. report_fatal_error("Failed to setup codegen");
  299. CodeGenPasses.run(Mod);
  300. if (DwoOut)
  301. DwoOut->keep();
  302. }
  303. void splitCodeGen(Config &C, TargetMachine *TM, AddStreamFn AddStream,
  304. unsigned ParallelCodeGenParallelismLevel,
  305. std::unique_ptr<Module> Mod) {
  306. ThreadPool CodegenThreadPool(ParallelCodeGenParallelismLevel);
  307. unsigned ThreadCount = 0;
  308. const Target *T = &TM->getTarget();
  309. SplitModule(
  310. std::move(Mod), ParallelCodeGenParallelismLevel,
  311. [&](std::unique_ptr<Module> MPart) {
  312. // We want to clone the module in a new context to multi-thread the
  313. // codegen. We do it by serializing partition modules to bitcode
  314. // (while still on the main thread, in order to avoid data races) and
  315. // spinning up new threads which deserialize the partitions into
  316. // separate contexts.
  317. // FIXME: Provide a more direct way to do this in LLVM.
  318. SmallString<0> BC;
  319. raw_svector_ostream BCOS(BC);
  320. WriteBitcodeToFile(*MPart, BCOS);
  321. // Enqueue the task
  322. CodegenThreadPool.async(
  323. [&](const SmallString<0> &BC, unsigned ThreadId) {
  324. LTOLLVMContext Ctx(C);
  325. Expected<std::unique_ptr<Module>> MOrErr = parseBitcodeFile(
  326. MemoryBufferRef(StringRef(BC.data(), BC.size()), "ld-temp.o"),
  327. Ctx);
  328. if (!MOrErr)
  329. report_fatal_error("Failed to read bitcode");
  330. std::unique_ptr<Module> MPartInCtx = std::move(MOrErr.get());
  331. std::unique_ptr<TargetMachine> TM =
  332. createTargetMachine(C, T, *MPartInCtx);
  333. codegen(C, TM.get(), AddStream, ThreadId, *MPartInCtx);
  334. },
  335. // Pass BC using std::move to ensure that it get moved rather than
  336. // copied into the thread's context.
  337. std::move(BC), ThreadCount++);
  338. },
  339. false);
  340. // Because the inner lambda (which runs in a worker thread) captures our local
  341. // variables, we need to wait for the worker threads to terminate before we
  342. // can leave the function scope.
  343. CodegenThreadPool.wait();
  344. }
  345. Expected<const Target *> initAndLookupTarget(Config &C, Module &Mod) {
  346. if (!C.OverrideTriple.empty())
  347. Mod.setTargetTriple(C.OverrideTriple);
  348. else if (Mod.getTargetTriple().empty())
  349. Mod.setTargetTriple(C.DefaultTriple);
  350. std::string Msg;
  351. const Target *T = TargetRegistry::lookupTarget(Mod.getTargetTriple(), Msg);
  352. if (!T)
  353. return make_error<StringError>(Msg, inconvertibleErrorCode());
  354. return T;
  355. }
  356. }
  357. static Error
  358. finalizeOptimizationRemarks(std::unique_ptr<ToolOutputFile> DiagOutputFile) {
  359. // Make sure we flush the diagnostic remarks file in case the linker doesn't
  360. // call the global destructors before exiting.
  361. if (!DiagOutputFile)
  362. return Error::success();
  363. DiagOutputFile->keep();
  364. DiagOutputFile->os().flush();
  365. return Error::success();
  366. }
  367. Error lto::backend(Config &C, AddStreamFn AddStream,
  368. unsigned ParallelCodeGenParallelismLevel,
  369. std::unique_ptr<Module> Mod,
  370. ModuleSummaryIndex &CombinedIndex) {
  371. Expected<const Target *> TOrErr = initAndLookupTarget(C, *Mod);
  372. if (!TOrErr)
  373. return TOrErr.takeError();
  374. std::unique_ptr<TargetMachine> TM = createTargetMachine(C, *TOrErr, *Mod);
  375. // Setup optimization remarks.
  376. auto DiagFileOrErr = lto::setupOptimizationRemarks(
  377. Mod->getContext(), C.RemarksFilename, C.RemarksPasses, C.RemarksFormat,
  378. C.RemarksWithHotness);
  379. if (!DiagFileOrErr)
  380. return DiagFileOrErr.takeError();
  381. auto DiagnosticOutputFile = std::move(*DiagFileOrErr);
  382. if (!C.CodeGenOnly) {
  383. if (!opt(C, TM.get(), 0, *Mod, /*IsThinLTO=*/false,
  384. /*ExportSummary=*/&CombinedIndex, /*ImportSummary=*/nullptr))
  385. return finalizeOptimizationRemarks(std::move(DiagnosticOutputFile));
  386. }
  387. if (ParallelCodeGenParallelismLevel == 1) {
  388. codegen(C, TM.get(), AddStream, 0, *Mod);
  389. } else {
  390. splitCodeGen(C, TM.get(), AddStream, ParallelCodeGenParallelismLevel,
  391. std::move(Mod));
  392. }
  393. return finalizeOptimizationRemarks(std::move(DiagnosticOutputFile));
  394. }
  395. static void dropDeadSymbols(Module &Mod, const GVSummaryMapTy &DefinedGlobals,
  396. const ModuleSummaryIndex &Index) {
  397. std::vector<GlobalValue*> DeadGVs;
  398. for (auto &GV : Mod.global_values())
  399. if (GlobalValueSummary *GVS = DefinedGlobals.lookup(GV.getGUID()))
  400. if (!Index.isGlobalValueLive(GVS)) {
  401. DeadGVs.push_back(&GV);
  402. convertToDeclaration(GV);
  403. }
  404. // Now that all dead bodies have been dropped, delete the actual objects
  405. // themselves when possible.
  406. for (GlobalValue *GV : DeadGVs) {
  407. GV->removeDeadConstantUsers();
  408. // Might reference something defined in native object (i.e. dropped a
  409. // non-prevailing IR def, but we need to keep the declaration).
  410. if (GV->use_empty())
  411. GV->eraseFromParent();
  412. }
  413. }
  414. Error lto::thinBackend(Config &Conf, unsigned Task, AddStreamFn AddStream,
  415. Module &Mod, const ModuleSummaryIndex &CombinedIndex,
  416. const FunctionImporter::ImportMapTy &ImportList,
  417. const GVSummaryMapTy &DefinedGlobals,
  418. MapVector<StringRef, BitcodeModule> &ModuleMap) {
  419. Expected<const Target *> TOrErr = initAndLookupTarget(Conf, Mod);
  420. if (!TOrErr)
  421. return TOrErr.takeError();
  422. std::unique_ptr<TargetMachine> TM = createTargetMachine(Conf, *TOrErr, Mod);
  423. // Setup optimization remarks.
  424. auto DiagFileOrErr = lto::setupOptimizationRemarks(
  425. Mod.getContext(), Conf.RemarksFilename, Conf.RemarksPasses,
  426. Conf.RemarksFormat, Conf.RemarksWithHotness, Task);
  427. if (!DiagFileOrErr)
  428. return DiagFileOrErr.takeError();
  429. auto DiagnosticOutputFile = std::move(*DiagFileOrErr);
  430. if (Conf.CodeGenOnly) {
  431. codegen(Conf, TM.get(), AddStream, Task, Mod);
  432. return finalizeOptimizationRemarks(std::move(DiagnosticOutputFile));
  433. }
  434. if (Conf.PreOptModuleHook && !Conf.PreOptModuleHook(Task, Mod))
  435. return finalizeOptimizationRemarks(std::move(DiagnosticOutputFile));
  436. renameModuleForThinLTO(Mod, CombinedIndex);
  437. dropDeadSymbols(Mod, DefinedGlobals, CombinedIndex);
  438. thinLTOResolvePrevailingInModule(Mod, DefinedGlobals);
  439. if (Conf.PostPromoteModuleHook && !Conf.PostPromoteModuleHook(Task, Mod))
  440. return finalizeOptimizationRemarks(std::move(DiagnosticOutputFile));
  441. if (!DefinedGlobals.empty())
  442. thinLTOInternalizeModule(Mod, DefinedGlobals);
  443. if (Conf.PostInternalizeModuleHook &&
  444. !Conf.PostInternalizeModuleHook(Task, Mod))
  445. return finalizeOptimizationRemarks(std::move(DiagnosticOutputFile));
  446. auto ModuleLoader = [&](StringRef Identifier) {
  447. assert(Mod.getContext().isODRUniquingDebugTypes() &&
  448. "ODR Type uniquing should be enabled on the context");
  449. auto I = ModuleMap.find(Identifier);
  450. assert(I != ModuleMap.end());
  451. return I->second.getLazyModule(Mod.getContext(),
  452. /*ShouldLazyLoadMetadata=*/true,
  453. /*IsImporting*/ true);
  454. };
  455. FunctionImporter Importer(CombinedIndex, ModuleLoader);
  456. if (Error Err = Importer.importFunctions(Mod, ImportList).takeError())
  457. return Err;
  458. if (Conf.PostImportModuleHook && !Conf.PostImportModuleHook(Task, Mod))
  459. return finalizeOptimizationRemarks(std::move(DiagnosticOutputFile));
  460. if (!opt(Conf, TM.get(), Task, Mod, /*IsThinLTO=*/true,
  461. /*ExportSummary=*/nullptr, /*ImportSummary=*/&CombinedIndex))
  462. return finalizeOptimizationRemarks(std::move(DiagnosticOutputFile));
  463. codegen(Conf, TM.get(), AddStream, Task, Mod);
  464. return finalizeOptimizationRemarks(std::move(DiagnosticOutputFile));
  465. }