1//===-LTOCodeGenerator.cpp - LLVM Link Time Optimizer ---------------------===//
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 Link Time Optimization library. This library is
10// intended to be used by linker to optimize code at link time.
11//
12//===----------------------------------------------------------------------===//
13
14#include "llvm/LTO/legacy/LTOCodeGenerator.h"
15
16#include "llvm/ADT/Statistic.h"
17#include "llvm/ADT/StringExtras.h"
18#include "llvm/Analysis/TargetLibraryInfo.h"
19#include "llvm/Analysis/TargetTransformInfo.h"
20#include "llvm/Bitcode/BitcodeWriter.h"
21#include "llvm/CodeGen/CommandFlags.h"
22#include "llvm/CodeGen/TargetSubtargetInfo.h"
23#include "llvm/Config/config.h"
24#include "llvm/IR/DataLayout.h"
25#include "llvm/IR/DebugInfo.h"
26#include "llvm/IR/DerivedTypes.h"
27#include "llvm/IR/DiagnosticInfo.h"
28#include "llvm/IR/DiagnosticPrinter.h"
29#include "llvm/IR/LLVMContext.h"
30#include "llvm/IR/LLVMRemarkStreamer.h"
31#include "llvm/IR/LegacyPassManager.h"
32#include "llvm/IR/Mangler.h"
33#include "llvm/IR/Module.h"
34#include "llvm/IR/PassTimingInfo.h"
35#include "llvm/IR/Verifier.h"
36#include "llvm/LTO/LTO.h"
37#include "llvm/LTO/LTOBackend.h"
38#include "llvm/LTO/legacy/LTOModule.h"
39#include "llvm/LTO/legacy/UpdateCompilerUsed.h"
40#include "llvm/Linker/Linker.h"
41#include "llvm/MC/TargetRegistry.h"
42#include "llvm/Remarks/HotnessThresholdParser.h"
43#include "llvm/Support/CommandLine.h"
44#include "llvm/Support/FileSystem.h"
45#include "llvm/Support/MemoryBuffer.h"
46#include "llvm/Support/Process.h"
47#include "llvm/Support/Signals.h"
48#include "llvm/Support/ToolOutputFile.h"
49#include "llvm/Support/raw_ostream.h"
50#include "llvm/Target/TargetOptions.h"
51#include "llvm/TargetParser/Host.h"
52#include "llvm/TargetParser/SubtargetFeature.h"
53#include "llvm/Transforms/IPO.h"
54#include "llvm/Transforms/IPO/Internalize.h"
55#include "llvm/Transforms/IPO/WholeProgramDevirt.h"
56#include "llvm/Transforms/Utils/ModuleUtils.h"
57#include <optional>
58#include <system_error>
59using namespace llvm;
60
61const char* LTOCodeGenerator::getVersionString() {
62 return PACKAGE_NAME " version " PACKAGE_VERSION;
63}
64
65namespace llvm {
66cl::opt<bool> LTODiscardValueNames(
67 "lto-discard-value-names",
68 cl::desc("Strip names from Value during LTO (other than GlobalValue)."),
69#ifdef NDEBUG
70 cl::init(Val: true),
71#else
72 cl::init(false),
73#endif
74 cl::Hidden);
75
76cl::opt<bool> RemarksWithHotness(
77 "lto-pass-remarks-with-hotness",
78 cl::desc("With PGO, include profile count in optimization remarks"),
79 cl::Hidden);
80
81cl::opt<std::optional<uint64_t>, false, remarks::HotnessThresholdParser>
82 RemarksHotnessThreshold(
83 "lto-pass-remarks-hotness-threshold",
84 cl::desc("Minimum profile count required for an "
85 "optimization remark to be output."
86 " Use 'auto' to apply the threshold from profile summary."),
87 cl::value_desc("uint or 'auto'"), cl::init(Val: 0), cl::Hidden);
88
89cl::opt<std::string>
90 RemarksFilename("lto-pass-remarks-output",
91 cl::desc("Output filename for pass remarks"),
92 cl::value_desc("filename"));
93
94cl::opt<std::string>
95 RemarksPasses("lto-pass-remarks-filter",
96 cl::desc("Only record optimization remarks from passes whose "
97 "names match the given regular expression"),
98 cl::value_desc("regex"));
99
100cl::opt<std::string> RemarksFormat(
101 "lto-pass-remarks-format",
102 cl::desc("The format used for serializing remarks (default: YAML)"),
103 cl::value_desc("format"), cl::init(Val: "yaml"));
104
105static cl::opt<std::string>
106 LTOStatsFile("lto-stats-file",
107 cl::desc("Save statistics to the specified file"), cl::Hidden);
108
109static cl::opt<std::string> AIXSystemAssemblerPath(
110 "lto-aix-system-assembler",
111 cl::desc("Path to a system assembler, picked up on AIX only"),
112 cl::value_desc("path"));
113
114cl::opt<bool>
115 LTORunCSIRInstr("cs-profile-generate",
116 cl::desc("Perform context sensitive PGO instrumentation"));
117
118cl::opt<std::string>
119 LTOCSIRProfile("cs-profile-path",
120 cl::desc("Context sensitive profile file path"));
121
122extern cl::opt<std::string> SampleProfileFile;
123} // namespace llvm
124
125LTOCodeGenerator::LTOCodeGenerator(LLVMContext &Context)
126 : Context(Context), MergedModule(new Module("ld-temp.o", Context)),
127 TheLinker(new Linker(*MergedModule)) {
128 Context.setDiscardValueNames(LTODiscardValueNames);
129 Context.enableDebugTypeODRUniquing();
130
131 Config.LibraryOptions = &Context.getLibraryOptions();
132 Config.CodeModel = std::nullopt;
133 Config.StatsFile = LTOStatsFile;
134 Config.RunCSIRInstr = LTORunCSIRInstr;
135 Config.CSIRProfile = LTOCSIRProfile;
136}
137
138LTOCodeGenerator::~LTOCodeGenerator() = default;
139
140void LTOCodeGenerator::setAsmUndefinedRefs(LTOModule *Mod) {
141 AsmUndefinedRefs.insert_range(R: Mod->getAsmUndefinedRefs());
142}
143
144bool LTOCodeGenerator::addModule(LTOModule *Mod) {
145 assert(&Mod->getModule().getContext() == &Context &&
146 "Expected module in same context");
147
148 bool ret = TheLinker->linkInModule(Src: Mod->takeModule());
149 setAsmUndefinedRefs(Mod);
150
151 // We've just changed the input, so let's make sure we verify it.
152 HasVerifiedInput = false;
153
154 return !ret;
155}
156
157void LTOCodeGenerator::setModule(std::unique_ptr<LTOModule> Mod) {
158 assert(&Mod->getModule().getContext() == &Context &&
159 "Expected module in same context");
160
161 AsmUndefinedRefs.clear();
162
163 MergedModule = Mod->takeModule();
164 TheLinker = std::make_unique<Linker>(args&: *MergedModule);
165 setAsmUndefinedRefs(&*Mod);
166
167 // We've just changed the input, so let's make sure we verify it.
168 HasVerifiedInput = false;
169}
170
171void LTOCodeGenerator::setTargetOptions(const TargetOptions &Options) {
172 Config.Options = Options;
173}
174
175void LTOCodeGenerator::setDebugInfo(lto_debug_model Debug) {
176 switch (Debug) {
177 case LTO_DEBUG_MODEL_NONE:
178 EmitDwarfDebugInfo = false;
179 return;
180
181 case LTO_DEBUG_MODEL_DWARF:
182 EmitDwarfDebugInfo = true;
183 return;
184 }
185 llvm_unreachable("Unknown debug format!");
186}
187
188void LTOCodeGenerator::setOptLevel(unsigned Level) {
189 Config.OptLevel = Level;
190 std::optional<CodeGenOptLevel> CGOptLevelOrNone =
191 CodeGenOpt::getLevel(OL: Config.OptLevel);
192 assert(CGOptLevelOrNone && "Unknown optimization level!");
193 Config.CGOptLevel = *CGOptLevelOrNone;
194}
195
196bool LTOCodeGenerator::writeMergedModules(StringRef Path) {
197 if (!determineTarget())
198 return false;
199
200 // We always run the verifier once on the merged module.
201 verifyMergedModuleOnce();
202
203 // mark which symbols can not be internalized
204 applyScopeRestrictions();
205
206 // create output file
207 std::error_code EC;
208 ToolOutputFile Out(Path, EC, sys::fs::OF_None);
209 if (EC) {
210 std::string ErrMsg = "could not open bitcode file for writing: ";
211 ErrMsg += Path.str() + ": " + EC.message();
212 emitError(ErrMsg);
213 return false;
214 }
215
216 // write bitcode to it
217 WriteBitcodeToFile(M: *MergedModule, Out&: Out.os(), ShouldPreserveUseListOrder: ShouldEmbedUselists);
218 Out.os().close();
219
220 if (Out.os().has_error()) {
221 std::string ErrMsg = "could not write bitcode file: ";
222 ErrMsg += Path.str() + ": " + Out.os().error().message();
223 emitError(ErrMsg);
224 Out.os().clear_error();
225 return false;
226 }
227
228 Out.keep();
229 return true;
230}
231
232bool LTOCodeGenerator::useAIXSystemAssembler() {
233 const auto &Triple = TargetMach->getTargetTriple();
234 return Triple.isOSAIX() && Config.Options.MCOptions.DisableIntegratedAS;
235}
236
237bool LTOCodeGenerator::runAIXSystemAssembler(SmallString<128> &AssemblyFile) {
238 assert(useAIXSystemAssembler() &&
239 "Runing AIX system assembler when integrated assembler is available!");
240
241 // Set the system assembler path.
242 SmallString<256> AssemblerPath("/usr/bin/as");
243 if (!llvm::AIXSystemAssemblerPath.empty()) {
244 if (llvm::sys::fs::real_path(path: llvm::AIXSystemAssemblerPath, output&: AssemblerPath,
245 /* expand_tilde */ true)) {
246 emitError(
247 ErrMsg: "Cannot find the assembler specified by lto-aix-system-assembler");
248 return false;
249 }
250 }
251
252 // Setup the LDR_CNTRL variable
253 std::string LDR_CNTRL_var = "LDR_CNTRL=MAXDATA32=0xA0000000@DSA";
254 if (std::optional<std::string> V = sys::Process::GetEnv(name: "LDR_CNTRL"))
255 LDR_CNTRL_var += ("@" + *V);
256
257 // Prepare inputs for the assember.
258 const auto &Triple = TargetMach->getTargetTriple();
259 const char *Arch = Triple.isArch64Bit() ? "-a64" : "-a32";
260 std::string ObjectFileName(AssemblyFile);
261 ObjectFileName[ObjectFileName.size() - 1] = 'o';
262 SmallVector<StringRef, 8> Args = {
263 "/bin/env", LDR_CNTRL_var,
264 AssemblerPath, Arch,
265 "-many", "-o",
266 ObjectFileName, AssemblyFile};
267
268 // Invoke the assembler.
269 int RC = sys::ExecuteAndWait(Program: Args[0], Args);
270
271 // Handle errors.
272 if (RC < -1) {
273 emitError(ErrMsg: "LTO assembler exited abnormally");
274 return false;
275 }
276 if (RC < 0) {
277 emitError(ErrMsg: "Unable to invoke LTO assembler");
278 return false;
279 }
280 if (RC > 0) {
281 emitError(ErrMsg: "LTO assembler invocation returned non-zero");
282 return false;
283 }
284
285 // Cleanup.
286 remove(filename: AssemblyFile.c_str());
287
288 // Fix the output file name.
289 AssemblyFile = ObjectFileName;
290
291 return true;
292}
293
294bool LTOCodeGenerator::compileOptimizedToFile(const char **Name) {
295 if (useAIXSystemAssembler())
296 setFileType(CodeGenFileType::AssemblyFile);
297
298 // make unique temp output file to put generated code
299 SmallString<128> Filename;
300
301 auto AddStream =
302 [&](size_t Task,
303 const Twine &ModuleName) -> std::unique_ptr<CachedFileStream> {
304 StringRef Extension(
305 Config.CGFileType == CodeGenFileType::AssemblyFile ? "s" : "o");
306
307 int FD;
308 std::error_code EC =
309 sys::fs::createTemporaryFile(Prefix: "lto-llvm", Suffix: Extension, ResultFD&: FD, ResultPath&: Filename);
310 if (EC)
311 emitError(ErrMsg: EC.message());
312
313 return std::make_unique<CachedFileStream>(
314 args: std::make_unique<llvm::raw_fd_ostream>(args&: FD, args: true));
315 };
316
317 bool genResult = compileOptimized(AddStream, ParallelismLevel: 1);
318
319 if (!genResult) {
320 sys::fs::remove(path: Twine(Filename));
321 return false;
322 }
323
324 // If statistics were requested, save them to the specified file or
325 // print them out after codegen.
326 if (StatsFile)
327 PrintStatisticsJSON(OS&: StatsFile->os());
328 else if (AreStatisticsEnabled())
329 PrintStatistics();
330
331 if (useAIXSystemAssembler())
332 if (!runAIXSystemAssembler(AssemblyFile&: Filename))
333 return false;
334
335 NativeObjectPath = Filename.c_str();
336 *Name = NativeObjectPath.c_str();
337 return true;
338}
339
340std::unique_ptr<MemoryBuffer>
341LTOCodeGenerator::compileOptimized() {
342 const char *name;
343 if (!compileOptimizedToFile(Name: &name))
344 return nullptr;
345
346 // read .o file into memory buffer
347 ErrorOr<std::unique_ptr<MemoryBuffer>> BufferOrErr = MemoryBuffer::getFile(
348 Filename: name, /*IsText=*/false, /*RequiresNullTerminator=*/false);
349 if (std::error_code EC = BufferOrErr.getError()) {
350 emitError(ErrMsg: EC.message());
351 sys::fs::remove(path: NativeObjectPath);
352 return nullptr;
353 }
354
355 // remove temp files
356 sys::fs::remove(path: NativeObjectPath);
357
358 return std::move(*BufferOrErr);
359}
360
361bool LTOCodeGenerator::compile_to_file(const char **Name) {
362 if (!optimize())
363 return false;
364
365 return compileOptimizedToFile(Name);
366}
367
368std::unique_ptr<MemoryBuffer> LTOCodeGenerator::compile() {
369 if (!optimize())
370 return nullptr;
371
372 return compileOptimized();
373}
374
375bool LTOCodeGenerator::determineTarget() {
376 if (TargetMach)
377 return true;
378
379 if (MergedModule->getTargetTriple().empty())
380 MergedModule->setTargetTriple(Triple(sys::getDefaultTargetTriple()));
381
382 // create target machine from info for merged modules
383 std::string ErrMsg;
384 MArch = TargetRegistry::lookupTarget(TheTriple: MergedModule->getTargetTriple(), Error&: ErrMsg);
385 if (!MArch) {
386 emitError(ErrMsg);
387 return false;
388 }
389
390 // Construct LTOModule, hand over ownership of module and target. Use MAttr as
391 // the default set of features.
392 SubtargetFeatures Features(join(R&: Config.MAttrs, Separator: ""));
393 Features.getDefaultSubtargetFeatures(Triple: MergedModule->getTargetTriple());
394 FeatureStr = Features.getString();
395 if (Config.CPU.empty())
396 Config.CPU = lto::getThinLTODefaultCPU(TheTriple: MergedModule->getTargetTriple());
397
398 // If data-sections is not explicitly set or unset, set data-sections by
399 // default to match the behaviour of lld and gold plugin.
400 if (!codegen::getExplicitDataSections())
401 Config.Options.DataSections = true;
402
403 TargetMach = createTargetMachine();
404 assert(TargetMach && "Unable to create target machine");
405
406 return true;
407}
408
409std::unique_ptr<TargetMachine> LTOCodeGenerator::createTargetMachine() {
410 assert(MArch && "MArch is not set!");
411 TargetOptions Options = Config.Options;
412 Options.MCOptions.LibraryOptions = Config.LibraryOptions;
413 return std::unique_ptr<TargetMachine>(MArch->createTargetMachine(
414 TT: MergedModule->getTargetTriple(), CPU: Config.CPU, Features: FeatureStr, Options,
415 RM: Config.RelocModel, CM: std::nullopt, OL: Config.CGOptLevel));
416}
417
418// If a linkonce global is present in the MustPreserveSymbols, we need to make
419// sure we honor this. To force the compiler to not drop it, we add it to the
420// "llvm.compiler.used" global.
421void LTOCodeGenerator::preserveDiscardableGVs(
422 Module &TheModule,
423 llvm::function_ref<bool(const GlobalValue &)> mustPreserveGV) {
424 std::vector<GlobalValue *> Used;
425 auto mayPreserveGlobal = [&](GlobalValue &GV) {
426 if (!GV.isDiscardableIfUnused() || GV.isDeclaration() ||
427 !mustPreserveGV(GV))
428 return;
429 if (GV.hasAvailableExternallyLinkage())
430 return emitWarning(
431 ErrMsg: (Twine("Linker asked to preserve available_externally global: '") +
432 GV.getName() + "'").str());
433 if (GV.hasInternalLinkage())
434 return emitWarning(ErrMsg: (Twine("Linker asked to preserve internal global: '") +
435 GV.getName() + "'").str());
436 Used.push_back(x: &GV);
437 };
438 for (auto &GV : TheModule)
439 mayPreserveGlobal(GV);
440 for (auto &GV : TheModule.globals())
441 mayPreserveGlobal(GV);
442 for (auto &GV : TheModule.aliases())
443 mayPreserveGlobal(GV);
444
445 if (Used.empty())
446 return;
447
448 appendToCompilerUsed(M&: TheModule, Values: Used);
449}
450
451void LTOCodeGenerator::applyScopeRestrictions() {
452 if (ScopeRestrictionsDone)
453 return;
454
455 // Declare a callback for the internalize pass that will ask for every
456 // candidate GlobalValue if it can be internalized or not.
457 Mangler Mang;
458 SmallString<64> MangledName;
459 auto mustPreserveGV = [&](const GlobalValue &GV) -> bool {
460 // Unnamed globals can't be mangled, but they can't be preserved either.
461 if (!GV.hasName())
462 return false;
463
464 // Need to mangle the GV as the "MustPreserveSymbols" StringSet is filled
465 // with the linker supplied name, which on Darwin includes a leading
466 // underscore.
467 MangledName.clear();
468 MangledName.reserve(N: GV.getName().size() + 1);
469 Mang.getNameWithPrefix(OutName&: MangledName, GV: &GV, /*CannotUsePrivateLabel=*/false);
470 return MustPreserveSymbols.count(Key: MangledName);
471 };
472
473 // Preserve linkonce value on linker request
474 preserveDiscardableGVs(TheModule&: *MergedModule, mustPreserveGV);
475
476 if (!ShouldInternalize)
477 return;
478
479 if (ShouldRestoreGlobalsLinkage) {
480 // Record the linkage type of non-local symbols so they can be restored
481 // prior
482 // to module splitting.
483 auto RecordLinkage = [&](const GlobalValue &GV) {
484 if (!GV.hasAvailableExternallyLinkage() && !GV.hasLocalLinkage() &&
485 GV.hasName())
486 ExternalSymbols.insert(KV: std::make_pair(x: GV.getName(), y: GV.getLinkage()));
487 };
488 for (auto &GV : *MergedModule)
489 RecordLinkage(GV);
490 for (auto &GV : MergedModule->globals())
491 RecordLinkage(GV);
492 for (auto &GV : MergedModule->aliases())
493 RecordLinkage(GV);
494 }
495
496 // Update the llvm.compiler_used globals to force preserving libcalls and
497 // symbols referenced from asm
498 updateCompilerUsed(TheModule&: *MergedModule, TM: *TargetMach, AsmUndefinedRefs);
499
500 internalizeModule(TheModule&: *MergedModule, MustPreserveGV: mustPreserveGV);
501
502 ScopeRestrictionsDone = true;
503}
504
505/// Restore original linkage for symbols that may have been internalized
506void LTOCodeGenerator::restoreLinkageForExternals() {
507 if (!ShouldInternalize || !ShouldRestoreGlobalsLinkage)
508 return;
509
510 assert(ScopeRestrictionsDone &&
511 "Cannot externalize without internalization!");
512
513 if (ExternalSymbols.empty())
514 return;
515
516 auto externalize = [this](GlobalValue &GV) {
517 if (!GV.hasLocalLinkage() || !GV.hasName())
518 return;
519
520 auto I = ExternalSymbols.find(Key: GV.getName());
521 if (I == ExternalSymbols.end())
522 return;
523
524 GV.setLinkage(I->second);
525 };
526
527 llvm::for_each(Range: MergedModule->functions(), F: externalize);
528 llvm::for_each(Range: MergedModule->globals(), F: externalize);
529 llvm::for_each(Range: MergedModule->aliases(), F: externalize);
530}
531
532void LTOCodeGenerator::verifyMergedModuleOnce() {
533 // Only run on the first call.
534 if (HasVerifiedInput)
535 return;
536 HasVerifiedInput = true;
537
538 bool BrokenDebugInfo = false;
539 if (verifyModule(M: *MergedModule, OS: &dbgs(), BrokenDebugInfo: &BrokenDebugInfo))
540 report_fatal_error(reason: "Broken module found, compilation aborted!");
541 if (BrokenDebugInfo) {
542 emitWarning(ErrMsg: "Invalid debug info found, debug info will be stripped");
543 StripDebugInfo(M&: *MergedModule);
544 }
545}
546
547void LTOCodeGenerator::finishOptimizationRemarks() {
548 if (DiagnosticOutputFile) {
549 DiagnosticOutputFile->keep();
550 // FIXME: LTOCodeGenerator dtor is not invoked on Darwin
551 DiagnosticOutputFile.finalize();
552 DiagnosticOutputFile->os().flush();
553 }
554}
555
556/// Optimize merged modules using various IPO passes
557bool LTOCodeGenerator::optimize() {
558 if (!this->determineTarget())
559 return false;
560
561 // libLTO parses options late, so re-set them here.
562 Context.setDiscardValueNames(LTODiscardValueNames);
563 Config.StatsFile = LTOStatsFile;
564 Config.RunCSIRInstr = LTORunCSIRInstr;
565 Config.CSIRProfile = LTOCSIRProfile;
566 Config.SampleProfile = SampleProfileFile;
567 Config.PTO = PipelineTuningOptions(Config.LibraryOptions);
568 Config.PTO.LoopVectorization = Config.OptLevel > 1;
569 Config.PTO.SLPVectorization = Config.OptLevel > 1;
570
571 auto DiagFileOrErr = lto::setupLLVMOptimizationRemarks(
572 Context, RemarksFilename, RemarksPasses, RemarksFormat,
573 RemarksWithHotness, RemarksHotnessThreshold);
574 if (!DiagFileOrErr) {
575 errs() << "Error: " << toString(E: DiagFileOrErr.takeError()) << "\n";
576 report_fatal_error(reason: "Can't get an output file for the remarks");
577 }
578 DiagnosticOutputFile = std::move(*DiagFileOrErr);
579
580 // Setup output file to emit statistics.
581 auto StatsFileOrErr = lto::setupStatsFile(LTOStatsFile);
582 if (!StatsFileOrErr) {
583 errs() << "Error: " << toString(E: StatsFileOrErr.takeError()) << "\n";
584 report_fatal_error(reason: "Can't get an output file for the statistics");
585 }
586 StatsFile = std::move(StatsFileOrErr.get());
587
588 // Currently there is no support for enabling whole program visibility via a
589 // linker option in the old LTO API, but this call allows it to be specified
590 // via the internal option. Must be done before WPD invoked via the optimizer
591 // pipeline run below.
592 updatePublicTypeTestCalls(M&: *MergedModule,
593 /* WholeProgramVisibilityEnabledInLTO */ false);
594 updateVCallVisibilityInModule(
595 M&: *MergedModule,
596 /* WholeProgramVisibilityEnabledInLTO */ false,
597 // FIXME: These need linker information via a
598 // TBD new interface.
599 /*DynamicExportSymbols=*/{},
600 /*ValidateAllVtablesHaveTypeInfos=*/false,
601 /*IsVisibleToRegularObj=*/[](StringRef) { return true; });
602
603 // We always run the verifier once on the merged module, the `DisableVerify`
604 // parameter only applies to subsequent verify.
605 verifyMergedModuleOnce();
606
607 // Mark which symbols can not be internalized
608 this->applyScopeRestrictions();
609
610 // Seed a DataLayout only if the merged module does not already carry one, so
611 // an input module's own DataLayout is preserved. Compute it from the module's
612 // ABI so the target-abi module flag is respected.
613 if (MergedModule->getDataLayout().isDefault()) {
614 MergedModule->setDataLayout(
615 MergedModule->getTargetTriple().computeDataLayout(
616 ABIName: TargetMach->getTargetABIName(M: *MergedModule)));
617 }
618
619 if (!SaveIRBeforeOptPath.empty()) {
620 std::error_code EC;
621 raw_fd_ostream OS(SaveIRBeforeOptPath, EC, sys::fs::OF_None);
622 if (EC)
623 report_fatal_error(reason: Twine("Failed to open ") + SaveIRBeforeOptPath +
624 " to save optimized bitcode\n");
625 WriteBitcodeToFile(M: *MergedModule, Out&: OS,
626 /* ShouldPreserveUseListOrder */ true);
627 }
628
629 ModuleSummaryIndex CombinedIndex(false);
630 TargetMach = createTargetMachine();
631 if (!opt(Conf: Config, TM: TargetMach.get(), Task: 0, Mod&: *MergedModule, /*IsThinLTO=*/false,
632 /*ExportSummary=*/&CombinedIndex, /*ImportSummary=*/nullptr,
633 /*CmdArgs*/ std::vector<uint8_t>(), /*BitcodeLibFuncs=*/{})) {
634 emitError(ErrMsg: "LTO middle-end optimizations failed");
635 return false;
636 }
637
638 return true;
639}
640
641bool LTOCodeGenerator::compileOptimized(AddStreamFn AddStream,
642 unsigned ParallelismLevel) {
643 if (!this->determineTarget())
644 return false;
645
646 // We always run the verifier once on the merged module. If it has already
647 // been called in optimize(), this call will return early.
648 verifyMergedModuleOnce();
649
650 // Re-externalize globals that may have been internalized to increase scope
651 // for splitting
652 restoreLinkageForExternals();
653
654 ModuleSummaryIndex CombinedIndex(false);
655
656 Config.CodeGenOnly = true;
657 Error Err = backend(C: Config, AddStream, ParallelCodeGenParallelismLevel: ParallelismLevel, M&: *MergedModule,
658 CombinedIndex, /*BitcodeLibFuncs=*/{});
659 assert(!Err && "unexpected code-generation failure");
660 (void)Err;
661
662 // If statistics were requested, save them to the specified file or
663 // print them out after codegen.
664 if (StatsFile)
665 PrintStatisticsJSON(OS&: StatsFile->os());
666 else if (AreStatisticsEnabled())
667 PrintStatistics();
668
669 reportAndResetTimings();
670
671 finishOptimizationRemarks();
672
673 return true;
674}
675
676void LTOCodeGenerator::setCodeGenDebugOptions(ArrayRef<StringRef> Options) {
677 for (StringRef Option : Options)
678 CodegenOptions.push_back(x: Option.str());
679}
680
681void LTOCodeGenerator::parseCodeGenDebugOptions() {
682 if (!CodegenOptions.empty()) {
683 // ParseCommandLineOptions() expects argv[0] to be program name.
684 std::vector<const char *> CodegenArgv(1, "libLLVMLTO");
685 for (std::string &Arg : CodegenOptions)
686 CodegenArgv.push_back(x: Arg.c_str());
687 cl::parseCommandLineOptions(Context&: Context.getLibraryOptions(), Args: CodegenArgv);
688 }
689}
690
691void LTOCodeGenerator::DiagnosticHandler(const DiagnosticInfo &DI) {
692 // Map the LLVM internal diagnostic severity to the LTO diagnostic severity.
693 lto_codegen_diagnostic_severity_t Severity;
694 switch (DI.getSeverity()) {
695 case DS_Error:
696 Severity = LTO_DS_ERROR;
697 break;
698 case DS_Warning:
699 Severity = LTO_DS_WARNING;
700 break;
701 case DS_Remark:
702 Severity = LTO_DS_REMARK;
703 break;
704 case DS_Note:
705 Severity = LTO_DS_NOTE;
706 break;
707 }
708 // Create the string that will be reported to the external diagnostic handler.
709 std::string MsgStorage;
710 raw_string_ostream Stream(MsgStorage);
711 DiagnosticPrinterRawOStream DP(Stream);
712 DI.print(DP);
713
714 // If this method has been called it means someone has set up an external
715 // diagnostic handler. Assert on that.
716 assert(DiagHandler && "Invalid diagnostic handler");
717 (*DiagHandler)(Severity, MsgStorage.c_str(), DiagContext);
718}
719
720namespace {
721struct LTODiagnosticHandler : public DiagnosticHandler {
722 LTOCodeGenerator *CodeGenerator;
723 LTODiagnosticHandler(LTOCodeGenerator *CodeGenPtr)
724 : CodeGenerator(CodeGenPtr) {}
725 bool handleDiagnostics(const DiagnosticInfo &DI) override {
726 CodeGenerator->DiagnosticHandler(DI);
727 return true;
728 }
729};
730}
731
732void
733LTOCodeGenerator::setDiagnosticHandler(lto_diagnostic_handler_t DiagHandler,
734 void *Ctxt) {
735 this->DiagHandler = DiagHandler;
736 this->DiagContext = Ctxt;
737 if (!DiagHandler)
738 return Context.setDiagnosticHandler(DH: nullptr);
739 // Register the LTOCodeGenerator stub in the LLVMContext to forward the
740 // diagnostic to the external DiagHandler.
741 Context.setDiagnosticHandler(DH: std::make_unique<LTODiagnosticHandler>(args: this),
742 RespectFilters: true);
743}
744
745namespace {
746class LTODiagnosticInfo : public DiagnosticInfo {
747 const Twine &Msg;
748public:
749 LTODiagnosticInfo(const Twine &DiagMsg LLVM_LIFETIME_BOUND,
750 DiagnosticSeverity Severity = DS_Error)
751 : DiagnosticInfo(DK_Linker, Severity), Msg(DiagMsg) {}
752 void print(DiagnosticPrinter &DP) const override { DP << Msg; }
753};
754}
755
756void LTOCodeGenerator::emitError(const std::string &ErrMsg) {
757 if (DiagHandler)
758 (*DiagHandler)(LTO_DS_ERROR, ErrMsg.c_str(), DiagContext);
759 else
760 Context.diagnose(DI: LTODiagnosticInfo(ErrMsg));
761}
762
763void LTOCodeGenerator::emitWarning(const std::string &ErrMsg) {
764 if (DiagHandler)
765 (*DiagHandler)(LTO_DS_WARNING, ErrMsg.c_str(), DiagContext);
766 else
767 Context.diagnose(DI: LTODiagnosticInfo(ErrMsg, DS_Warning));
768}
769