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