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/legacy/LTOModule.h"
39 #include "llvm/LTO/legacy/UpdateCompilerUsed.h"
40 #include "llvm/Linker/Linker.h"
41 #include "llvm/MC/MCAsmInfo.h"
42 #include "llvm/MC/MCContext.h"
43 #include "llvm/MC/SubtargetFeature.h"
44 #include "llvm/Support/CommandLine.h"
45 #include "llvm/Support/FileSystem.h"
46 #include "llvm/Support/Host.h"
47 #include "llvm/Support/MemoryBuffer.h"
48 #include "llvm/Support/Signals.h"
49 #include "llvm/Support/TargetRegistry.h"
50 #include "llvm/Support/TargetSelect.h"
51 #include "llvm/Support/ToolOutputFile.h"
52 #include "llvm/Support/YAMLTraits.h"
53 #include "llvm/Support/raw_ostream.h"
54 #include "llvm/Target/TargetLowering.h"
55 #include "llvm/Target/TargetOptions.h"
56 #include "llvm/Target/TargetRegisterInfo.h"
57 #include "llvm/Target/TargetSubtargetInfo.h"
58 #include "llvm/Transforms/IPO.h"
59 #include "llvm/Transforms/IPO/Internalize.h"
60 #include "llvm/Transforms/IPO/PassManagerBuilder.h"
61 #include "llvm/Transforms/ObjCARC.h"
62 #include "llvm/Transforms/Utils/ModuleUtils.h"
63 #include <system_error>
64 using namespace llvm;
65 
66 const char* LTOCodeGenerator::getVersionString() {
67 #ifdef LLVM_VERSION_INFO
68   return PACKAGE_NAME " version " PACKAGE_VERSION ", " LLVM_VERSION_INFO;
69 #else
70   return PACKAGE_NAME " version " PACKAGE_VERSION;
71 #endif
72 }
73 
74 namespace llvm {
75 cl::opt<bool> LTODiscardValueNames(
76     "lto-discard-value-names",
77     cl::desc("Strip names from Value during LTO (other than GlobalValue)."),
78 #ifdef NDEBUG
79     cl::init(true),
80 #else
81     cl::init(false),
82 #endif
83     cl::Hidden);
84 
85 cl::opt<bool> LTOStripInvalidDebugInfo(
86     "lto-strip-invalid-debug-info",
87     cl::desc("Strip invalid debug info metadata during LTO instead of aborting."),
88 #ifdef NDEBUG
89     cl::init(true),
90 #else
91     cl::init(false),
92 #endif
93     cl::Hidden);
94 
95 cl::opt<std::string>
96     LTORemarksFilename("lto-pass-remarks-output",
97                        cl::desc("Output filename for pass remarks"),
98                        cl::value_desc("filename"));
99 }
100 
101 LTOCodeGenerator::LTOCodeGenerator(LLVMContext &Context)
102     : Context(Context), MergedModule(new Module("ld-temp.o", Context)),
103       TheLinker(new Linker(*MergedModule)) {
104   Context.setDiscardValueNames(LTODiscardValueNames);
105   Context.enableDebugTypeODRUniquing();
106   initializeLTOPasses();
107 }
108 
109 LTOCodeGenerator::~LTOCodeGenerator() {}
110 
111 // Initialize LTO passes. Please keep this function in sync with
112 // PassManagerBuilder::populateLTOPassManager(), and make sure all LTO
113 // passes are initialized.
114 void LTOCodeGenerator::initializeLTOPasses() {
115   PassRegistry &R = *PassRegistry::getPassRegistry();
116 
117   initializeInternalizeLegacyPassPass(R);
118   initializeIPSCCPLegacyPassPass(R);
119   initializeGlobalOptLegacyPassPass(R);
120   initializeConstantMergeLegacyPassPass(R);
121   initializeDAHPass(R);
122   initializeInstructionCombiningPassPass(R);
123   initializeSimpleInlinerPass(R);
124   initializePruneEHPass(R);
125   initializeGlobalDCELegacyPassPass(R);
126   initializeArgPromotionPass(R);
127   initializeJumpThreadingPass(R);
128   initializeSROALegacyPassPass(R);
129   initializePostOrderFunctionAttrsLegacyPassPass(R);
130   initializeReversePostOrderFunctionAttrsLegacyPassPass(R);
131   initializeGlobalsAAWrapperPassPass(R);
132   initializeLegacyLICMPassPass(R);
133   initializeMergedLoadStoreMotionLegacyPassPass(R);
134   initializeGVNLegacyPassPass(R);
135   initializeMemCpyOptLegacyPassPass(R);
136   initializeDCELegacyPassPass(R);
137   initializeCFGSimplifyPassPass(R);
138 }
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[undefs[i]] = 1;
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 = 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   this->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   OptLevel = Level;
192   switch (OptLevel) {
193   case 0:
194     CGOptLevel = CodeGenOpt::None;
195     return;
196   case 1:
197     CGOptLevel = CodeGenOpt::Less;
198     return;
199   case 2:
200     CGOptLevel = CodeGenOpt::Default;
201     return;
202   case 3:
203     CGOptLevel = CodeGenOpt::Aggressive;
204     return;
205   }
206   llvm_unreachable("Unknown optimization level!");
207 }
208 
209 bool LTOCodeGenerator::writeMergedModules(StringRef Path) {
210   if (!determineTarget())
211     return false;
212 
213   // We always run the verifier once on the merged module.
214   verifyMergedModuleOnce();
215 
216   // mark which symbols can not be internalized
217   applyScopeRestrictions();
218 
219   // create output file
220   std::error_code EC;
221   tool_output_file Out(Path, EC, sys::fs::F_None);
222   if (EC) {
223     std::string ErrMsg = "could not open bitcode file for writing: ";
224     ErrMsg += Path;
225     emitError(ErrMsg);
226     return false;
227   }
228 
229   // write bitcode to it
230   WriteBitcodeToFile(MergedModule.get(), Out.os(), ShouldEmbedUselists);
231   Out.os().close();
232 
233   if (Out.os().has_error()) {
234     std::string ErrMsg = "could not write bitcode file: ";
235     ErrMsg += Path;
236     emitError(ErrMsg);
237     Out.os().clear_error();
238     return false;
239   }
240 
241   Out.keep();
242   return true;
243 }
244 
245 bool LTOCodeGenerator::compileOptimizedToFile(const char **Name) {
246   // make unique temp output file to put generated code
247   SmallString<128> Filename;
248   int FD;
249 
250   StringRef Extension
251       (FileType == TargetMachine::CGFT_AssemblyFile ? "s" : "o");
252 
253   std::error_code EC =
254       sys::fs::createTemporaryFile("lto-llvm", Extension, FD, Filename);
255   if (EC) {
256     emitError(EC.message());
257     return false;
258   }
259 
260   // generate object file
261   tool_output_file objFile(Filename, FD);
262 
263   bool genResult = compileOptimized(&objFile.os());
264   objFile.os().close();
265   if (objFile.os().has_error()) {
266     emitError((Twine("could not write object file: ") + Filename).str());
267     objFile.os().clear_error();
268     sys::fs::remove(Twine(Filename));
269     return false;
270   }
271 
272   objFile.keep();
273   if (!genResult) {
274     sys::fs::remove(Twine(Filename));
275     return false;
276   }
277 
278   NativeObjectPath = Filename.c_str();
279   *Name = NativeObjectPath.c_str();
280   return true;
281 }
282 
283 std::unique_ptr<MemoryBuffer>
284 LTOCodeGenerator::compileOptimized() {
285   const char *name;
286   if (!compileOptimizedToFile(&name))
287     return nullptr;
288 
289   // read .o file into memory buffer
290   ErrorOr<std::unique_ptr<MemoryBuffer>> BufferOrErr =
291       MemoryBuffer::getFile(name, -1, false);
292   if (std::error_code EC = BufferOrErr.getError()) {
293     emitError(EC.message());
294     sys::fs::remove(NativeObjectPath);
295     return nullptr;
296   }
297 
298   // remove temp files
299   sys::fs::remove(NativeObjectPath);
300 
301   return std::move(*BufferOrErr);
302 }
303 
304 bool LTOCodeGenerator::compile_to_file(const char **Name, bool DisableVerify,
305                                        bool DisableInline,
306                                        bool DisableGVNLoadPRE,
307                                        bool DisableVectorization) {
308   if (!optimize(DisableVerify, DisableInline, DisableGVNLoadPRE,
309                 DisableVectorization))
310     return false;
311 
312   return compileOptimizedToFile(Name);
313 }
314 
315 std::unique_ptr<MemoryBuffer>
316 LTOCodeGenerator::compile(bool DisableVerify, bool DisableInline,
317                           bool DisableGVNLoadPRE, bool DisableVectorization) {
318   if (!optimize(DisableVerify, DisableInline, DisableGVNLoadPRE,
319                 DisableVectorization))
320     return nullptr;
321 
322   return compileOptimized();
323 }
324 
325 bool LTOCodeGenerator::determineTarget() {
326   if (TargetMach)
327     return true;
328 
329   TripleStr = MergedModule->getTargetTriple();
330   if (TripleStr.empty()) {
331     TripleStr = sys::getDefaultTargetTriple();
332     MergedModule->setTargetTriple(TripleStr);
333   }
334   llvm::Triple Triple(TripleStr);
335 
336   // create target machine from info for merged modules
337   std::string ErrMsg;
338   MArch = TargetRegistry::lookupTarget(TripleStr, ErrMsg);
339   if (!MArch) {
340     emitError(ErrMsg);
341     return false;
342   }
343 
344   // Construct LTOModule, hand over ownership of module and target. Use MAttr as
345   // the default set of features.
346   SubtargetFeatures Features(MAttr);
347   Features.getDefaultSubtargetFeatures(Triple);
348   FeatureStr = Features.getString();
349   // Set a default CPU for Darwin triples.
350   if (MCpu.empty() && Triple.isOSDarwin()) {
351     if (Triple.getArch() == llvm::Triple::x86_64)
352       MCpu = "core2";
353     else if (Triple.getArch() == llvm::Triple::x86)
354       MCpu = "yonah";
355     else if (Triple.getArch() == llvm::Triple::aarch64)
356       MCpu = "cyclone";
357   }
358 
359   TargetMach = createTargetMachine();
360   return true;
361 }
362 
363 std::unique_ptr<TargetMachine> LTOCodeGenerator::createTargetMachine() {
364   return std::unique_ptr<TargetMachine>(
365       MArch->createTargetMachine(TripleStr, MCpu, FeatureStr, Options,
366                                  RelocModel, CodeModel::Default, 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   std::for_each(MergedModule->begin(), MergedModule->end(), externalize);
479   std::for_each(MergedModule->global_begin(), MergedModule->global_end(),
480                 externalize);
481   std::for_each(MergedModule->alias_begin(), MergedModule->alias_end(),
482                 externalize);
483 }
484 
485 void LTOCodeGenerator::verifyMergedModuleOnce() {
486   // Only run on the first call.
487   if (HasVerifiedInput)
488     return;
489   HasVerifiedInput = true;
490 
491   if (LTOStripInvalidDebugInfo) {
492     bool BrokenDebugInfo = false;
493     if (verifyModule(*MergedModule, &dbgs(), &BrokenDebugInfo))
494       report_fatal_error("Broken module found, compilation aborted!");
495     if (BrokenDebugInfo) {
496       emitWarning("Invalid debug info found, debug info will be stripped");
497       StripDebugInfo(*MergedModule);
498     }
499   }
500   if (verifyModule(*MergedModule, &dbgs()))
501     report_fatal_error("Broken module found, compilation aborted!");
502 }
503 
504 bool LTOCodeGenerator::setupOptimizationRemarks() {
505   if (LTORemarksFilename != "") {
506     std::error_code EC;
507     DiagnosticOutputFile = llvm::make_unique<tool_output_file>(
508         LTORemarksFilename, EC, sys::fs::F_None);
509     if (EC) {
510       emitError(EC.message());
511       return false;
512     }
513     Context.setDiagnosticsOutputFile(
514         llvm::make_unique<yaml::Output>(DiagnosticOutputFile->os()));
515   }
516   return true;
517 }
518 
519 void LTOCodeGenerator::finishOptimizationRemarks() {
520   if (DiagnosticOutputFile) {
521     DiagnosticOutputFile->keep();
522     // FIXME: LTOCodeGenerator dtor is not invoked on Darwin
523     DiagnosticOutputFile->os().flush();
524   }
525 }
526 
527 /// Optimize merged modules using various IPO passes
528 bool LTOCodeGenerator::optimize(bool DisableVerify, bool DisableInline,
529                                 bool DisableGVNLoadPRE,
530                                 bool DisableVectorization) {
531   if (!this->determineTarget())
532     return false;
533 
534   if (!setupOptimizationRemarks())
535     return false;
536 
537   // We always run the verifier once on the merged module, the `DisableVerify`
538   // parameter only applies to subsequent verify.
539   verifyMergedModuleOnce();
540 
541   // Mark which symbols can not be internalized
542   this->applyScopeRestrictions();
543 
544   // Instantiate the pass manager to organize the passes.
545   legacy::PassManager passes;
546 
547   // Add an appropriate DataLayout instance for this module...
548   MergedModule->setDataLayout(TargetMach->createDataLayout());
549 
550   passes.add(
551       createTargetTransformInfoWrapperPass(TargetMach->getTargetIRAnalysis()));
552 
553   Triple TargetTriple(TargetMach->getTargetTriple());
554   PassManagerBuilder PMB;
555   PMB.DisableGVNLoadPRE = DisableGVNLoadPRE;
556   PMB.LoopVectorize = !DisableVectorization;
557   PMB.SLPVectorize = !DisableVectorization;
558   if (!DisableInline)
559     PMB.Inliner = createFunctionInliningPass();
560   PMB.LibraryInfo = new TargetLibraryInfoImpl(TargetTriple);
561   PMB.OptLevel = OptLevel;
562   PMB.VerifyInput = !DisableVerify;
563   PMB.VerifyOutput = !DisableVerify;
564 
565   PMB.populateLTOPassManager(passes);
566 
567   // Run our queue of passes all at once now, efficiently.
568   passes.run(*MergedModule);
569 
570   finishOptimizationRemarks();
571 
572   return true;
573 }
574 
575 bool LTOCodeGenerator::compileOptimized(ArrayRef<raw_pwrite_stream *> Out) {
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   legacy::PassManager preCodeGenPasses;
584 
585   // If the bitcode files contain ARC code and were compiled with optimization,
586   // the ObjCARCContractPass must be run, so do it unconditionally here.
587   preCodeGenPasses.add(createObjCARCContractPass());
588   preCodeGenPasses.run(*MergedModule);
589 
590   // Re-externalize globals that may have been internalized to increase scope
591   // for splitting
592   restoreLinkageForExternals();
593 
594   // Do code generation. We need to preserve the module in case the client calls
595   // writeMergedModules() after compilation, but we only need to allow this at
596   // parallelism level 1. This is achieved by having splitCodeGen return the
597   // original module at parallelism level 1 which we then assign back to
598   // MergedModule.
599   MergedModule = splitCodeGen(std::move(MergedModule), Out, {},
600                               [&]() { return createTargetMachine(); }, FileType,
601                               ShouldRestoreGlobalsLinkage);
602 
603   // If statistics were requested, print them out after codegen.
604   if (llvm::AreStatisticsEnabled())
605     llvm::PrintStatistics();
606 
607   return true;
608 }
609 
610 /// setCodeGenDebugOptions - Set codegen debugging options to aid in debugging
611 /// LTO problems.
612 void LTOCodeGenerator::setCodeGenDebugOptions(StringRef Options) {
613   for (std::pair<StringRef, StringRef> o = getToken(Options); !o.first.empty();
614        o = getToken(o.second))
615     CodegenOptions.push_back(o.first);
616 }
617 
618 void LTOCodeGenerator::parseCodeGenDebugOptions() {
619   // if options were requested, set them
620   if (!CodegenOptions.empty()) {
621     // ParseCommandLineOptions() expects argv[0] to be program name.
622     std::vector<const char *> CodegenArgv(1, "libLLVMLTO");
623     for (std::string &Arg : CodegenOptions)
624       CodegenArgv.push_back(Arg.c_str());
625     cl::ParseCommandLineOptions(CodegenArgv.size(), CodegenArgv.data());
626   }
627 }
628 
629 void LTOCodeGenerator::DiagnosticHandler(const DiagnosticInfo &DI,
630                                          void *Context) {
631   ((LTOCodeGenerator *)Context)->DiagnosticHandler2(DI);
632 }
633 
634 void LTOCodeGenerator::DiagnosticHandler2(const DiagnosticInfo &DI) {
635   // Map the LLVM internal diagnostic severity to the LTO diagnostic severity.
636   lto_codegen_diagnostic_severity_t Severity;
637   switch (DI.getSeverity()) {
638   case DS_Error:
639     Severity = LTO_DS_ERROR;
640     break;
641   case DS_Warning:
642     Severity = LTO_DS_WARNING;
643     break;
644   case DS_Remark:
645     Severity = LTO_DS_REMARK;
646     break;
647   case DS_Note:
648     Severity = LTO_DS_NOTE;
649     break;
650   }
651   // Create the string that will be reported to the external diagnostic handler.
652   std::string MsgStorage;
653   raw_string_ostream Stream(MsgStorage);
654   DiagnosticPrinterRawOStream DP(Stream);
655   DI.print(DP);
656   Stream.flush();
657 
658   // If this method has been called it means someone has set up an external
659   // diagnostic handler. Assert on that.
660   assert(DiagHandler && "Invalid diagnostic handler");
661   (*DiagHandler)(Severity, MsgStorage.c_str(), DiagContext);
662 }
663 
664 void
665 LTOCodeGenerator::setDiagnosticHandler(lto_diagnostic_handler_t DiagHandler,
666                                        void *Ctxt) {
667   this->DiagHandler = DiagHandler;
668   this->DiagContext = Ctxt;
669   if (!DiagHandler)
670     return Context.setDiagnosticHandler(nullptr, nullptr);
671   // Register the LTOCodeGenerator stub in the LLVMContext to forward the
672   // diagnostic to the external DiagHandler.
673   Context.setDiagnosticHandler(LTOCodeGenerator::DiagnosticHandler, this,
674                                /* RespectFilters */ true);
675 }
676 
677 namespace {
678 class LTODiagnosticInfo : public DiagnosticInfo {
679   const Twine &Msg;
680 public:
681   LTODiagnosticInfo(const Twine &DiagMsg, DiagnosticSeverity Severity=DS_Error)
682       : DiagnosticInfo(DK_Linker, Severity), Msg(DiagMsg) {}
683   void print(DiagnosticPrinter &DP) const override { DP << Msg; }
684 };
685 }
686 
687 void LTOCodeGenerator::emitError(const std::string &ErrMsg) {
688   if (DiagHandler)
689     (*DiagHandler)(LTO_DS_ERROR, ErrMsg.c_str(), DiagContext);
690   else
691     Context.diagnose(LTODiagnosticInfo(ErrMsg));
692 }
693 
694 void LTOCodeGenerator::emitWarning(const std::string &ErrMsg) {
695   if (DiagHandler)
696     (*DiagHandler)(LTO_DS_WARNING, ErrMsg.c_str(), DiagContext);
697   else
698     Context.diagnose(LTODiagnosticInfo(ErrMsg, DS_Warning));
699 }
700