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