1 //===-LTOCodeGenerator.cpp - LLVM Link Time Optimizer ---------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements the Link Time Optimization library. This library is
11 // intended to be used by linker to optimize code at link time.
12 //
13 //===----------------------------------------------------------------------===//
14 
15 #include "llvm/LTO/legacy/LTOCodeGenerator.h"
16 
17 #include "llvm/ADT/Statistic.h"
18 #include "llvm/ADT/StringExtras.h"
19 #include "llvm/Analysis/Passes.h"
20 #include "llvm/Analysis/TargetLibraryInfo.h"
21 #include "llvm/Analysis/TargetTransformInfo.h"
22 #include "llvm/Bitcode/BitcodeWriter.h"
23 #include "llvm/CodeGen/ParallelCG.h"
24 #include "llvm/CodeGen/RuntimeLibcalls.h"
25 #include "llvm/Config/config.h"
26 #include "llvm/IR/Constants.h"
27 #include "llvm/IR/DataLayout.h"
28 #include "llvm/IR/DebugInfo.h"
29 #include "llvm/IR/DerivedTypes.h"
30 #include "llvm/IR/DiagnosticInfo.h"
31 #include "llvm/IR/DiagnosticPrinter.h"
32 #include "llvm/IR/LLVMContext.h"
33 #include "llvm/IR/LegacyPassManager.h"
34 #include "llvm/IR/Mangler.h"
35 #include "llvm/IR/Module.h"
36 #include "llvm/IR/Verifier.h"
37 #include "llvm/InitializePasses.h"
38 #include "llvm/LTO/LTO.h"
39 #include "llvm/LTO/legacy/LTOModule.h"
40 #include "llvm/LTO/legacy/UpdateCompilerUsed.h"
41 #include "llvm/Linker/Linker.h"
42 #include "llvm/MC/MCAsmInfo.h"
43 #include "llvm/MC/MCContext.h"
44 #include "llvm/MC/SubtargetFeature.h"
45 #include "llvm/Support/CommandLine.h"
46 #include "llvm/Support/FileSystem.h"
47 #include "llvm/Support/Host.h"
48 #include "llvm/Support/MemoryBuffer.h"
49 #include "llvm/Support/Signals.h"
50 #include "llvm/Support/TargetRegistry.h"
51 #include "llvm/Support/TargetSelect.h"
52 #include "llvm/Support/ToolOutputFile.h"
53 #include "llvm/Support/YAMLTraits.h"
54 #include "llvm/Support/raw_ostream.h"
55 #include "llvm/Target/TargetLowering.h"
56 #include "llvm/Target/TargetOptions.h"
57 #include "llvm/Target/TargetRegisterInfo.h"
58 #include "llvm/Target/TargetSubtargetInfo.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/ObjCARC.h"
63 #include "llvm/Transforms/Utils/ModuleUtils.h"
64 #include <system_error>
65 using namespace llvm;
66 
67 const char* LTOCodeGenerator::getVersionString() {
68 #ifdef LLVM_VERSION_INFO
69   return PACKAGE_NAME " version " PACKAGE_VERSION ", " LLVM_VERSION_INFO;
70 #else
71   return PACKAGE_NAME " version " PACKAGE_VERSION;
72 #endif
73 }
74 
75 namespace llvm {
76 cl::opt<bool> LTODiscardValueNames(
77     "lto-discard-value-names",
78     cl::desc("Strip names from Value during LTO (other than GlobalValue)."),
79 #ifdef NDEBUG
80     cl::init(true),
81 #else
82     cl::init(false),
83 #endif
84     cl::Hidden);
85 
86 cl::opt<bool> LTOStripInvalidDebugInfo(
87     "lto-strip-invalid-debug-info",
88     cl::desc("Strip invalid debug info metadata during LTO instead of aborting."),
89 #ifdef NDEBUG
90     cl::init(true),
91 #else
92     cl::init(false),
93 #endif
94     cl::Hidden);
95 
96 cl::opt<std::string>
97     LTORemarksFilename("lto-pass-remarks-output",
98                        cl::desc("Output filename for pass remarks"),
99                        cl::value_desc("filename"));
100 
101 cl::opt<bool> LTOPassRemarksWithHotness(
102     "lto-pass-remarks-with-hotness",
103     cl::desc("With PGO, include profile count in optimization remarks"),
104     cl::Hidden);
105 }
106 
107 LTOCodeGenerator::LTOCodeGenerator(LLVMContext &Context)
108     : Context(Context), MergedModule(new Module("ld-temp.o", Context)),
109       TheLinker(new Linker(*MergedModule)) {
110   Context.setDiscardValueNames(LTODiscardValueNames);
111   Context.enableDebugTypeODRUniquing();
112   initializeLTOPasses();
113 }
114 
115 LTOCodeGenerator::~LTOCodeGenerator() {}
116 
117 // Initialize LTO passes. Please keep this function in sync with
118 // PassManagerBuilder::populateLTOPassManager(), and make sure all LTO
119 // passes are initialized.
120 void LTOCodeGenerator::initializeLTOPasses() {
121   PassRegistry &R = *PassRegistry::getPassRegistry();
122 
123   initializeInternalizeLegacyPassPass(R);
124   initializeIPSCCPLegacyPassPass(R);
125   initializeGlobalOptLegacyPassPass(R);
126   initializeConstantMergeLegacyPassPass(R);
127   initializeDAHPass(R);
128   initializeInstructionCombiningPassPass(R);
129   initializeSimpleInlinerPass(R);
130   initializePruneEHPass(R);
131   initializeGlobalDCELegacyPassPass(R);
132   initializeArgPromotionPass(R);
133   initializeJumpThreadingPass(R);
134   initializeSROALegacyPassPass(R);
135   initializePostOrderFunctionAttrsLegacyPassPass(R);
136   initializeReversePostOrderFunctionAttrsLegacyPassPass(R);
137   initializeGlobalsAAWrapperPassPass(R);
138   initializeLegacyLICMPassPass(R);
139   initializeMergedLoadStoreMotionLegacyPassPass(R);
140   initializeGVNLegacyPassPass(R);
141   initializeMemCpyOptLegacyPassPass(R);
142   initializeDCELegacyPassPass(R);
143   initializeCFGSimplifyPassPass(R);
144 }
145 
146 void LTOCodeGenerator::setAsmUndefinedRefs(LTOModule *Mod) {
147   const std::vector<StringRef> &undefs = Mod->getAsmUndefinedRefs();
148   for (int i = 0, e = undefs.size(); i != e; ++i)
149     AsmUndefinedRefs[undefs[i]] = 1;
150 }
151 
152 bool LTOCodeGenerator::addModule(LTOModule *Mod) {
153   assert(&Mod->getModule().getContext() == &Context &&
154          "Expected module in same context");
155 
156   bool ret = TheLinker->linkInModule(Mod->takeModule());
157   setAsmUndefinedRefs(Mod);
158 
159   // We've just changed the input, so let's make sure we verify it.
160   HasVerifiedInput = false;
161 
162   return !ret;
163 }
164 
165 void LTOCodeGenerator::setModule(std::unique_ptr<LTOModule> Mod) {
166   assert(&Mod->getModule().getContext() == &Context &&
167          "Expected module in same context");
168 
169   AsmUndefinedRefs.clear();
170 
171   MergedModule = Mod->takeModule();
172   TheLinker = make_unique<Linker>(*MergedModule);
173   setAsmUndefinedRefs(&*Mod);
174 
175   // We've just changed the input, so let's make sure we verify it.
176   HasVerifiedInput = false;
177 }
178 
179 void LTOCodeGenerator::setTargetOptions(const TargetOptions &Options) {
180   this->Options = Options;
181 }
182 
183 void LTOCodeGenerator::setDebugInfo(lto_debug_model Debug) {
184   switch (Debug) {
185   case LTO_DEBUG_MODEL_NONE:
186     EmitDwarfDebugInfo = false;
187     return;
188 
189   case LTO_DEBUG_MODEL_DWARF:
190     EmitDwarfDebugInfo = true;
191     return;
192   }
193   llvm_unreachable("Unknown debug format!");
194 }
195 
196 void LTOCodeGenerator::setOptLevel(unsigned Level) {
197   OptLevel = Level;
198   switch (OptLevel) {
199   case 0:
200     CGOptLevel = CodeGenOpt::None;
201     return;
202   case 1:
203     CGOptLevel = CodeGenOpt::Less;
204     return;
205   case 2:
206     CGOptLevel = CodeGenOpt::Default;
207     return;
208   case 3:
209     CGOptLevel = CodeGenOpt::Aggressive;
210     return;
211   }
212   llvm_unreachable("Unknown optimization level!");
213 }
214 
215 bool LTOCodeGenerator::writeMergedModules(StringRef Path) {
216   if (!determineTarget())
217     return false;
218 
219   // We always run the verifier once on the merged module.
220   verifyMergedModuleOnce();
221 
222   // mark which symbols can not be internalized
223   applyScopeRestrictions();
224 
225   // create output file
226   std::error_code EC;
227   tool_output_file Out(Path, EC, sys::fs::F_None);
228   if (EC) {
229     std::string ErrMsg = "could not open bitcode file for writing: ";
230     ErrMsg += Path;
231     emitError(ErrMsg);
232     return false;
233   }
234 
235   // write bitcode to it
236   WriteBitcodeToFile(MergedModule.get(), Out.os(), ShouldEmbedUselists);
237   Out.os().close();
238 
239   if (Out.os().has_error()) {
240     std::string ErrMsg = "could not write bitcode file: ";
241     ErrMsg += Path;
242     emitError(ErrMsg);
243     Out.os().clear_error();
244     return false;
245   }
246 
247   Out.keep();
248   return true;
249 }
250 
251 bool LTOCodeGenerator::compileOptimizedToFile(const char **Name) {
252   // make unique temp output file to put generated code
253   SmallString<128> Filename;
254   int FD;
255 
256   StringRef Extension
257       (FileType == TargetMachine::CGFT_AssemblyFile ? "s" : "o");
258 
259   std::error_code EC =
260       sys::fs::createTemporaryFile("lto-llvm", Extension, FD, Filename);
261   if (EC) {
262     emitError(EC.message());
263     return false;
264   }
265 
266   // generate object file
267   tool_output_file objFile(Filename, FD);
268 
269   bool genResult = compileOptimized(&objFile.os());
270   objFile.os().close();
271   if (objFile.os().has_error()) {
272     emitError((Twine("could not write object file: ") + Filename).str());
273     objFile.os().clear_error();
274     sys::fs::remove(Twine(Filename));
275     return false;
276   }
277 
278   objFile.keep();
279   if (!genResult) {
280     sys::fs::remove(Twine(Filename));
281     return false;
282   }
283 
284   NativeObjectPath = Filename.c_str();
285   *Name = NativeObjectPath.c_str();
286   return true;
287 }
288 
289 std::unique_ptr<MemoryBuffer>
290 LTOCodeGenerator::compileOptimized() {
291   const char *name;
292   if (!compileOptimizedToFile(&name))
293     return nullptr;
294 
295   // read .o file into memory buffer
296   ErrorOr<std::unique_ptr<MemoryBuffer>> BufferOrErr =
297       MemoryBuffer::getFile(name, -1, false);
298   if (std::error_code EC = BufferOrErr.getError()) {
299     emitError(EC.message());
300     sys::fs::remove(NativeObjectPath);
301     return nullptr;
302   }
303 
304   // remove temp files
305   sys::fs::remove(NativeObjectPath);
306 
307   return std::move(*BufferOrErr);
308 }
309 
310 bool LTOCodeGenerator::compile_to_file(const char **Name, bool DisableVerify,
311                                        bool DisableInline,
312                                        bool DisableGVNLoadPRE,
313                                        bool DisableVectorization) {
314   if (!optimize(DisableVerify, DisableInline, DisableGVNLoadPRE,
315                 DisableVectorization))
316     return false;
317 
318   return compileOptimizedToFile(Name);
319 }
320 
321 std::unique_ptr<MemoryBuffer>
322 LTOCodeGenerator::compile(bool DisableVerify, bool DisableInline,
323                           bool DisableGVNLoadPRE, bool DisableVectorization) {
324   if (!optimize(DisableVerify, DisableInline, DisableGVNLoadPRE,
325                 DisableVectorization))
326     return nullptr;
327 
328   return compileOptimized();
329 }
330 
331 bool LTOCodeGenerator::determineTarget() {
332   if (TargetMach)
333     return true;
334 
335   TripleStr = MergedModule->getTargetTriple();
336   if (TripleStr.empty()) {
337     TripleStr = sys::getDefaultTargetTriple();
338     MergedModule->setTargetTriple(TripleStr);
339   }
340   llvm::Triple Triple(TripleStr);
341 
342   // create target machine from info for merged modules
343   std::string ErrMsg;
344   MArch = TargetRegistry::lookupTarget(TripleStr, ErrMsg);
345   if (!MArch) {
346     emitError(ErrMsg);
347     return false;
348   }
349 
350   // Construct LTOModule, hand over ownership of module and target. Use MAttr as
351   // the default set of features.
352   SubtargetFeatures Features(MAttr);
353   Features.getDefaultSubtargetFeatures(Triple);
354   FeatureStr = Features.getString();
355   // Set a default CPU for Darwin triples.
356   if (MCpu.empty() && Triple.isOSDarwin()) {
357     if (Triple.getArch() == llvm::Triple::x86_64)
358       MCpu = "core2";
359     else if (Triple.getArch() == llvm::Triple::x86)
360       MCpu = "yonah";
361     else if (Triple.getArch() == llvm::Triple::aarch64)
362       MCpu = "cyclone";
363   }
364 
365   TargetMach = createTargetMachine();
366   return true;
367 }
368 
369 std::unique_ptr<TargetMachine> LTOCodeGenerator::createTargetMachine() {
370   return std::unique_ptr<TargetMachine>(
371       MArch->createTargetMachine(TripleStr, MCpu, FeatureStr, Options,
372                                  RelocModel, CodeModel::Default, CGOptLevel));
373 }
374 
375 // If a linkonce global is present in the MustPreserveSymbols, we need to make
376 // sure we honor this. To force the compiler to not drop it, we add it to the
377 // "llvm.compiler.used" global.
378 void LTOCodeGenerator::preserveDiscardableGVs(
379     Module &TheModule,
380     llvm::function_ref<bool(const GlobalValue &)> mustPreserveGV) {
381   std::vector<GlobalValue *> Used;
382   auto mayPreserveGlobal = [&](GlobalValue &GV) {
383     if (!GV.isDiscardableIfUnused() || GV.isDeclaration() ||
384         !mustPreserveGV(GV))
385       return;
386     if (GV.hasAvailableExternallyLinkage())
387       return emitWarning(
388           (Twine("Linker asked to preserve available_externally global: '") +
389            GV.getName() + "'").str());
390     if (GV.hasInternalLinkage())
391       return emitWarning((Twine("Linker asked to preserve internal global: '") +
392                    GV.getName() + "'").str());
393     Used.push_back(&GV);
394   };
395   for (auto &GV : TheModule)
396     mayPreserveGlobal(GV);
397   for (auto &GV : TheModule.globals())
398     mayPreserveGlobal(GV);
399   for (auto &GV : TheModule.aliases())
400     mayPreserveGlobal(GV);
401 
402   if (Used.empty())
403     return;
404 
405   appendToCompilerUsed(TheModule, Used);
406 }
407 
408 void LTOCodeGenerator::applyScopeRestrictions() {
409   if (ScopeRestrictionsDone)
410     return;
411 
412   // Declare a callback for the internalize pass that will ask for every
413   // candidate GlobalValue if it can be internalized or not.
414   Mangler Mang;
415   SmallString<64> MangledName;
416   auto mustPreserveGV = [&](const GlobalValue &GV) -> bool {
417     // Unnamed globals can't be mangled, but they can't be preserved either.
418     if (!GV.hasName())
419       return false;
420 
421     // Need to mangle the GV as the "MustPreserveSymbols" StringSet is filled
422     // with the linker supplied name, which on Darwin includes a leading
423     // underscore.
424     MangledName.clear();
425     MangledName.reserve(GV.getName().size() + 1);
426     Mang.getNameWithPrefix(MangledName, &GV, /*CannotUsePrivateLabel=*/false);
427     return MustPreserveSymbols.count(MangledName);
428   };
429 
430   // Preserve linkonce value on linker request
431   preserveDiscardableGVs(*MergedModule, mustPreserveGV);
432 
433   if (!ShouldInternalize)
434     return;
435 
436   if (ShouldRestoreGlobalsLinkage) {
437     // Record the linkage type of non-local symbols so they can be restored
438     // prior
439     // to module splitting.
440     auto RecordLinkage = [&](const GlobalValue &GV) {
441       if (!GV.hasAvailableExternallyLinkage() && !GV.hasLocalLinkage() &&
442           GV.hasName())
443         ExternalSymbols.insert(std::make_pair(GV.getName(), GV.getLinkage()));
444     };
445     for (auto &GV : *MergedModule)
446       RecordLinkage(GV);
447     for (auto &GV : MergedModule->globals())
448       RecordLinkage(GV);
449     for (auto &GV : MergedModule->aliases())
450       RecordLinkage(GV);
451   }
452 
453   // Update the llvm.compiler_used globals to force preserving libcalls and
454   // symbols referenced from asm
455   updateCompilerUsed(*MergedModule, *TargetMach, AsmUndefinedRefs);
456 
457   internalizeModule(*MergedModule, mustPreserveGV);
458 
459   ScopeRestrictionsDone = true;
460 }
461 
462 /// Restore original linkage for symbols that may have been internalized
463 void LTOCodeGenerator::restoreLinkageForExternals() {
464   if (!ShouldInternalize || !ShouldRestoreGlobalsLinkage)
465     return;
466 
467   assert(ScopeRestrictionsDone &&
468          "Cannot externalize without internalization!");
469 
470   if (ExternalSymbols.empty())
471     return;
472 
473   auto externalize = [this](GlobalValue &GV) {
474     if (!GV.hasLocalLinkage() || !GV.hasName())
475       return;
476 
477     auto I = ExternalSymbols.find(GV.getName());
478     if (I == ExternalSymbols.end())
479       return;
480 
481     GV.setLinkage(I->second);
482   };
483 
484   std::for_each(MergedModule->begin(), MergedModule->end(), externalize);
485   std::for_each(MergedModule->global_begin(), MergedModule->global_end(),
486                 externalize);
487   std::for_each(MergedModule->alias_begin(), MergedModule->alias_end(),
488                 externalize);
489 }
490 
491 void LTOCodeGenerator::verifyMergedModuleOnce() {
492   // Only run on the first call.
493   if (HasVerifiedInput)
494     return;
495   HasVerifiedInput = true;
496 
497   if (LTOStripInvalidDebugInfo) {
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   if (verifyModule(*MergedModule, &dbgs()))
507     report_fatal_error("Broken module found, compilation aborted!");
508 }
509 
510 void LTOCodeGenerator::finishOptimizationRemarks() {
511   if (DiagnosticOutputFile) {
512     DiagnosticOutputFile->keep();
513     // FIXME: LTOCodeGenerator dtor is not invoked on Darwin
514     DiagnosticOutputFile->os().flush();
515   }
516 }
517 
518 /// Optimize merged modules using various IPO passes
519 bool LTOCodeGenerator::optimize(bool DisableVerify, bool DisableInline,
520                                 bool DisableGVNLoadPRE,
521                                 bool DisableVectorization) {
522   if (!this->determineTarget())
523     return false;
524 
525   auto DiagFileOrErr = lto::setupOptimizationRemarks(
526       Context, LTORemarksFilename, LTOPassRemarksWithHotness);
527   if (!DiagFileOrErr) {
528     errs() << "Error: " << toString(DiagFileOrErr.takeError()) << "\n";
529     report_fatal_error("Can't get an output file for the remarks");
530   }
531   DiagnosticOutputFile = std::move(*DiagFileOrErr);
532 
533   // We always run the verifier once on the merged module, the `DisableVerify`
534   // parameter only applies to subsequent verify.
535   verifyMergedModuleOnce();
536 
537   // Mark which symbols can not be internalized
538   this->applyScopeRestrictions();
539 
540   // Instantiate the pass manager to organize the passes.
541   legacy::PassManager passes;
542 
543   // Add an appropriate DataLayout instance for this module...
544   MergedModule->setDataLayout(TargetMach->createDataLayout());
545 
546   passes.add(
547       createTargetTransformInfoWrapperPass(TargetMach->getTargetIRAnalysis()));
548 
549   Triple TargetTriple(TargetMach->getTargetTriple());
550   PassManagerBuilder PMB;
551   PMB.DisableGVNLoadPRE = DisableGVNLoadPRE;
552   PMB.LoopVectorize = !DisableVectorization;
553   PMB.SLPVectorize = !DisableVectorization;
554   if (!DisableInline)
555     PMB.Inliner = createFunctionInliningPass();
556   PMB.LibraryInfo = new TargetLibraryInfoImpl(TargetTriple);
557   PMB.OptLevel = OptLevel;
558   PMB.VerifyInput = !DisableVerify;
559   PMB.VerifyOutput = !DisableVerify;
560 
561   PMB.populateLTOPassManager(passes);
562 
563   // Run our queue of passes all at once now, efficiently.
564   passes.run(*MergedModule);
565 
566   return true;
567 }
568 
569 bool LTOCodeGenerator::compileOptimized(ArrayRef<raw_pwrite_stream *> Out) {
570   if (!this->determineTarget())
571     return false;
572 
573   // We always run the verifier once on the merged module.  If it has already
574   // been called in optimize(), this call will return early.
575   verifyMergedModuleOnce();
576 
577   legacy::PassManager preCodeGenPasses;
578 
579   // If the bitcode files contain ARC code and were compiled with optimization,
580   // the ObjCARCContractPass must be run, so do it unconditionally here.
581   preCodeGenPasses.add(createObjCARCContractPass());
582   preCodeGenPasses.run(*MergedModule);
583 
584   // Re-externalize globals that may have been internalized to increase scope
585   // for splitting
586   restoreLinkageForExternals();
587 
588   // Do code generation. We need to preserve the module in case the client calls
589   // writeMergedModules() after compilation, but we only need to allow this at
590   // parallelism level 1. This is achieved by having splitCodeGen return the
591   // original module at parallelism level 1 which we then assign back to
592   // MergedModule.
593   MergedModule = splitCodeGen(std::move(MergedModule), Out, {},
594                               [&]() { return createTargetMachine(); }, FileType,
595                               ShouldRestoreGlobalsLinkage);
596 
597   // If statistics were requested, print them out after codegen.
598   if (llvm::AreStatisticsEnabled())
599     llvm::PrintStatistics();
600 
601   finishOptimizationRemarks();
602 
603   return true;
604 }
605 
606 /// setCodeGenDebugOptions - Set codegen debugging options to aid in debugging
607 /// LTO problems.
608 void LTOCodeGenerator::setCodeGenDebugOptions(StringRef Options) {
609   for (std::pair<StringRef, StringRef> o = getToken(Options); !o.first.empty();
610        o = getToken(o.second))
611     CodegenOptions.push_back(o.first);
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 void LTOCodeGenerator::DiagnosticHandler(const DiagnosticInfo &DI,
626                                          void *Context) {
627   ((LTOCodeGenerator *)Context)->DiagnosticHandler2(DI);
628 }
629 
630 void LTOCodeGenerator::DiagnosticHandler2(const DiagnosticInfo &DI) {
631   // Map the LLVM internal diagnostic severity to the LTO diagnostic severity.
632   lto_codegen_diagnostic_severity_t Severity;
633   switch (DI.getSeverity()) {
634   case DS_Error:
635     Severity = LTO_DS_ERROR;
636     break;
637   case DS_Warning:
638     Severity = LTO_DS_WARNING;
639     break;
640   case DS_Remark:
641     Severity = LTO_DS_REMARK;
642     break;
643   case DS_Note:
644     Severity = LTO_DS_NOTE;
645     break;
646   }
647   // Create the string that will be reported to the external diagnostic handler.
648   std::string MsgStorage;
649   raw_string_ostream Stream(MsgStorage);
650   DiagnosticPrinterRawOStream DP(Stream);
651   DI.print(DP);
652   Stream.flush();
653 
654   // If this method has been called it means someone has set up an external
655   // diagnostic handler. Assert on that.
656   assert(DiagHandler && "Invalid diagnostic handler");
657   (*DiagHandler)(Severity, MsgStorage.c_str(), DiagContext);
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, nullptr);
667   // Register the LTOCodeGenerator stub in the LLVMContext to forward the
668   // diagnostic to the external DiagHandler.
669   Context.setDiagnosticHandler(LTOCodeGenerator::DiagnosticHandler, this,
670                                /* RespectFilters */ 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