LTOBackend.cpp 16 KB

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