LTOBackend.cpp 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746
  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/ModuleSummaryAnalysis.h"
  19. #include "llvm/Analysis/TargetLibraryInfo.h"
  20. #include "llvm/Analysis/TargetTransformInfo.h"
  21. #include "llvm/Bitcode/BitcodeReader.h"
  22. #include "llvm/Bitcode/BitcodeWriter.h"
  23. #include "llvm/IR/LLVMRemarkStreamer.h"
  24. #include "llvm/IR/LegacyPassManager.h"
  25. #include "llvm/IR/PassManager.h"
  26. #include "llvm/IR/Verifier.h"
  27. #include "llvm/LTO/LTO.h"
  28. #include "llvm/MC/SubtargetFeature.h"
  29. #include "llvm/Object/ModuleSymbolTable.h"
  30. #include "llvm/Passes/PassBuilder.h"
  31. #include "llvm/Passes/PassPlugin.h"
  32. #include "llvm/Passes/StandardInstrumentations.h"
  33. #include "llvm/Support/Error.h"
  34. #include "llvm/Support/FileSystem.h"
  35. #include "llvm/Support/MemoryBuffer.h"
  36. #include "llvm/Support/Path.h"
  37. #include "llvm/Support/Program.h"
  38. #include "llvm/Support/SmallVectorMemoryBuffer.h"
  39. #include "llvm/Support/TargetRegistry.h"
  40. #include "llvm/Support/ThreadPool.h"
  41. #include "llvm/Support/raw_ostream.h"
  42. #include "llvm/Target/TargetMachine.h"
  43. #include "llvm/Transforms/IPO.h"
  44. #include "llvm/Transforms/IPO/PassManagerBuilder.h"
  45. #include "llvm/Transforms/Scalar/LoopPassManager.h"
  46. #include "llvm/Transforms/Utils/FunctionImportUtils.h"
  47. #include "llvm/Transforms/Utils/SplitModule.h"
  48. using namespace llvm;
  49. using namespace lto;
  50. #define DEBUG_TYPE "lto-backend"
  51. enum class LTOBitcodeEmbedding {
  52. DoNotEmbed = 0,
  53. EmbedOptimized = 1,
  54. EmbedPostMergePreOptimized = 2
  55. };
  56. static cl::opt<LTOBitcodeEmbedding> EmbedBitcode(
  57. "lto-embed-bitcode", cl::init(LTOBitcodeEmbedding::DoNotEmbed),
  58. cl::values(clEnumValN(LTOBitcodeEmbedding::DoNotEmbed, "none",
  59. "Do not embed"),
  60. clEnumValN(LTOBitcodeEmbedding::EmbedOptimized, "optimized",
  61. "Embed after all optimization passes"),
  62. clEnumValN(LTOBitcodeEmbedding::EmbedPostMergePreOptimized,
  63. "post-merge-pre-opt",
  64. "Embed post merge, but before optimizations")),
  65. cl::desc("Embed LLVM bitcode in object files produced by LTO"));
  66. static cl::opt<bool> ThinLTOAssumeMerged(
  67. "thinlto-assume-merged", cl::init(false),
  68. cl::desc("Assume the input has already undergone ThinLTO function "
  69. "importing and the other pre-optimization pipeline changes."));
  70. LLVM_ATTRIBUTE_NORETURN static void reportOpenError(StringRef Path, Twine Msg) {
  71. errs() << "failed to open " << Path << ": " << Msg << '\n';
  72. errs().flush();
  73. exit(1);
  74. }
  75. Error Config::addSaveTemps(std::string OutputFileName,
  76. bool UseInputModulePath) {
  77. ShouldDiscardValueNames = false;
  78. std::error_code EC;
  79. ResolutionFile = std::make_unique<raw_fd_ostream>(
  80. OutputFileName + "resolution.txt", EC, sys::fs::OpenFlags::OF_Text);
  81. if (EC) {
  82. ResolutionFile.reset();
  83. return errorCodeToError(EC);
  84. }
  85. auto setHook = [&](std::string PathSuffix, ModuleHookFn &Hook) {
  86. // Keep track of the hook provided by the linker, which also needs to run.
  87. ModuleHookFn LinkerHook = Hook;
  88. Hook = [=](unsigned Task, const Module &M) {
  89. // If the linker's hook returned false, we need to pass that result
  90. // through.
  91. if (LinkerHook && !LinkerHook(Task, M))
  92. return false;
  93. std::string PathPrefix;
  94. // If this is the combined module (not a ThinLTO backend compile) or the
  95. // user hasn't requested using the input module's path, emit to a file
  96. // named from the provided OutputFileName with the Task ID appended.
  97. if (M.getModuleIdentifier() == "ld-temp.o" || !UseInputModulePath) {
  98. PathPrefix = OutputFileName;
  99. if (Task != (unsigned)-1)
  100. PathPrefix += utostr(Task) + ".";
  101. } else
  102. PathPrefix = M.getModuleIdentifier() + ".";
  103. std::string Path = PathPrefix + PathSuffix + ".bc";
  104. std::error_code EC;
  105. raw_fd_ostream OS(Path, EC, sys::fs::OpenFlags::OF_None);
  106. // Because -save-temps is a debugging feature, we report the error
  107. // directly and exit.
  108. if (EC)
  109. reportOpenError(Path, EC.message());
  110. WriteBitcodeToFile(M, OS, /*ShouldPreserveUseListOrder=*/false);
  111. return true;
  112. };
  113. };
  114. setHook("0.preopt", PreOptModuleHook);
  115. setHook("1.promote", PostPromoteModuleHook);
  116. setHook("2.internalize", PostInternalizeModuleHook);
  117. setHook("3.import", PostImportModuleHook);
  118. setHook("4.opt", PostOptModuleHook);
  119. setHook("5.precodegen", PreCodeGenModuleHook);
  120. CombinedIndexHook =
  121. [=](const ModuleSummaryIndex &Index,
  122. const DenseSet<GlobalValue::GUID> &GUIDPreservedSymbols) {
  123. std::string Path = OutputFileName + "index.bc";
  124. std::error_code EC;
  125. raw_fd_ostream OS(Path, EC, sys::fs::OpenFlags::OF_None);
  126. // Because -save-temps is a debugging feature, we report the error
  127. // directly and exit.
  128. if (EC)
  129. reportOpenError(Path, EC.message());
  130. WriteIndexToFile(Index, OS);
  131. Path = OutputFileName + "index.dot";
  132. raw_fd_ostream OSDot(Path, EC, sys::fs::OpenFlags::OF_None);
  133. if (EC)
  134. reportOpenError(Path, EC.message());
  135. Index.exportToDot(OSDot, GUIDPreservedSymbols);
  136. return true;
  137. };
  138. return Error::success();
  139. }
  140. #define HANDLE_EXTENSION(Ext) \
  141. llvm::PassPluginLibraryInfo get##Ext##PluginInfo();
  142. #include "llvm/Support/Extension.def"
  143. static void RegisterPassPlugins(ArrayRef<std::string> PassPlugins,
  144. PassBuilder &PB) {
  145. #define HANDLE_EXTENSION(Ext) \
  146. get##Ext##PluginInfo().RegisterPassBuilderCallbacks(PB);
  147. #include "llvm/Support/Extension.def"
  148. // Load requested pass plugins and let them register pass builder callbacks
  149. for (auto &PluginFN : PassPlugins) {
  150. auto PassPlugin = PassPlugin::Load(PluginFN);
  151. if (!PassPlugin) {
  152. errs() << "Failed to load passes from '" << PluginFN
  153. << "'. Request ignored.\n";
  154. continue;
  155. }
  156. PassPlugin->registerPassBuilderCallbacks(PB);
  157. }
  158. }
  159. static std::unique_ptr<TargetMachine>
  160. createTargetMachine(const Config &Conf, const Target *TheTarget, Module &M) {
  161. StringRef TheTriple = M.getTargetTriple();
  162. SubtargetFeatures Features;
  163. Features.getDefaultSubtargetFeatures(Triple(TheTriple));
  164. for (const std::string &A : Conf.MAttrs)
  165. Features.AddFeature(A);
  166. Reloc::Model RelocModel;
  167. if (Conf.RelocModel)
  168. RelocModel = *Conf.RelocModel;
  169. else
  170. RelocModel =
  171. M.getPICLevel() == PICLevel::NotPIC ? Reloc::Static : Reloc::PIC_;
  172. Optional<CodeModel::Model> CodeModel;
  173. if (Conf.CodeModel)
  174. CodeModel = *Conf.CodeModel;
  175. else
  176. CodeModel = M.getCodeModel();
  177. std::unique_ptr<TargetMachine> TM(TheTarget->createTargetMachine(
  178. TheTriple, Conf.CPU, Features.getString(), Conf.Options, RelocModel,
  179. CodeModel, Conf.CGOptLevel));
  180. assert(TM && "Failed to create target machine");
  181. return TM;
  182. }
  183. static void runNewPMPasses(const Config &Conf, Module &Mod, TargetMachine *TM,
  184. unsigned OptLevel, bool IsThinLTO,
  185. ModuleSummaryIndex *ExportSummary,
  186. const ModuleSummaryIndex *ImportSummary) {
  187. Optional<PGOOptions> PGOOpt;
  188. if (!Conf.SampleProfile.empty())
  189. PGOOpt = PGOOptions(Conf.SampleProfile, "", Conf.ProfileRemapping,
  190. PGOOptions::SampleUse, PGOOptions::NoCSAction, true);
  191. else if (Conf.RunCSIRInstr) {
  192. PGOOpt = PGOOptions("", Conf.CSIRProfile, Conf.ProfileRemapping,
  193. PGOOptions::IRUse, PGOOptions::CSIRInstr);
  194. } else if (!Conf.CSIRProfile.empty()) {
  195. PGOOpt = PGOOptions(Conf.CSIRProfile, "", Conf.ProfileRemapping,
  196. PGOOptions::IRUse, PGOOptions::CSIRUse);
  197. }
  198. PassInstrumentationCallbacks PIC;
  199. StandardInstrumentations SI(Conf.DebugPassManager);
  200. SI.registerCallbacks(PIC);
  201. PassBuilder PB(Conf.DebugPassManager, TM, Conf.PTO, PGOOpt, &PIC);
  202. AAManager AA;
  203. // Parse a custom AA pipeline if asked to.
  204. if (auto Err = PB.parseAAPipeline(AA, "default"))
  205. report_fatal_error("Error parsing default AA pipeline");
  206. RegisterPassPlugins(Conf.PassPlugins, PB);
  207. LoopAnalysisManager LAM(Conf.DebugPassManager);
  208. FunctionAnalysisManager FAM(Conf.DebugPassManager);
  209. CGSCCAnalysisManager CGAM(Conf.DebugPassManager);
  210. ModuleAnalysisManager MAM(Conf.DebugPassManager);
  211. std::unique_ptr<TargetLibraryInfoImpl> TLII(
  212. new TargetLibraryInfoImpl(Triple(TM->getTargetTriple())));
  213. if (Conf.Freestanding)
  214. TLII->disableAllFunctions();
  215. FAM.registerPass([&] { return TargetLibraryAnalysis(*TLII); });
  216. // Register the AA manager first so that our version is the one used.
  217. FAM.registerPass([&] { return std::move(AA); });
  218. // Register all the basic analyses with the managers.
  219. PB.registerModuleAnalyses(MAM);
  220. PB.registerCGSCCAnalyses(CGAM);
  221. PB.registerFunctionAnalyses(FAM);
  222. PB.registerLoopAnalyses(LAM);
  223. PB.crossRegisterProxies(LAM, FAM, CGAM, MAM);
  224. ModulePassManager MPM(Conf.DebugPassManager);
  225. if (!Conf.DisableVerify)
  226. MPM.addPass(VerifierPass());
  227. PassBuilder::OptimizationLevel OL;
  228. switch (OptLevel) {
  229. default:
  230. llvm_unreachable("Invalid optimization level");
  231. case 0:
  232. OL = PassBuilder::OptimizationLevel::O0;
  233. break;
  234. case 1:
  235. OL = PassBuilder::OptimizationLevel::O1;
  236. break;
  237. case 2:
  238. OL = PassBuilder::OptimizationLevel::O2;
  239. break;
  240. case 3:
  241. OL = PassBuilder::OptimizationLevel::O3;
  242. break;
  243. }
  244. if (IsThinLTO)
  245. MPM.addPass(PB.buildThinLTODefaultPipeline(OL, ImportSummary));
  246. else
  247. MPM.addPass(PB.buildLTODefaultPipeline(OL, ExportSummary));
  248. if (!Conf.DisableVerify)
  249. MPM.addPass(VerifierPass());
  250. MPM.run(Mod, MAM);
  251. }
  252. static void runNewPMCustomPasses(const Config &Conf, Module &Mod,
  253. TargetMachine *TM, std::string PipelineDesc,
  254. std::string AAPipelineDesc,
  255. bool DisableVerify) {
  256. PassBuilder PB(Conf.DebugPassManager, TM);
  257. AAManager AA;
  258. // Parse a custom AA pipeline if asked to.
  259. if (!AAPipelineDesc.empty())
  260. if (auto Err = PB.parseAAPipeline(AA, AAPipelineDesc))
  261. report_fatal_error("unable to parse AA pipeline description '" +
  262. AAPipelineDesc + "': " + toString(std::move(Err)));
  263. RegisterPassPlugins(Conf.PassPlugins, PB);
  264. LoopAnalysisManager LAM;
  265. FunctionAnalysisManager FAM;
  266. CGSCCAnalysisManager CGAM;
  267. ModuleAnalysisManager MAM;
  268. std::unique_ptr<TargetLibraryInfoImpl> TLII(
  269. new TargetLibraryInfoImpl(Triple(TM->getTargetTriple())));
  270. if (Conf.Freestanding)
  271. TLII->disableAllFunctions();
  272. FAM.registerPass([&] { return TargetLibraryAnalysis(*TLII); });
  273. // Register the AA manager first so that our version is the one used.
  274. FAM.registerPass([&] { return std::move(AA); });
  275. // Register all the basic analyses with the managers.
  276. PB.registerModuleAnalyses(MAM);
  277. PB.registerCGSCCAnalyses(CGAM);
  278. PB.registerFunctionAnalyses(FAM);
  279. PB.registerLoopAnalyses(LAM);
  280. PB.crossRegisterProxies(LAM, FAM, CGAM, MAM);
  281. ModulePassManager MPM;
  282. // Always verify the input.
  283. MPM.addPass(VerifierPass());
  284. // Now, add all the passes we've been requested to.
  285. if (auto Err = PB.parsePassPipeline(MPM, PipelineDesc))
  286. report_fatal_error("unable to parse pass pipeline description '" +
  287. PipelineDesc + "': " + toString(std::move(Err)));
  288. if (!DisableVerify)
  289. MPM.addPass(VerifierPass());
  290. MPM.run(Mod, MAM);
  291. }
  292. static void runOldPMPasses(const Config &Conf, Module &Mod, TargetMachine *TM,
  293. bool IsThinLTO, ModuleSummaryIndex *ExportSummary,
  294. const ModuleSummaryIndex *ImportSummary) {
  295. legacy::PassManager passes;
  296. passes.add(createTargetTransformInfoWrapperPass(TM->getTargetIRAnalysis()));
  297. PassManagerBuilder PMB;
  298. PMB.LibraryInfo = new TargetLibraryInfoImpl(Triple(TM->getTargetTriple()));
  299. if (Conf.Freestanding)
  300. PMB.LibraryInfo->disableAllFunctions();
  301. PMB.Inliner = createFunctionInliningPass();
  302. PMB.ExportSummary = ExportSummary;
  303. PMB.ImportSummary = ImportSummary;
  304. // Unconditionally verify input since it is not verified before this
  305. // point and has unknown origin.
  306. PMB.VerifyInput = true;
  307. PMB.VerifyOutput = !Conf.DisableVerify;
  308. PMB.LoopVectorize = true;
  309. PMB.SLPVectorize = true;
  310. PMB.OptLevel = Conf.OptLevel;
  311. PMB.PGOSampleUse = Conf.SampleProfile;
  312. PMB.EnablePGOCSInstrGen = Conf.RunCSIRInstr;
  313. if (!Conf.RunCSIRInstr && !Conf.CSIRProfile.empty()) {
  314. PMB.EnablePGOCSInstrUse = true;
  315. PMB.PGOInstrUse = Conf.CSIRProfile;
  316. }
  317. if (IsThinLTO)
  318. PMB.populateThinLTOPassManager(passes);
  319. else
  320. PMB.populateLTOPassManager(passes);
  321. passes.run(Mod);
  322. }
  323. bool lto::opt(const Config &Conf, TargetMachine *TM, unsigned Task, Module &Mod,
  324. bool IsThinLTO, ModuleSummaryIndex *ExportSummary,
  325. const ModuleSummaryIndex *ImportSummary,
  326. const std::vector<uint8_t> &CmdArgs) {
  327. if (EmbedBitcode == LTOBitcodeEmbedding::EmbedPostMergePreOptimized) {
  328. // FIXME: the motivation for capturing post-merge bitcode and command line
  329. // is replicating the compilation environment from bitcode, without needing
  330. // to understand the dependencies (the functions to be imported). This
  331. // assumes a clang - based invocation, case in which we have the command
  332. // line.
  333. // It's not very clear how the above motivation would map in the
  334. // linker-based case, so we currently don't plumb the command line args in
  335. // that case.
  336. if (CmdArgs.empty())
  337. LLVM_DEBUG(
  338. dbgs() << "Post-(Thin)LTO merge bitcode embedding was requested, but "
  339. "command line arguments are not available");
  340. llvm::EmbedBitcodeInModule(Mod, llvm::MemoryBufferRef(),
  341. /*EmbedBitcode*/ true, /*EmbedCmdline*/ true,
  342. /*Cmdline*/ CmdArgs);
  343. }
  344. // FIXME: Plumb the combined index into the new pass manager.
  345. if (!Conf.OptPipeline.empty())
  346. runNewPMCustomPasses(Conf, Mod, TM, Conf.OptPipeline, Conf.AAPipeline,
  347. Conf.DisableVerify);
  348. else if (Conf.UseNewPM)
  349. runNewPMPasses(Conf, Mod, TM, Conf.OptLevel, IsThinLTO, ExportSummary,
  350. ImportSummary);
  351. else
  352. runOldPMPasses(Conf, Mod, TM, IsThinLTO, ExportSummary, ImportSummary);
  353. return !Conf.PostOptModuleHook || Conf.PostOptModuleHook(Task, Mod);
  354. }
  355. static void codegen(const Config &Conf, TargetMachine *TM,
  356. AddStreamFn AddStream, unsigned Task, Module &Mod,
  357. const ModuleSummaryIndex &CombinedIndex) {
  358. if (Conf.PreCodeGenModuleHook && !Conf.PreCodeGenModuleHook(Task, Mod))
  359. return;
  360. if (EmbedBitcode == LTOBitcodeEmbedding::EmbedOptimized)
  361. llvm::EmbedBitcodeInModule(Mod, llvm::MemoryBufferRef(),
  362. /*EmbedBitcode*/ true,
  363. /*EmbedCmdline*/ false,
  364. /*CmdArgs*/ std::vector<uint8_t>());
  365. std::unique_ptr<ToolOutputFile> DwoOut;
  366. SmallString<1024> DwoFile(Conf.SplitDwarfOutput);
  367. if (!Conf.DwoDir.empty()) {
  368. std::error_code EC;
  369. if (auto EC = llvm::sys::fs::create_directories(Conf.DwoDir))
  370. report_fatal_error("Failed to create directory " + Conf.DwoDir + ": " +
  371. EC.message());
  372. DwoFile = Conf.DwoDir;
  373. sys::path::append(DwoFile, std::to_string(Task) + ".dwo");
  374. TM->Options.MCOptions.SplitDwarfFile = std::string(DwoFile);
  375. } else
  376. TM->Options.MCOptions.SplitDwarfFile = Conf.SplitDwarfFile;
  377. if (!DwoFile.empty()) {
  378. std::error_code EC;
  379. DwoOut = std::make_unique<ToolOutputFile>(DwoFile, EC, sys::fs::OF_None);
  380. if (EC)
  381. report_fatal_error("Failed to open " + DwoFile + ": " + EC.message());
  382. }
  383. auto Stream = AddStream(Task);
  384. legacy::PassManager CodeGenPasses;
  385. CodeGenPasses.add(
  386. createImmutableModuleSummaryIndexWrapperPass(&CombinedIndex));
  387. if (Conf.PreCodeGenPassesHook)
  388. Conf.PreCodeGenPassesHook(CodeGenPasses);
  389. if (TM->addPassesToEmitFile(CodeGenPasses, *Stream->OS,
  390. DwoOut ? &DwoOut->os() : nullptr,
  391. Conf.CGFileType))
  392. report_fatal_error("Failed to setup codegen");
  393. CodeGenPasses.run(Mod);
  394. if (DwoOut)
  395. DwoOut->keep();
  396. }
  397. static void splitCodeGen(const Config &C, TargetMachine *TM,
  398. AddStreamFn AddStream,
  399. unsigned ParallelCodeGenParallelismLevel,
  400. std::unique_ptr<Module> Mod,
  401. const ModuleSummaryIndex &CombinedIndex) {
  402. ThreadPool CodegenThreadPool(
  403. heavyweight_hardware_concurrency(ParallelCodeGenParallelismLevel));
  404. unsigned ThreadCount = 0;
  405. const Target *T = &TM->getTarget();
  406. SplitModule(
  407. std::move(Mod), ParallelCodeGenParallelismLevel,
  408. [&](std::unique_ptr<Module> MPart) {
  409. // We want to clone the module in a new context to multi-thread the
  410. // codegen. We do it by serializing partition modules to bitcode
  411. // (while still on the main thread, in order to avoid data races) and
  412. // spinning up new threads which deserialize the partitions into
  413. // separate contexts.
  414. // FIXME: Provide a more direct way to do this in LLVM.
  415. SmallString<0> BC;
  416. raw_svector_ostream BCOS(BC);
  417. WriteBitcodeToFile(*MPart, BCOS);
  418. // Enqueue the task
  419. CodegenThreadPool.async(
  420. [&](const SmallString<0> &BC, unsigned ThreadId) {
  421. LTOLLVMContext Ctx(C);
  422. Expected<std::unique_ptr<Module>> MOrErr = parseBitcodeFile(
  423. MemoryBufferRef(StringRef(BC.data(), BC.size()), "ld-temp.o"),
  424. Ctx);
  425. if (!MOrErr)
  426. report_fatal_error("Failed to read bitcode");
  427. std::unique_ptr<Module> MPartInCtx = std::move(MOrErr.get());
  428. std::unique_ptr<TargetMachine> TM =
  429. createTargetMachine(C, T, *MPartInCtx);
  430. codegen(C, TM.get(), AddStream, ThreadId, *MPartInCtx,
  431. CombinedIndex);
  432. },
  433. // Pass BC using std::move to ensure that it get moved rather than
  434. // copied into the thread's context.
  435. std::move(BC), ThreadCount++);
  436. },
  437. false);
  438. // Because the inner lambda (which runs in a worker thread) captures our local
  439. // variables, we need to wait for the worker threads to terminate before we
  440. // can leave the function scope.
  441. CodegenThreadPool.wait();
  442. }
  443. static Expected<const Target *> initAndLookupTarget(const Config &C,
  444. Module &Mod) {
  445. if (!C.OverrideTriple.empty())
  446. Mod.setTargetTriple(C.OverrideTriple);
  447. else if (Mod.getTargetTriple().empty())
  448. Mod.setTargetTriple(C.DefaultTriple);
  449. std::string Msg;
  450. const Target *T = TargetRegistry::lookupTarget(Mod.getTargetTriple(), Msg);
  451. if (!T)
  452. return make_error<StringError>(Msg, inconvertibleErrorCode());
  453. return T;
  454. }
  455. Error lto::finalizeOptimizationRemarks(
  456. std::unique_ptr<ToolOutputFile> DiagOutputFile) {
  457. // Make sure we flush the diagnostic remarks file in case the linker doesn't
  458. // call the global destructors before exiting.
  459. if (!DiagOutputFile)
  460. return Error::success();
  461. DiagOutputFile->keep();
  462. DiagOutputFile->os().flush();
  463. return Error::success();
  464. }
  465. Error lto::backend(const Config &C, AddStreamFn AddStream,
  466. unsigned ParallelCodeGenParallelismLevel,
  467. std::unique_ptr<Module> Mod,
  468. ModuleSummaryIndex &CombinedIndex) {
  469. Expected<const Target *> TOrErr = initAndLookupTarget(C, *Mod);
  470. if (!TOrErr)
  471. return TOrErr.takeError();
  472. std::unique_ptr<TargetMachine> TM = createTargetMachine(C, *TOrErr, *Mod);
  473. if (!C.CodeGenOnly) {
  474. if (!opt(C, TM.get(), 0, *Mod, /*IsThinLTO=*/false,
  475. /*ExportSummary=*/&CombinedIndex, /*ImportSummary=*/nullptr,
  476. /*CmdArgs*/ std::vector<uint8_t>()))
  477. return Error::success();
  478. }
  479. if (ParallelCodeGenParallelismLevel == 1) {
  480. codegen(C, TM.get(), AddStream, 0, *Mod, CombinedIndex);
  481. } else {
  482. splitCodeGen(C, TM.get(), AddStream, ParallelCodeGenParallelismLevel,
  483. std::move(Mod), CombinedIndex);
  484. }
  485. return Error::success();
  486. }
  487. static void dropDeadSymbols(Module &Mod, const GVSummaryMapTy &DefinedGlobals,
  488. const ModuleSummaryIndex &Index) {
  489. std::vector<GlobalValue*> DeadGVs;
  490. for (auto &GV : Mod.global_values())
  491. if (GlobalValueSummary *GVS = DefinedGlobals.lookup(GV.getGUID()))
  492. if (!Index.isGlobalValueLive(GVS)) {
  493. DeadGVs.push_back(&GV);
  494. convertToDeclaration(GV);
  495. }
  496. // Now that all dead bodies have been dropped, delete the actual objects
  497. // themselves when possible.
  498. for (GlobalValue *GV : DeadGVs) {
  499. GV->removeDeadConstantUsers();
  500. // Might reference something defined in native object (i.e. dropped a
  501. // non-prevailing IR def, but we need to keep the declaration).
  502. if (GV->use_empty())
  503. GV->eraseFromParent();
  504. }
  505. }
  506. Error lto::thinBackend(const Config &Conf, unsigned Task, AddStreamFn AddStream,
  507. Module &Mod, const ModuleSummaryIndex &CombinedIndex,
  508. const FunctionImporter::ImportMapTy &ImportList,
  509. const GVSummaryMapTy &DefinedGlobals,
  510. MapVector<StringRef, BitcodeModule> &ModuleMap,
  511. const std::vector<uint8_t> &CmdArgs) {
  512. Expected<const Target *> TOrErr = initAndLookupTarget(Conf, Mod);
  513. if (!TOrErr)
  514. return TOrErr.takeError();
  515. std::unique_ptr<TargetMachine> TM = createTargetMachine(Conf, *TOrErr, Mod);
  516. // Setup optimization remarks.
  517. auto DiagFileOrErr = lto::setupLLVMOptimizationRemarks(
  518. Mod.getContext(), Conf.RemarksFilename, Conf.RemarksPasses,
  519. Conf.RemarksFormat, Conf.RemarksWithHotness, Conf.RemarksHotnessThreshold,
  520. Task);
  521. if (!DiagFileOrErr)
  522. return DiagFileOrErr.takeError();
  523. auto DiagnosticOutputFile = std::move(*DiagFileOrErr);
  524. // Set the partial sample profile ratio in the profile summary module flag of
  525. // the module, if applicable.
  526. Mod.setPartialSampleProfileRatio(CombinedIndex);
  527. if (Conf.CodeGenOnly) {
  528. codegen(Conf, TM.get(), AddStream, Task, Mod, CombinedIndex);
  529. return finalizeOptimizationRemarks(std::move(DiagnosticOutputFile));
  530. }
  531. if (Conf.PreOptModuleHook && !Conf.PreOptModuleHook(Task, Mod))
  532. return finalizeOptimizationRemarks(std::move(DiagnosticOutputFile));
  533. auto OptimizeAndCodegen =
  534. [&](Module &Mod, TargetMachine *TM,
  535. std::unique_ptr<ToolOutputFile> DiagnosticOutputFile) {
  536. if (!opt(Conf, TM, Task, Mod, /*IsThinLTO=*/true,
  537. /*ExportSummary=*/nullptr, /*ImportSummary=*/&CombinedIndex,
  538. CmdArgs))
  539. return finalizeOptimizationRemarks(std::move(DiagnosticOutputFile));
  540. codegen(Conf, TM, AddStream, Task, Mod, CombinedIndex);
  541. return finalizeOptimizationRemarks(std::move(DiagnosticOutputFile));
  542. };
  543. if (ThinLTOAssumeMerged)
  544. return OptimizeAndCodegen(Mod, TM.get(), std::move(DiagnosticOutputFile));
  545. // When linking an ELF shared object, dso_local should be dropped. We
  546. // conservatively do this for -fpic.
  547. bool ClearDSOLocalOnDeclarations =
  548. TM->getTargetTriple().isOSBinFormatELF() &&
  549. TM->getRelocationModel() != Reloc::Static &&
  550. Mod.getPIELevel() == PIELevel::Default;
  551. renameModuleForThinLTO(Mod, CombinedIndex, ClearDSOLocalOnDeclarations);
  552. dropDeadSymbols(Mod, DefinedGlobals, CombinedIndex);
  553. thinLTOResolvePrevailingInModule(Mod, DefinedGlobals);
  554. if (Conf.PostPromoteModuleHook && !Conf.PostPromoteModuleHook(Task, Mod))
  555. return finalizeOptimizationRemarks(std::move(DiagnosticOutputFile));
  556. if (!DefinedGlobals.empty())
  557. thinLTOInternalizeModule(Mod, DefinedGlobals);
  558. if (Conf.PostInternalizeModuleHook &&
  559. !Conf.PostInternalizeModuleHook(Task, Mod))
  560. return finalizeOptimizationRemarks(std::move(DiagnosticOutputFile));
  561. auto ModuleLoader = [&](StringRef Identifier) {
  562. assert(Mod.getContext().isODRUniquingDebugTypes() &&
  563. "ODR Type uniquing should be enabled on the context");
  564. auto I = ModuleMap.find(Identifier);
  565. assert(I != ModuleMap.end());
  566. return I->second.getLazyModule(Mod.getContext(),
  567. /*ShouldLazyLoadMetadata=*/true,
  568. /*IsImporting*/ true);
  569. };
  570. FunctionImporter Importer(CombinedIndex, ModuleLoader,
  571. ClearDSOLocalOnDeclarations);
  572. if (Error Err = Importer.importFunctions(Mod, ImportList).takeError())
  573. return Err;
  574. if (Conf.PostImportModuleHook && !Conf.PostImportModuleHook(Task, Mod))
  575. return finalizeOptimizationRemarks(std::move(DiagnosticOutputFile));
  576. return OptimizeAndCodegen(Mod, TM.get(), std::move(DiagnosticOutputFile));
  577. }
  578. BitcodeModule *lto::findThinLTOModule(MutableArrayRef<BitcodeModule> BMs) {
  579. if (ThinLTOAssumeMerged && BMs.size() == 1)
  580. return BMs.begin();
  581. for (BitcodeModule &BM : BMs) {
  582. Expected<BitcodeLTOInfo> LTOInfo = BM.getLTOInfo();
  583. if (LTOInfo && LTOInfo->IsThinLTO)
  584. return &BM;
  585. }
  586. return nullptr;
  587. }
  588. Expected<BitcodeModule> lto::findThinLTOModule(MemoryBufferRef MBRef) {
  589. Expected<std::vector<BitcodeModule>> BMsOrErr = getBitcodeModuleList(MBRef);
  590. if (!BMsOrErr)
  591. return BMsOrErr.takeError();
  592. // The bitcode file may contain multiple modules, we want the one that is
  593. // marked as being the ThinLTO module.
  594. if (const BitcodeModule *Bm = lto::findThinLTOModule(*BMsOrErr))
  595. return *Bm;
  596. return make_error<StringError>("Could not find module summary",
  597. inconvertibleErrorCode());
  598. }
  599. bool lto::loadReferencedModules(
  600. const Module &M, const ModuleSummaryIndex &CombinedIndex,
  601. FunctionImporter::ImportMapTy &ImportList,
  602. MapVector<llvm::StringRef, llvm::BitcodeModule> &ModuleMap,
  603. std::vector<std::unique_ptr<llvm::MemoryBuffer>>
  604. &OwnedImportsLifetimeManager) {
  605. if (ThinLTOAssumeMerged)
  606. return true;
  607. // We can simply import the values mentioned in the combined index, since
  608. // we should only invoke this using the individual indexes written out
  609. // via a WriteIndexesThinBackend.
  610. for (const auto &GlobalList : CombinedIndex) {
  611. // Ignore entries for undefined references.
  612. if (GlobalList.second.SummaryList.empty())
  613. continue;
  614. auto GUID = GlobalList.first;
  615. for (const auto &Summary : GlobalList.second.SummaryList) {
  616. // Skip the summaries for the importing module. These are included to
  617. // e.g. record required linkage changes.
  618. if (Summary->modulePath() == M.getModuleIdentifier())
  619. continue;
  620. // Add an entry to provoke importing by thinBackend.
  621. ImportList[Summary->modulePath()].insert(GUID);
  622. }
  623. }
  624. for (auto &I : ImportList) {
  625. ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> MBOrErr =
  626. llvm::MemoryBuffer::getFile(I.first());
  627. if (!MBOrErr) {
  628. errs() << "Error loading imported file '" << I.first()
  629. << "': " << MBOrErr.getError().message() << "\n";
  630. return false;
  631. }
  632. Expected<BitcodeModule> BMOrErr = findThinLTOModule(**MBOrErr);
  633. if (!BMOrErr) {
  634. handleAllErrors(BMOrErr.takeError(), [&](ErrorInfoBase &EIB) {
  635. errs() << "Error loading imported file '" << I.first()
  636. << "': " << EIB.message() << '\n';
  637. });
  638. return false;
  639. }
  640. ModuleMap.insert({I.first(), *BMOrErr});
  641. OwnedImportsLifetimeManager.push_back(std::move(*MBOrErr));
  642. }
  643. return true;
  644. }