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