1 //===-LTOBackend.cpp - LLVM Link Time Optimizer Backend -------------------===//
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
7 //===----------------------------------------------------------------------===//
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.
14 //===----------------------------------------------------------------------===//
16 #include "llvm/LTO/LTOBackend.h"
17 #include "llvm/Analysis/AliasAnalysis.h"
18 #include "llvm/Analysis/CGSCCPassManager.h"
19 #include "llvm/Analysis/ModuleSummaryAnalysis.h"
20 #include "llvm/Analysis/TargetLibraryInfo.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/TargetRegistry.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/ThreadPool.h"
39 #include "llvm/Support/ToolOutputFile.h"
40 #include "llvm/Support/VirtualFileSystem.h"
41 #include "llvm/Support/raw_ostream.h"
42 #include "llvm/Target/TargetMachine.h"
43 #include "llvm/TargetParser/SubtargetFeature.h"
44 #include "llvm/Transforms/IPO/WholeProgramDevirt.h"
45 #include "llvm/Transforms/Scalar/LoopPassManager.h"
46 #include "llvm/Transforms/Utils/FunctionImportUtils.h"
47 #include "llvm/Transforms/Utils/SplitModule.h"
53 #define DEBUG_TYPE "lto-backend"
55 enum class LTOBitcodeEmbedding
{
58 EmbedPostMergePreOptimized
= 2
61 static cl::opt
<LTOBitcodeEmbedding
> EmbedBitcode(
62 "lto-embed-bitcode", cl::init(LTOBitcodeEmbedding::DoNotEmbed
),
63 cl::values(clEnumValN(LTOBitcodeEmbedding::DoNotEmbed
, "none",
65 clEnumValN(LTOBitcodeEmbedding::EmbedOptimized
, "optimized",
66 "Embed after all optimization passes"),
67 clEnumValN(LTOBitcodeEmbedding::EmbedPostMergePreOptimized
,
69 "Embed post merge, but before optimizations")),
70 cl::desc("Embed LLVM bitcode in object files produced by LTO"));
72 static cl::opt
<bool> ThinLTOAssumeMerged(
73 "thinlto-assume-merged", cl::init(false),
74 cl::desc("Assume the input has already undergone ThinLTO function "
75 "importing and the other pre-optimization pipeline changes."));
78 extern cl::opt
<bool> NoPGOWarnMismatch
;
81 [[noreturn
]] static void reportOpenError(StringRef Path
, Twine Msg
) {
82 errs() << "failed to open " << Path
<< ": " << Msg
<< '\n';
87 Error
Config::addSaveTemps(std::string OutputFileName
, bool UseInputModulePath
,
88 const DenseSet
<StringRef
> &SaveTempsArgs
) {
89 ShouldDiscardValueNames
= false;
92 if (SaveTempsArgs
.empty() || SaveTempsArgs
.contains("resolution")) {
94 std::make_unique
<raw_fd_ostream
>(OutputFileName
+ "resolution.txt", EC
,
95 sys::fs::OpenFlags::OF_TextWithCRLF
);
97 ResolutionFile
.reset();
98 return errorCodeToError(EC
);
102 auto setHook
= [&](std::string PathSuffix
, ModuleHookFn
&Hook
) {
103 // Keep track of the hook provided by the linker, which also needs to run.
104 ModuleHookFn LinkerHook
= Hook
;
105 Hook
= [=](unsigned Task
, const Module
&M
) {
106 // If the linker's hook returned false, we need to pass that result
108 if (LinkerHook
&& !LinkerHook(Task
, M
))
111 std::string PathPrefix
;
112 // If this is the combined module (not a ThinLTO backend compile) or the
113 // user hasn't requested using the input module's path, emit to a file
114 // named from the provided OutputFileName with the Task ID appended.
115 if (M
.getModuleIdentifier() == "ld-temp.o" || !UseInputModulePath
) {
116 PathPrefix
= OutputFileName
;
117 if (Task
!= (unsigned)-1)
118 PathPrefix
+= utostr(Task
) + ".";
120 PathPrefix
= M
.getModuleIdentifier() + ".";
121 std::string Path
= PathPrefix
+ PathSuffix
+ ".bc";
123 raw_fd_ostream
OS(Path
, EC
, sys::fs::OpenFlags::OF_None
);
124 // Because -save-temps is a debugging feature, we report the error
125 // directly and exit.
127 reportOpenError(Path
, EC
.message());
128 WriteBitcodeToFile(M
, OS
, /*ShouldPreserveUseListOrder=*/false);
133 auto SaveCombinedIndex
=
134 [=](const ModuleSummaryIndex
&Index
,
135 const DenseSet
<GlobalValue::GUID
> &GUIDPreservedSymbols
) {
136 std::string Path
= OutputFileName
+ "index.bc";
138 raw_fd_ostream
OS(Path
, EC
, sys::fs::OpenFlags::OF_None
);
139 // Because -save-temps is a debugging feature, we report the error
140 // directly and exit.
142 reportOpenError(Path
, EC
.message());
143 writeIndexToFile(Index
, OS
);
145 Path
= OutputFileName
+ "index.dot";
146 raw_fd_ostream
OSDot(Path
, EC
, sys::fs::OpenFlags::OF_None
);
148 reportOpenError(Path
, EC
.message());
149 Index
.exportToDot(OSDot
, GUIDPreservedSymbols
);
153 if (SaveTempsArgs
.empty()) {
154 setHook("0.preopt", PreOptModuleHook
);
155 setHook("1.promote", PostPromoteModuleHook
);
156 setHook("2.internalize", PostInternalizeModuleHook
);
157 setHook("3.import", PostImportModuleHook
);
158 setHook("4.opt", PostOptModuleHook
);
159 setHook("5.precodegen", PreCodeGenModuleHook
);
160 CombinedIndexHook
= SaveCombinedIndex
;
162 if (SaveTempsArgs
.contains("preopt"))
163 setHook("0.preopt", PreOptModuleHook
);
164 if (SaveTempsArgs
.contains("promote"))
165 setHook("1.promote", PostPromoteModuleHook
);
166 if (SaveTempsArgs
.contains("internalize"))
167 setHook("2.internalize", PostInternalizeModuleHook
);
168 if (SaveTempsArgs
.contains("import"))
169 setHook("3.import", PostImportModuleHook
);
170 if (SaveTempsArgs
.contains("opt"))
171 setHook("4.opt", PostOptModuleHook
);
172 if (SaveTempsArgs
.contains("precodegen"))
173 setHook("5.precodegen", PreCodeGenModuleHook
);
174 if (SaveTempsArgs
.contains("combinedindex"))
175 CombinedIndexHook
= SaveCombinedIndex
;
178 return Error::success();
181 #define HANDLE_EXTENSION(Ext) \
182 llvm::PassPluginLibraryInfo get##Ext##PluginInfo();
183 #include "llvm/Support/Extension.def"
185 static void RegisterPassPlugins(ArrayRef
<std::string
> PassPlugins
,
187 #define HANDLE_EXTENSION(Ext) \
188 get##Ext##PluginInfo().RegisterPassBuilderCallbacks(PB);
189 #include "llvm/Support/Extension.def"
191 // Load requested pass plugins and let them register pass builder callbacks
192 for (auto &PluginFN
: PassPlugins
) {
193 auto PassPlugin
= PassPlugin::Load(PluginFN
);
195 errs() << "Failed to load passes from '" << PluginFN
196 << "'. Request ignored.\n";
200 PassPlugin
->registerPassBuilderCallbacks(PB
);
204 static std::unique_ptr
<TargetMachine
>
205 createTargetMachine(const Config
&Conf
, const Target
*TheTarget
, Module
&M
) {
206 StringRef TheTriple
= M
.getTargetTriple();
207 SubtargetFeatures Features
;
208 Features
.getDefaultSubtargetFeatures(Triple(TheTriple
));
209 for (const std::string
&A
: Conf
.MAttrs
)
210 Features
.AddFeature(A
);
212 std::optional
<Reloc::Model
> RelocModel
;
214 RelocModel
= *Conf
.RelocModel
;
215 else if (M
.getModuleFlag("PIC Level"))
217 M
.getPICLevel() == PICLevel::NotPIC
? Reloc::Static
: Reloc::PIC_
;
219 std::optional
<CodeModel::Model
> CodeModel
;
221 CodeModel
= *Conf
.CodeModel
;
223 CodeModel
= M
.getCodeModel();
225 std::unique_ptr
<TargetMachine
> TM(TheTarget
->createTargetMachine(
226 TheTriple
, Conf
.CPU
, Features
.getString(), Conf
.Options
, RelocModel
,
227 CodeModel
, Conf
.CGOptLevel
));
229 assert(TM
&& "Failed to create target machine");
231 if (std::optional
<uint64_t> LargeDataThreshold
= M
.getLargeDataThreshold())
232 TM
->setLargeDataThreshold(*LargeDataThreshold
);
237 static void runNewPMPasses(const Config
&Conf
, Module
&Mod
, TargetMachine
*TM
,
238 unsigned OptLevel
, bool IsThinLTO
,
239 ModuleSummaryIndex
*ExportSummary
,
240 const ModuleSummaryIndex
*ImportSummary
) {
241 auto FS
= vfs::getRealFileSystem();
242 std::optional
<PGOOptions
> PGOOpt
;
243 if (!Conf
.SampleProfile
.empty())
244 PGOOpt
= PGOOptions(Conf
.SampleProfile
, "", Conf
.ProfileRemapping
,
245 /*MemoryProfile=*/"", FS
, PGOOptions::SampleUse
,
246 PGOOptions::NoCSAction
, true);
247 else if (Conf
.RunCSIRInstr
) {
248 PGOOpt
= PGOOptions("", Conf
.CSIRProfile
, Conf
.ProfileRemapping
,
249 /*MemoryProfile=*/"", FS
, PGOOptions::IRUse
,
250 PGOOptions::CSIRInstr
, Conf
.AddFSDiscriminator
);
251 } else if (!Conf
.CSIRProfile
.empty()) {
252 PGOOpt
= PGOOptions(Conf
.CSIRProfile
, "", Conf
.ProfileRemapping
,
253 /*MemoryProfile=*/"", FS
, PGOOptions::IRUse
,
254 PGOOptions::CSIRUse
, Conf
.AddFSDiscriminator
);
255 NoPGOWarnMismatch
= !Conf
.PGOWarnMismatch
;
256 } else if (Conf
.AddFSDiscriminator
) {
257 PGOOpt
= PGOOptions("", "", "", /*MemoryProfile=*/"", nullptr,
258 PGOOptions::NoAction
, PGOOptions::NoCSAction
, true);
260 TM
->setPGOOption(PGOOpt
);
262 LoopAnalysisManager LAM
;
263 FunctionAnalysisManager FAM
;
264 CGSCCAnalysisManager CGAM
;
265 ModuleAnalysisManager MAM
;
267 PassInstrumentationCallbacks PIC
;
268 StandardInstrumentations
SI(Mod
.getContext(), Conf
.DebugPassManager
,
270 SI
.registerCallbacks(PIC
, &MAM
);
271 PassBuilder
PB(TM
, Conf
.PTO
, PGOOpt
, &PIC
);
273 RegisterPassPlugins(Conf
.PassPlugins
, PB
);
275 std::unique_ptr
<TargetLibraryInfoImpl
> TLII(
276 new TargetLibraryInfoImpl(Triple(TM
->getTargetTriple())));
277 if (Conf
.Freestanding
)
278 TLII
->disableAllFunctions();
279 FAM
.registerPass([&] { return TargetLibraryAnalysis(*TLII
); });
281 // Parse a custom AA pipeline if asked to.
282 if (!Conf
.AAPipeline
.empty()) {
284 if (auto Err
= PB
.parseAAPipeline(AA
, Conf
.AAPipeline
)) {
285 report_fatal_error(Twine("unable to parse AA pipeline description '") +
286 Conf
.AAPipeline
+ "': " + toString(std::move(Err
)));
288 // Register the AA manager first so that our version is the one used.
289 FAM
.registerPass([&] { return std::move(AA
); });
292 // Register all the basic analyses with the managers.
293 PB
.registerModuleAnalyses(MAM
);
294 PB
.registerCGSCCAnalyses(CGAM
);
295 PB
.registerFunctionAnalyses(FAM
);
296 PB
.registerLoopAnalyses(LAM
);
297 PB
.crossRegisterProxies(LAM
, FAM
, CGAM
, MAM
);
299 ModulePassManager MPM
;
301 if (!Conf
.DisableVerify
)
302 MPM
.addPass(VerifierPass());
304 OptimizationLevel OL
;
308 llvm_unreachable("Invalid optimization level");
310 OL
= OptimizationLevel::O0
;
313 OL
= OptimizationLevel::O1
;
316 OL
= OptimizationLevel::O2
;
319 OL
= OptimizationLevel::O3
;
323 // Parse a custom pipeline if asked to.
324 if (!Conf
.OptPipeline
.empty()) {
325 if (auto Err
= PB
.parsePassPipeline(MPM
, Conf
.OptPipeline
)) {
326 report_fatal_error(Twine("unable to parse pass pipeline description '") +
327 Conf
.OptPipeline
+ "': " + toString(std::move(Err
)));
329 } else if (Conf
.UseDefaultPipeline
) {
330 MPM
.addPass(PB
.buildPerModuleDefaultPipeline(OL
));
331 } else if (IsThinLTO
) {
332 MPM
.addPass(PB
.buildThinLTODefaultPipeline(OL
, ImportSummary
));
334 MPM
.addPass(PB
.buildLTODefaultPipeline(OL
, ExportSummary
));
337 if (!Conf
.DisableVerify
)
338 MPM
.addPass(VerifierPass());
343 bool lto::opt(const Config
&Conf
, TargetMachine
*TM
, unsigned Task
, Module
&Mod
,
344 bool IsThinLTO
, ModuleSummaryIndex
*ExportSummary
,
345 const ModuleSummaryIndex
*ImportSummary
,
346 const std::vector
<uint8_t> &CmdArgs
) {
347 if (EmbedBitcode
== LTOBitcodeEmbedding::EmbedPostMergePreOptimized
) {
348 // FIXME: the motivation for capturing post-merge bitcode and command line
349 // is replicating the compilation environment from bitcode, without needing
350 // to understand the dependencies (the functions to be imported). This
351 // assumes a clang - based invocation, case in which we have the command
353 // It's not very clear how the above motivation would map in the
354 // linker-based case, so we currently don't plumb the command line args in
358 dbgs() << "Post-(Thin)LTO merge bitcode embedding was requested, but "
359 "command line arguments are not available");
360 llvm::embedBitcodeInModule(Mod
, llvm::MemoryBufferRef(),
361 /*EmbedBitcode*/ true, /*EmbedCmdline*/ true,
362 /*Cmdline*/ CmdArgs
);
364 // FIXME: Plumb the combined index into the new pass manager.
365 runNewPMPasses(Conf
, Mod
, TM
, Conf
.OptLevel
, IsThinLTO
, ExportSummary
,
367 return !Conf
.PostOptModuleHook
|| Conf
.PostOptModuleHook(Task
, Mod
);
370 static void codegen(const Config
&Conf
, TargetMachine
*TM
,
371 AddStreamFn AddStream
, unsigned Task
, Module
&Mod
,
372 const ModuleSummaryIndex
&CombinedIndex
) {
373 if (Conf
.PreCodeGenModuleHook
&& !Conf
.PreCodeGenModuleHook(Task
, Mod
))
376 if (EmbedBitcode
== LTOBitcodeEmbedding::EmbedOptimized
)
377 llvm::embedBitcodeInModule(Mod
, llvm::MemoryBufferRef(),
378 /*EmbedBitcode*/ true,
379 /*EmbedCmdline*/ false,
380 /*CmdArgs*/ std::vector
<uint8_t>());
382 std::unique_ptr
<ToolOutputFile
> DwoOut
;
383 SmallString
<1024> DwoFile(Conf
.SplitDwarfOutput
);
384 if (!Conf
.DwoDir
.empty()) {
386 if (auto EC
= llvm::sys::fs::create_directories(Conf
.DwoDir
))
387 report_fatal_error(Twine("Failed to create directory ") + Conf
.DwoDir
+
388 ": " + EC
.message());
390 DwoFile
= Conf
.DwoDir
;
391 sys::path::append(DwoFile
, std::to_string(Task
) + ".dwo");
392 TM
->Options
.MCOptions
.SplitDwarfFile
= std::string(DwoFile
);
394 TM
->Options
.MCOptions
.SplitDwarfFile
= Conf
.SplitDwarfFile
;
396 if (!DwoFile
.empty()) {
398 DwoOut
= std::make_unique
<ToolOutputFile
>(DwoFile
, EC
, sys::fs::OF_None
);
400 report_fatal_error(Twine("Failed to open ") + DwoFile
+ ": " +
404 Expected
<std::unique_ptr
<CachedFileStream
>> StreamOrErr
=
405 AddStream(Task
, Mod
.getModuleIdentifier());
406 if (Error Err
= StreamOrErr
.takeError())
407 report_fatal_error(std::move(Err
));
408 std::unique_ptr
<CachedFileStream
> &Stream
= *StreamOrErr
;
409 TM
->Options
.ObjectFilenameForDebug
= Stream
->ObjectPathName
;
411 legacy::PassManager CodeGenPasses
;
412 TargetLibraryInfoImpl
TLII(Triple(Mod
.getTargetTriple()));
413 CodeGenPasses
.add(new TargetLibraryInfoWrapperPass(TLII
));
415 createImmutableModuleSummaryIndexWrapperPass(&CombinedIndex
));
416 if (Conf
.PreCodeGenPassesHook
)
417 Conf
.PreCodeGenPassesHook(CodeGenPasses
);
418 if (TM
->addPassesToEmitFile(CodeGenPasses
, *Stream
->OS
,
419 DwoOut
? &DwoOut
->os() : nullptr,
421 report_fatal_error("Failed to setup codegen");
422 CodeGenPasses
.run(Mod
);
428 static void splitCodeGen(const Config
&C
, TargetMachine
*TM
,
429 AddStreamFn AddStream
,
430 unsigned ParallelCodeGenParallelismLevel
, Module
&Mod
,
431 const ModuleSummaryIndex
&CombinedIndex
) {
432 ThreadPool
CodegenThreadPool(
433 heavyweight_hardware_concurrency(ParallelCodeGenParallelismLevel
));
434 unsigned ThreadCount
= 0;
435 const Target
*T
= &TM
->getTarget();
438 Mod
, ParallelCodeGenParallelismLevel
,
439 [&](std::unique_ptr
<Module
> MPart
) {
440 // We want to clone the module in a new context to multi-thread the
441 // codegen. We do it by serializing partition modules to bitcode
442 // (while still on the main thread, in order to avoid data races) and
443 // spinning up new threads which deserialize the partitions into
444 // separate contexts.
445 // FIXME: Provide a more direct way to do this in LLVM.
447 raw_svector_ostream
BCOS(BC
);
448 WriteBitcodeToFile(*MPart
, BCOS
);
451 CodegenThreadPool
.async(
452 [&](const SmallString
<0> &BC
, unsigned ThreadId
) {
453 LTOLLVMContext
Ctx(C
);
454 Expected
<std::unique_ptr
<Module
>> MOrErr
= parseBitcodeFile(
455 MemoryBufferRef(StringRef(BC
.data(), BC
.size()), "ld-temp.o"),
458 report_fatal_error("Failed to read bitcode");
459 std::unique_ptr
<Module
> MPartInCtx
= std::move(MOrErr
.get());
461 std::unique_ptr
<TargetMachine
> TM
=
462 createTargetMachine(C
, T
, *MPartInCtx
);
464 codegen(C
, TM
.get(), AddStream
, ThreadId
, *MPartInCtx
,
467 // Pass BC using std::move to ensure that it get moved rather than
468 // copied into the thread's context.
469 std::move(BC
), ThreadCount
++);
473 // Because the inner lambda (which runs in a worker thread) captures our local
474 // variables, we need to wait for the worker threads to terminate before we
475 // can leave the function scope.
476 CodegenThreadPool
.wait();
479 static Expected
<const Target
*> initAndLookupTarget(const Config
&C
,
481 if (!C
.OverrideTriple
.empty())
482 Mod
.setTargetTriple(C
.OverrideTriple
);
483 else if (Mod
.getTargetTriple().empty())
484 Mod
.setTargetTriple(C
.DefaultTriple
);
487 const Target
*T
= TargetRegistry::lookupTarget(Mod
.getTargetTriple(), Msg
);
489 return make_error
<StringError
>(Msg
, inconvertibleErrorCode());
493 Error
lto::finalizeOptimizationRemarks(
494 std::unique_ptr
<ToolOutputFile
> DiagOutputFile
) {
495 // Make sure we flush the diagnostic remarks file in case the linker doesn't
496 // call the global destructors before exiting.
498 return Error::success();
499 DiagOutputFile
->keep();
500 DiagOutputFile
->os().flush();
501 return Error::success();
504 Error
lto::backend(const Config
&C
, AddStreamFn AddStream
,
505 unsigned ParallelCodeGenParallelismLevel
, Module
&Mod
,
506 ModuleSummaryIndex
&CombinedIndex
) {
507 Expected
<const Target
*> TOrErr
= initAndLookupTarget(C
, Mod
);
509 return TOrErr
.takeError();
511 std::unique_ptr
<TargetMachine
> TM
= createTargetMachine(C
, *TOrErr
, Mod
);
513 LLVM_DEBUG(dbgs() << "Running regular LTO\n");
514 if (!C
.CodeGenOnly
) {
515 if (!opt(C
, TM
.get(), 0, Mod
, /*IsThinLTO=*/false,
516 /*ExportSummary=*/&CombinedIndex
, /*ImportSummary=*/nullptr,
517 /*CmdArgs*/ std::vector
<uint8_t>()))
518 return Error::success();
521 if (ParallelCodeGenParallelismLevel
== 1) {
522 codegen(C
, TM
.get(), AddStream
, 0, Mod
, CombinedIndex
);
524 splitCodeGen(C
, TM
.get(), AddStream
, ParallelCodeGenParallelismLevel
, Mod
,
527 return Error::success();
530 static void dropDeadSymbols(Module
&Mod
, const GVSummaryMapTy
&DefinedGlobals
,
531 const ModuleSummaryIndex
&Index
) {
532 std::vector
<GlobalValue
*> DeadGVs
;
533 for (auto &GV
: Mod
.global_values())
534 if (GlobalValueSummary
*GVS
= DefinedGlobals
.lookup(GV
.getGUID()))
535 if (!Index
.isGlobalValueLive(GVS
)) {
536 DeadGVs
.push_back(&GV
);
537 convertToDeclaration(GV
);
540 // Now that all dead bodies have been dropped, delete the actual objects
541 // themselves when possible.
542 for (GlobalValue
*GV
: DeadGVs
) {
543 GV
->removeDeadConstantUsers();
544 // Might reference something defined in native object (i.e. dropped a
545 // non-prevailing IR def, but we need to keep the declaration).
547 GV
->eraseFromParent();
551 Error
lto::thinBackend(const Config
&Conf
, unsigned Task
, AddStreamFn AddStream
,
552 Module
&Mod
, const ModuleSummaryIndex
&CombinedIndex
,
553 const FunctionImporter::ImportMapTy
&ImportList
,
554 const GVSummaryMapTy
&DefinedGlobals
,
555 MapVector
<StringRef
, BitcodeModule
> *ModuleMap
,
556 const std::vector
<uint8_t> &CmdArgs
) {
557 Expected
<const Target
*> TOrErr
= initAndLookupTarget(Conf
, Mod
);
559 return TOrErr
.takeError();
561 std::unique_ptr
<TargetMachine
> TM
= createTargetMachine(Conf
, *TOrErr
, Mod
);
563 // Setup optimization remarks.
564 auto DiagFileOrErr
= lto::setupLLVMOptimizationRemarks(
565 Mod
.getContext(), Conf
.RemarksFilename
, Conf
.RemarksPasses
,
566 Conf
.RemarksFormat
, Conf
.RemarksWithHotness
, Conf
.RemarksHotnessThreshold
,
569 return DiagFileOrErr
.takeError();
570 auto DiagnosticOutputFile
= std::move(*DiagFileOrErr
);
572 // Set the partial sample profile ratio in the profile summary module flag of
573 // the module, if applicable.
574 Mod
.setPartialSampleProfileRatio(CombinedIndex
);
576 LLVM_DEBUG(dbgs() << "Running ThinLTO\n");
577 if (Conf
.CodeGenOnly
) {
578 codegen(Conf
, TM
.get(), AddStream
, Task
, Mod
, CombinedIndex
);
579 return finalizeOptimizationRemarks(std::move(DiagnosticOutputFile
));
582 if (Conf
.PreOptModuleHook
&& !Conf
.PreOptModuleHook(Task
, Mod
))
583 return finalizeOptimizationRemarks(std::move(DiagnosticOutputFile
));
585 auto OptimizeAndCodegen
=
586 [&](Module
&Mod
, TargetMachine
*TM
,
587 std::unique_ptr
<ToolOutputFile
> DiagnosticOutputFile
) {
588 if (!opt(Conf
, TM
, Task
, Mod
, /*IsThinLTO=*/true,
589 /*ExportSummary=*/nullptr, /*ImportSummary=*/&CombinedIndex
,
591 return finalizeOptimizationRemarks(std::move(DiagnosticOutputFile
));
593 codegen(Conf
, TM
, AddStream
, Task
, Mod
, CombinedIndex
);
594 return finalizeOptimizationRemarks(std::move(DiagnosticOutputFile
));
597 if (ThinLTOAssumeMerged
)
598 return OptimizeAndCodegen(Mod
, TM
.get(), std::move(DiagnosticOutputFile
));
600 // When linking an ELF shared object, dso_local should be dropped. We
601 // conservatively do this for -fpic.
602 bool ClearDSOLocalOnDeclarations
=
603 TM
->getTargetTriple().isOSBinFormatELF() &&
604 TM
->getRelocationModel() != Reloc::Static
&&
605 Mod
.getPIELevel() == PIELevel::Default
;
606 renameModuleForThinLTO(Mod
, CombinedIndex
, ClearDSOLocalOnDeclarations
);
608 dropDeadSymbols(Mod
, DefinedGlobals
, CombinedIndex
);
610 thinLTOFinalizeInModule(Mod
, DefinedGlobals
, /*PropagateAttrs=*/true);
612 if (Conf
.PostPromoteModuleHook
&& !Conf
.PostPromoteModuleHook(Task
, Mod
))
613 return finalizeOptimizationRemarks(std::move(DiagnosticOutputFile
));
615 if (!DefinedGlobals
.empty())
616 thinLTOInternalizeModule(Mod
, DefinedGlobals
);
618 if (Conf
.PostInternalizeModuleHook
&&
619 !Conf
.PostInternalizeModuleHook(Task
, Mod
))
620 return finalizeOptimizationRemarks(std::move(DiagnosticOutputFile
));
622 auto ModuleLoader
= [&](StringRef Identifier
) {
623 assert(Mod
.getContext().isODRUniquingDebugTypes() &&
624 "ODR Type uniquing should be enabled on the context");
626 auto I
= ModuleMap
->find(Identifier
);
627 assert(I
!= ModuleMap
->end());
628 return I
->second
.getLazyModule(Mod
.getContext(),
629 /*ShouldLazyLoadMetadata=*/true,
630 /*IsImporting*/ true);
633 ErrorOr
<std::unique_ptr
<llvm::MemoryBuffer
>> MBOrErr
=
634 llvm::MemoryBuffer::getFile(Identifier
);
636 return Expected
<std::unique_ptr
<llvm::Module
>>(make_error
<StringError
>(
637 Twine("Error loading imported file ") + Identifier
+ " : ",
638 MBOrErr
.getError()));
640 Expected
<BitcodeModule
> BMOrErr
= findThinLTOModule(**MBOrErr
);
642 return Expected
<std::unique_ptr
<llvm::Module
>>(make_error
<StringError
>(
643 Twine("Error loading imported file ") + Identifier
+ " : " +
644 toString(BMOrErr
.takeError()),
645 inconvertibleErrorCode()));
647 Expected
<std::unique_ptr
<Module
>> MOrErr
=
648 BMOrErr
->getLazyModule(Mod
.getContext(),
649 /*ShouldLazyLoadMetadata=*/true,
650 /*IsImporting*/ true);
652 (*MOrErr
)->setOwnedMemoryBuffer(std::move(*MBOrErr
));
656 FunctionImporter
Importer(CombinedIndex
, ModuleLoader
,
657 ClearDSOLocalOnDeclarations
);
658 if (Error Err
= Importer
.importFunctions(Mod
, ImportList
).takeError())
661 // Do this after any importing so that imported code is updated.
662 updateMemProfAttributes(Mod
, CombinedIndex
);
663 updatePublicTypeTestCalls(Mod
, CombinedIndex
.withWholeProgramVisibility());
665 if (Conf
.PostImportModuleHook
&& !Conf
.PostImportModuleHook(Task
, Mod
))
666 return finalizeOptimizationRemarks(std::move(DiagnosticOutputFile
));
668 return OptimizeAndCodegen(Mod
, TM
.get(), std::move(DiagnosticOutputFile
));
671 BitcodeModule
*lto::findThinLTOModule(MutableArrayRef
<BitcodeModule
> BMs
) {
672 if (ThinLTOAssumeMerged
&& BMs
.size() == 1)
675 for (BitcodeModule
&BM
: BMs
) {
676 Expected
<BitcodeLTOInfo
> LTOInfo
= BM
.getLTOInfo();
677 if (LTOInfo
&& LTOInfo
->IsThinLTO
)
683 Expected
<BitcodeModule
> lto::findThinLTOModule(MemoryBufferRef MBRef
) {
684 Expected
<std::vector
<BitcodeModule
>> BMsOrErr
= getBitcodeModuleList(MBRef
);
686 return BMsOrErr
.takeError();
688 // The bitcode file may contain multiple modules, we want the one that is
689 // marked as being the ThinLTO module.
690 if (const BitcodeModule
*Bm
= lto::findThinLTOModule(*BMsOrErr
))
693 return make_error
<StringError
>("Could not find module summary",
694 inconvertibleErrorCode());
697 bool lto::initImportList(const Module
&M
,
698 const ModuleSummaryIndex
&CombinedIndex
,
699 FunctionImporter::ImportMapTy
&ImportList
) {
700 if (ThinLTOAssumeMerged
)
702 // We can simply import the values mentioned in the combined index, since
703 // we should only invoke this using the individual indexes written out
704 // via a WriteIndexesThinBackend.
705 for (const auto &GlobalList
: CombinedIndex
) {
706 // Ignore entries for undefined references.
707 if (GlobalList
.second
.SummaryList
.empty())
710 auto GUID
= GlobalList
.first
;
711 for (const auto &Summary
: GlobalList
.second
.SummaryList
) {
712 // Skip the summaries for the importing module. These are included to
713 // e.g. record required linkage changes.
714 if (Summary
->modulePath() == M
.getModuleIdentifier())
716 // Add an entry to provoke importing by thinBackend.
717 ImportList
[Summary
->modulePath()].insert(GUID
);