LTOBackend.cpp 27 KB

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