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/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/VirtualFileSystem.h"
42 #include "llvm/Support/raw_ostream.h"
43 #include "llvm/Target/TargetMachine.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
));
228 assert(TM
&& "Failed to create target machine");
232 static void runNewPMPasses(const Config
&Conf
, Module
&Mod
, TargetMachine
*TM
,
233 unsigned OptLevel
, bool IsThinLTO
,
234 ModuleSummaryIndex
*ExportSummary
,
235 const ModuleSummaryIndex
*ImportSummary
) {
236 auto FS
= vfs::getRealFileSystem();
237 std::optional
<PGOOptions
> PGOOpt
;
238 if (!Conf
.SampleProfile
.empty())
239 PGOOpt
= PGOOptions(Conf
.SampleProfile
, "", Conf
.ProfileRemapping
, FS
,
240 PGOOptions::SampleUse
, PGOOptions::NoCSAction
, true);
241 else if (Conf
.RunCSIRInstr
) {
242 PGOOpt
= PGOOptions("", Conf
.CSIRProfile
, Conf
.ProfileRemapping
, FS
,
243 PGOOptions::IRUse
, PGOOptions::CSIRInstr
,
244 Conf
.AddFSDiscriminator
);
245 } else if (!Conf
.CSIRProfile
.empty()) {
246 PGOOpt
= PGOOptions(Conf
.CSIRProfile
, "", Conf
.ProfileRemapping
, FS
,
247 PGOOptions::IRUse
, PGOOptions::CSIRUse
,
248 Conf
.AddFSDiscriminator
);
249 NoPGOWarnMismatch
= !Conf
.PGOWarnMismatch
;
250 } else if (Conf
.AddFSDiscriminator
) {
251 PGOOpt
= PGOOptions("", "", "", nullptr, PGOOptions::NoAction
,
252 PGOOptions::NoCSAction
, true);
254 TM
->setPGOOption(PGOOpt
);
256 LoopAnalysisManager LAM
;
257 FunctionAnalysisManager FAM
;
258 CGSCCAnalysisManager CGAM
;
259 ModuleAnalysisManager MAM
;
261 PassInstrumentationCallbacks PIC
;
262 StandardInstrumentations
SI(Mod
.getContext(), Conf
.DebugPassManager
);
263 SI
.registerCallbacks(PIC
, &MAM
);
264 PassBuilder
PB(TM
, Conf
.PTO
, PGOOpt
, &PIC
);
266 RegisterPassPlugins(Conf
.PassPlugins
, PB
);
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
); });
274 // Parse a custom AA pipeline if asked to.
275 if (!Conf
.AAPipeline
.empty()) {
277 if (auto Err
= PB
.parseAAPipeline(AA
, Conf
.AAPipeline
)) {
278 report_fatal_error(Twine("unable to parse AA pipeline description '") +
279 Conf
.AAPipeline
+ "': " + toString(std::move(Err
)));
281 // Register the AA manager first so that our version is the one used.
282 FAM
.registerPass([&] { return std::move(AA
); });
285 // Register all the basic analyses with the managers.
286 PB
.registerModuleAnalyses(MAM
);
287 PB
.registerCGSCCAnalyses(CGAM
);
288 PB
.registerFunctionAnalyses(FAM
);
289 PB
.registerLoopAnalyses(LAM
);
290 PB
.crossRegisterProxies(LAM
, FAM
, CGAM
, MAM
);
292 ModulePassManager MPM
;
294 if (!Conf
.DisableVerify
)
295 MPM
.addPass(VerifierPass());
297 OptimizationLevel OL
;
301 llvm_unreachable("Invalid optimization level");
303 OL
= OptimizationLevel::O0
;
306 OL
= OptimizationLevel::O1
;
309 OL
= OptimizationLevel::O2
;
312 OL
= OptimizationLevel::O3
;
316 // Parse a custom pipeline if asked to.
317 if (!Conf
.OptPipeline
.empty()) {
318 if (auto Err
= PB
.parsePassPipeline(MPM
, Conf
.OptPipeline
)) {
319 report_fatal_error(Twine("unable to parse pass pipeline description '") +
320 Conf
.OptPipeline
+ "': " + toString(std::move(Err
)));
322 } else if (Conf
.UseDefaultPipeline
) {
323 MPM
.addPass(PB
.buildPerModuleDefaultPipeline(OL
));
324 } else if (IsThinLTO
) {
325 MPM
.addPass(PB
.buildThinLTODefaultPipeline(OL
, ImportSummary
));
327 MPM
.addPass(PB
.buildLTODefaultPipeline(OL
, ExportSummary
));
330 if (!Conf
.DisableVerify
)
331 MPM
.addPass(VerifierPass());
336 bool lto::opt(const Config
&Conf
, TargetMachine
*TM
, unsigned Task
, Module
&Mod
,
337 bool IsThinLTO
, ModuleSummaryIndex
*ExportSummary
,
338 const ModuleSummaryIndex
*ImportSummary
,
339 const std::vector
<uint8_t> &CmdArgs
) {
340 if (EmbedBitcode
== LTOBitcodeEmbedding::EmbedPostMergePreOptimized
) {
341 // FIXME: the motivation for capturing post-merge bitcode and command line
342 // is replicating the compilation environment from bitcode, without needing
343 // to understand the dependencies (the functions to be imported). This
344 // assumes a clang - based invocation, case in which we have the command
346 // It's not very clear how the above motivation would map in the
347 // linker-based case, so we currently don't plumb the command line args in
351 dbgs() << "Post-(Thin)LTO merge bitcode embedding was requested, but "
352 "command line arguments are not available");
353 llvm::embedBitcodeInModule(Mod
, llvm::MemoryBufferRef(),
354 /*EmbedBitcode*/ true, /*EmbedCmdline*/ true,
355 /*Cmdline*/ CmdArgs
);
357 // FIXME: Plumb the combined index into the new pass manager.
358 runNewPMPasses(Conf
, Mod
, TM
, Conf
.OptLevel
, IsThinLTO
, ExportSummary
,
360 return !Conf
.PostOptModuleHook
|| Conf
.PostOptModuleHook(Task
, Mod
);
363 static void codegen(const Config
&Conf
, TargetMachine
*TM
,
364 AddStreamFn AddStream
, unsigned Task
, Module
&Mod
,
365 const ModuleSummaryIndex
&CombinedIndex
) {
366 if (Conf
.PreCodeGenModuleHook
&& !Conf
.PreCodeGenModuleHook(Task
, Mod
))
369 if (EmbedBitcode
== LTOBitcodeEmbedding::EmbedOptimized
)
370 llvm::embedBitcodeInModule(Mod
, llvm::MemoryBufferRef(),
371 /*EmbedBitcode*/ true,
372 /*EmbedCmdline*/ false,
373 /*CmdArgs*/ std::vector
<uint8_t>());
375 std::unique_ptr
<ToolOutputFile
> DwoOut
;
376 SmallString
<1024> DwoFile(Conf
.SplitDwarfOutput
);
377 if (!Conf
.DwoDir
.empty()) {
379 if (auto EC
= llvm::sys::fs::create_directories(Conf
.DwoDir
))
380 report_fatal_error(Twine("Failed to create directory ") + Conf
.DwoDir
+
381 ": " + EC
.message());
383 DwoFile
= Conf
.DwoDir
;
384 sys::path::append(DwoFile
, std::to_string(Task
) + ".dwo");
385 TM
->Options
.MCOptions
.SplitDwarfFile
= std::string(DwoFile
);
387 TM
->Options
.MCOptions
.SplitDwarfFile
= Conf
.SplitDwarfFile
;
389 if (!DwoFile
.empty()) {
391 DwoOut
= std::make_unique
<ToolOutputFile
>(DwoFile
, EC
, sys::fs::OF_None
);
393 report_fatal_error(Twine("Failed to open ") + DwoFile
+ ": " +
397 Expected
<std::unique_ptr
<CachedFileStream
>> StreamOrErr
=
398 AddStream(Task
, Mod
.getModuleIdentifier());
399 if (Error Err
= StreamOrErr
.takeError())
400 report_fatal_error(std::move(Err
));
401 std::unique_ptr
<CachedFileStream
> &Stream
= *StreamOrErr
;
402 TM
->Options
.ObjectFilenameForDebug
= Stream
->ObjectPathName
;
404 legacy::PassManager CodeGenPasses
;
405 TargetLibraryInfoImpl
TLII(Triple(Mod
.getTargetTriple()));
406 CodeGenPasses
.add(new TargetLibraryInfoWrapperPass(TLII
));
408 createImmutableModuleSummaryIndexWrapperPass(&CombinedIndex
));
409 if (Conf
.PreCodeGenPassesHook
)
410 Conf
.PreCodeGenPassesHook(CodeGenPasses
);
411 if (TM
->addPassesToEmitFile(CodeGenPasses
, *Stream
->OS
,
412 DwoOut
? &DwoOut
->os() : nullptr,
414 report_fatal_error("Failed to setup codegen");
415 CodeGenPasses
.run(Mod
);
421 static void splitCodeGen(const Config
&C
, TargetMachine
*TM
,
422 AddStreamFn AddStream
,
423 unsigned ParallelCodeGenParallelismLevel
, Module
&Mod
,
424 const ModuleSummaryIndex
&CombinedIndex
) {
425 ThreadPool
CodegenThreadPool(
426 heavyweight_hardware_concurrency(ParallelCodeGenParallelismLevel
));
427 unsigned ThreadCount
= 0;
428 const Target
*T
= &TM
->getTarget();
431 Mod
, ParallelCodeGenParallelismLevel
,
432 [&](std::unique_ptr
<Module
> MPart
) {
433 // We want to clone the module in a new context to multi-thread the
434 // codegen. We do it by serializing partition modules to bitcode
435 // (while still on the main thread, in order to avoid data races) and
436 // spinning up new threads which deserialize the partitions into
437 // separate contexts.
438 // FIXME: Provide a more direct way to do this in LLVM.
440 raw_svector_ostream
BCOS(BC
);
441 WriteBitcodeToFile(*MPart
, BCOS
);
444 CodegenThreadPool
.async(
445 [&](const SmallString
<0> &BC
, unsigned ThreadId
) {
446 LTOLLVMContext
Ctx(C
);
447 Expected
<std::unique_ptr
<Module
>> MOrErr
= parseBitcodeFile(
448 MemoryBufferRef(StringRef(BC
.data(), BC
.size()), "ld-temp.o"),
451 report_fatal_error("Failed to read bitcode");
452 std::unique_ptr
<Module
> MPartInCtx
= std::move(MOrErr
.get());
454 std::unique_ptr
<TargetMachine
> TM
=
455 createTargetMachine(C
, T
, *MPartInCtx
);
457 codegen(C
, TM
.get(), AddStream
, ThreadId
, *MPartInCtx
,
460 // Pass BC using std::move to ensure that it get moved rather than
461 // copied into the thread's context.
462 std::move(BC
), ThreadCount
++);
466 // Because the inner lambda (which runs in a worker thread) captures our local
467 // variables, we need to wait for the worker threads to terminate before we
468 // can leave the function scope.
469 CodegenThreadPool
.wait();
472 static Expected
<const Target
*> initAndLookupTarget(const Config
&C
,
474 if (!C
.OverrideTriple
.empty())
475 Mod
.setTargetTriple(C
.OverrideTriple
);
476 else if (Mod
.getTargetTriple().empty())
477 Mod
.setTargetTriple(C
.DefaultTriple
);
480 const Target
*T
= TargetRegistry::lookupTarget(Mod
.getTargetTriple(), Msg
);
482 return make_error
<StringError
>(Msg
, inconvertibleErrorCode());
486 Error
lto::finalizeOptimizationRemarks(
487 std::unique_ptr
<ToolOutputFile
> DiagOutputFile
) {
488 // Make sure we flush the diagnostic remarks file in case the linker doesn't
489 // call the global destructors before exiting.
491 return Error::success();
492 DiagOutputFile
->keep();
493 DiagOutputFile
->os().flush();
494 return Error::success();
497 Error
lto::backend(const Config
&C
, AddStreamFn AddStream
,
498 unsigned ParallelCodeGenParallelismLevel
, Module
&Mod
,
499 ModuleSummaryIndex
&CombinedIndex
) {
500 Expected
<const Target
*> TOrErr
= initAndLookupTarget(C
, Mod
);
502 return TOrErr
.takeError();
504 std::unique_ptr
<TargetMachine
> TM
= createTargetMachine(C
, *TOrErr
, Mod
);
506 if (!C
.CodeGenOnly
) {
507 if (!opt(C
, TM
.get(), 0, Mod
, /*IsThinLTO=*/false,
508 /*ExportSummary=*/&CombinedIndex
, /*ImportSummary=*/nullptr,
509 /*CmdArgs*/ std::vector
<uint8_t>()))
510 return Error::success();
513 if (ParallelCodeGenParallelismLevel
== 1) {
514 codegen(C
, TM
.get(), AddStream
, 0, Mod
, CombinedIndex
);
516 splitCodeGen(C
, TM
.get(), AddStream
, ParallelCodeGenParallelismLevel
, Mod
,
519 return Error::success();
522 static void dropDeadSymbols(Module
&Mod
, const GVSummaryMapTy
&DefinedGlobals
,
523 const ModuleSummaryIndex
&Index
) {
524 std::vector
<GlobalValue
*> DeadGVs
;
525 for (auto &GV
: Mod
.global_values())
526 if (GlobalValueSummary
*GVS
= DefinedGlobals
.lookup(GV
.getGUID()))
527 if (!Index
.isGlobalValueLive(GVS
)) {
528 DeadGVs
.push_back(&GV
);
529 convertToDeclaration(GV
);
532 // Now that all dead bodies have been dropped, delete the actual objects
533 // themselves when possible.
534 for (GlobalValue
*GV
: DeadGVs
) {
535 GV
->removeDeadConstantUsers();
536 // Might reference something defined in native object (i.e. dropped a
537 // non-prevailing IR def, but we need to keep the declaration).
539 GV
->eraseFromParent();
543 Error
lto::thinBackend(const Config
&Conf
, unsigned Task
, AddStreamFn AddStream
,
544 Module
&Mod
, const ModuleSummaryIndex
&CombinedIndex
,
545 const FunctionImporter::ImportMapTy
&ImportList
,
546 const GVSummaryMapTy
&DefinedGlobals
,
547 MapVector
<StringRef
, BitcodeModule
> *ModuleMap
,
548 const std::vector
<uint8_t> &CmdArgs
) {
549 Expected
<const Target
*> TOrErr
= initAndLookupTarget(Conf
, Mod
);
551 return TOrErr
.takeError();
553 std::unique_ptr
<TargetMachine
> TM
= createTargetMachine(Conf
, *TOrErr
, Mod
);
555 // Setup optimization remarks.
556 auto DiagFileOrErr
= lto::setupLLVMOptimizationRemarks(
557 Mod
.getContext(), Conf
.RemarksFilename
, Conf
.RemarksPasses
,
558 Conf
.RemarksFormat
, Conf
.RemarksWithHotness
, Conf
.RemarksHotnessThreshold
,
561 return DiagFileOrErr
.takeError();
562 auto DiagnosticOutputFile
= std::move(*DiagFileOrErr
);
564 // Set the partial sample profile ratio in the profile summary module flag of
565 // the module, if applicable.
566 Mod
.setPartialSampleProfileRatio(CombinedIndex
);
568 if (Conf
.CodeGenOnly
) {
569 codegen(Conf
, TM
.get(), AddStream
, Task
, Mod
, CombinedIndex
);
570 return finalizeOptimizationRemarks(std::move(DiagnosticOutputFile
));
573 if (Conf
.PreOptModuleHook
&& !Conf
.PreOptModuleHook(Task
, Mod
))
574 return finalizeOptimizationRemarks(std::move(DiagnosticOutputFile
));
576 auto OptimizeAndCodegen
=
577 [&](Module
&Mod
, TargetMachine
*TM
,
578 std::unique_ptr
<ToolOutputFile
> DiagnosticOutputFile
) {
579 if (!opt(Conf
, TM
, Task
, Mod
, /*IsThinLTO=*/true,
580 /*ExportSummary=*/nullptr, /*ImportSummary=*/&CombinedIndex
,
582 return finalizeOptimizationRemarks(std::move(DiagnosticOutputFile
));
584 codegen(Conf
, TM
, AddStream
, Task
, Mod
, CombinedIndex
);
585 return finalizeOptimizationRemarks(std::move(DiagnosticOutputFile
));
588 if (ThinLTOAssumeMerged
)
589 return OptimizeAndCodegen(Mod
, TM
.get(), std::move(DiagnosticOutputFile
));
591 // When linking an ELF shared object, dso_local should be dropped. We
592 // conservatively do this for -fpic.
593 bool ClearDSOLocalOnDeclarations
=
594 TM
->getTargetTriple().isOSBinFormatELF() &&
595 TM
->getRelocationModel() != Reloc::Static
&&
596 Mod
.getPIELevel() == PIELevel::Default
;
597 renameModuleForThinLTO(Mod
, CombinedIndex
, ClearDSOLocalOnDeclarations
);
599 dropDeadSymbols(Mod
, DefinedGlobals
, CombinedIndex
);
601 thinLTOFinalizeInModule(Mod
, DefinedGlobals
, /*PropagateAttrs=*/true);
603 if (Conf
.PostPromoteModuleHook
&& !Conf
.PostPromoteModuleHook(Task
, Mod
))
604 return finalizeOptimizationRemarks(std::move(DiagnosticOutputFile
));
606 if (!DefinedGlobals
.empty())
607 thinLTOInternalizeModule(Mod
, DefinedGlobals
);
609 if (Conf
.PostInternalizeModuleHook
&&
610 !Conf
.PostInternalizeModuleHook(Task
, Mod
))
611 return finalizeOptimizationRemarks(std::move(DiagnosticOutputFile
));
613 auto ModuleLoader
= [&](StringRef Identifier
) {
614 assert(Mod
.getContext().isODRUniquingDebugTypes() &&
615 "ODR Type uniquing should be enabled on the context");
617 auto I
= ModuleMap
->find(Identifier
);
618 assert(I
!= ModuleMap
->end());
619 return I
->second
.getLazyModule(Mod
.getContext(),
620 /*ShouldLazyLoadMetadata=*/true,
621 /*IsImporting*/ true);
624 ErrorOr
<std::unique_ptr
<llvm::MemoryBuffer
>> MBOrErr
=
625 llvm::MemoryBuffer::getFile(Identifier
);
627 return Expected
<std::unique_ptr
<llvm::Module
>>(make_error
<StringError
>(
628 Twine("Error loading imported file ") + Identifier
+ " : ",
629 MBOrErr
.getError()));
631 Expected
<BitcodeModule
> BMOrErr
= findThinLTOModule(**MBOrErr
);
633 return Expected
<std::unique_ptr
<llvm::Module
>>(make_error
<StringError
>(
634 Twine("Error loading imported file ") + Identifier
+ " : " +
635 toString(BMOrErr
.takeError()),
636 inconvertibleErrorCode()));
638 Expected
<std::unique_ptr
<Module
>> MOrErr
=
639 BMOrErr
->getLazyModule(Mod
.getContext(),
640 /*ShouldLazyLoadMetadata=*/true,
641 /*IsImporting*/ true);
643 (*MOrErr
)->setOwnedMemoryBuffer(std::move(*MBOrErr
));
647 FunctionImporter
Importer(CombinedIndex
, ModuleLoader
,
648 ClearDSOLocalOnDeclarations
);
649 if (Error Err
= Importer
.importFunctions(Mod
, ImportList
).takeError())
652 // Do this after any importing so that imported code is updated.
653 updateMemProfAttributes(Mod
, CombinedIndex
);
654 updatePublicTypeTestCalls(Mod
, CombinedIndex
.withWholeProgramVisibility());
656 if (Conf
.PostImportModuleHook
&& !Conf
.PostImportModuleHook(Task
, Mod
))
657 return finalizeOptimizationRemarks(std::move(DiagnosticOutputFile
));
659 return OptimizeAndCodegen(Mod
, TM
.get(), std::move(DiagnosticOutputFile
));
662 BitcodeModule
*lto::findThinLTOModule(MutableArrayRef
<BitcodeModule
> BMs
) {
663 if (ThinLTOAssumeMerged
&& BMs
.size() == 1)
666 for (BitcodeModule
&BM
: BMs
) {
667 Expected
<BitcodeLTOInfo
> LTOInfo
= BM
.getLTOInfo();
668 if (LTOInfo
&& LTOInfo
->IsThinLTO
)
674 Expected
<BitcodeModule
> lto::findThinLTOModule(MemoryBufferRef MBRef
) {
675 Expected
<std::vector
<BitcodeModule
>> BMsOrErr
= getBitcodeModuleList(MBRef
);
677 return BMsOrErr
.takeError();
679 // The bitcode file may contain multiple modules, we want the one that is
680 // marked as being the ThinLTO module.
681 if (const BitcodeModule
*Bm
= lto::findThinLTOModule(*BMsOrErr
))
684 return make_error
<StringError
>("Could not find module summary",
685 inconvertibleErrorCode());
688 bool lto::initImportList(const Module
&M
,
689 const ModuleSummaryIndex
&CombinedIndex
,
690 FunctionImporter::ImportMapTy
&ImportList
) {
691 if (ThinLTOAssumeMerged
)
693 // We can simply import the values mentioned in the combined index, since
694 // we should only invoke this using the individual indexes written out
695 // via a WriteIndexesThinBackend.
696 for (const auto &GlobalList
: CombinedIndex
) {
697 // Ignore entries for undefined references.
698 if (GlobalList
.second
.SummaryList
.empty())
701 auto GUID
= GlobalList
.first
;
702 for (const auto &Summary
: GlobalList
.second
.SummaryList
) {
703 // Skip the summaries for the importing module. These are included to
704 // e.g. record required linkage changes.
705 if (Summary
->modulePath() == M
.getModuleIdentifier())
707 // Add an entry to provoke importing by thinBackend.
708 ImportList
[Summary
->modulePath()].insert(GUID
);