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/LegacyPassManager.h"
33 #include "llvm/IR/Mangler.h"
34 #include "llvm/IR/Module.h"
35 #include "llvm/IR/PassTimingInfo.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/TargetOptions.h"
56 #include "llvm/Transforms/IPO.h"
57 #include "llvm/Transforms/IPO/Internalize.h"
58 #include "llvm/Transforms/IPO/PassManagerBuilder.h"
59 #include "llvm/Transforms/ObjCARC.h"
60 #include "llvm/Transforms/Utils/ModuleUtils.h"
61 #include <system_error>
62 using namespace llvm;
63 
64 const char* LTOCodeGenerator::getVersionString() {
65 #ifdef LLVM_VERSION_INFO
66   return PACKAGE_NAME " version " PACKAGE_VERSION ", " LLVM_VERSION_INFO;
67 #else
68   return PACKAGE_NAME " version " PACKAGE_VERSION;
69 #endif
70 }
71 
72 namespace llvm {
73 cl::opt<bool> LTODiscardValueNames(
74     "lto-discard-value-names",
75     cl::desc("Strip names from Value during LTO (other than GlobalValue)."),
76 #ifdef NDEBUG
77     cl::init(true),
78 #else
79     cl::init(false),
80 #endif
81     cl::Hidden);
82 
83 cl::opt<std::string>
84     LTORemarksFilename("lto-pass-remarks-output",
85                        cl::desc("Output filename for pass remarks"),
86                        cl::value_desc("filename"));
87 
88 cl::opt<std::string>
89     LTORemarksPasses("lto-pass-remarks-filter",
90                      cl::desc("Only record optimization remarks from passes "
91                               "whose names match the given regular expression"),
92                      cl::value_desc("regex"));
93 
94 cl::opt<bool> LTOPassRemarksWithHotness(
95     "lto-pass-remarks-with-hotness",
96     cl::desc("With PGO, include profile count in optimization remarks"),
97     cl::Hidden);
98 }
99 
100 LTOCodeGenerator::LTOCodeGenerator(LLVMContext &Context)
101     : Context(Context), MergedModule(new Module("ld-temp.o", Context)),
102       TheLinker(new Linker(*MergedModule)) {
103   Context.setDiscardValueNames(LTODiscardValueNames);
104   Context.enableDebugTypeODRUniquing();
105   initializeLTOPasses();
106 }
107 
108 LTOCodeGenerator::~LTOCodeGenerator() {}
109 
110 // Initialize LTO passes. Please keep this function in sync with
111 // PassManagerBuilder::populateLTOPassManager(), and make sure all LTO
112 // passes are initialized.
113 void LTOCodeGenerator::initializeLTOPasses() {
114   PassRegistry &R = *PassRegistry::getPassRegistry();
115 
116   initializeInternalizeLegacyPassPass(R);
117   initializeIPSCCPLegacyPassPass(R);
118   initializeGlobalOptLegacyPassPass(R);
119   initializeConstantMergeLegacyPassPass(R);
120   initializeDAHPass(R);
121   initializeInstructionCombiningPassPass(R);
122   initializeSimpleInlinerPass(R);
123   initializePruneEHPass(R);
124   initializeGlobalDCELegacyPassPass(R);
125   initializeArgPromotionPass(R);
126   initializeJumpThreadingPass(R);
127   initializeSROALegacyPassPass(R);
128   initializePostOrderFunctionAttrsLegacyPassPass(R);
129   initializeReversePostOrderFunctionAttrsLegacyPassPass(R);
130   initializeGlobalsAAWrapperPassPass(R);
131   initializeLegacyLICMPassPass(R);
132   initializeMergedLoadStoreMotionLegacyPassPass(R);
133   initializeGVNLegacyPassPass(R);
134   initializeMemCpyOptLegacyPassPass(R);
135   initializeDCELegacyPassPass(R);
136   initializeCFGSimplifyPassPass(R);
137 }
138 
139 void LTOCodeGenerator::setAsmUndefinedRefs(LTOModule *Mod) {
140   const std::vector<StringRef> &undefs = Mod->getAsmUndefinedRefs();
141   for (int i = 0, e = undefs.size(); i != e; ++i)
142     AsmUndefinedRefs[undefs[i]] = 1;
143 }
144 
145 bool LTOCodeGenerator::addModule(LTOModule *Mod) {
146   assert(&Mod->getModule().getContext() == &Context &&
147          "Expected module in same context");
148 
149   bool ret = TheLinker->linkInModule(Mod->takeModule());
150   setAsmUndefinedRefs(Mod);
151 
152   // We've just changed the input, so let's make sure we verify it.
153   HasVerifiedInput = false;
154 
155   return !ret;
156 }
157 
158 void LTOCodeGenerator::setModule(std::unique_ptr<LTOModule> Mod) {
159   assert(&Mod->getModule().getContext() == &Context &&
160          "Expected module in same context");
161 
162   AsmUndefinedRefs.clear();
163 
164   MergedModule = Mod->takeModule();
165   TheLinker = make_unique<Linker>(*MergedModule);
166   setAsmUndefinedRefs(&*Mod);
167 
168   // We've just changed the input, so let's make sure we verify it.
169   HasVerifiedInput = false;
170 }
171 
172 void LTOCodeGenerator::setTargetOptions(const TargetOptions &Options) {
173   this->Options = Options;
174 }
175 
176 void LTOCodeGenerator::setDebugInfo(lto_debug_model Debug) {
177   switch (Debug) {
178   case LTO_DEBUG_MODEL_NONE:
179     EmitDwarfDebugInfo = false;
180     return;
181 
182   case LTO_DEBUG_MODEL_DWARF:
183     EmitDwarfDebugInfo = true;
184     return;
185   }
186   llvm_unreachable("Unknown debug format!");
187 }
188 
189 void LTOCodeGenerator::setOptLevel(unsigned Level) {
190   OptLevel = Level;
191   switch (OptLevel) {
192   case 0:
193     CGOptLevel = CodeGenOpt::None;
194     return;
195   case 1:
196     CGOptLevel = CodeGenOpt::Less;
197     return;
198   case 2:
199     CGOptLevel = CodeGenOpt::Default;
200     return;
201   case 3:
202     CGOptLevel = CodeGenOpt::Aggressive;
203     return;
204   }
205   llvm_unreachable("Unknown optimization level!");
206 }
207 
208 bool LTOCodeGenerator::writeMergedModules(StringRef Path) {
209   if (!determineTarget())
210     return false;
211 
212   // We always run the verifier once on the merged module.
213   verifyMergedModuleOnce();
214 
215   // mark which symbols can not be internalized
216   applyScopeRestrictions();
217 
218   // create output file
219   std::error_code EC;
220   ToolOutputFile Out(Path, EC, sys::fs::F_None);
221   if (EC) {
222     std::string ErrMsg = "could not open bitcode file for writing: ";
223     ErrMsg += Path.str() + ": " + EC.message();
224     emitError(ErrMsg);
225     return false;
226   }
227 
228   // write bitcode to it
229   WriteBitcodeToFile(*MergedModule, Out.os(), ShouldEmbedUselists);
230   Out.os().close();
231 
232   if (Out.os().has_error()) {
233     std::string ErrMsg = "could not write bitcode file: ";
234     ErrMsg += Path.str() + ": " + Out.os().error().message();
235     emitError(ErrMsg);
236     Out.os().clear_error();
237     return false;
238   }
239 
240   Out.keep();
241   return true;
242 }
243 
244 bool LTOCodeGenerator::compileOptimizedToFile(const char **Name) {
245   // make unique temp output file to put generated code
246   SmallString<128> Filename;
247   int FD;
248 
249   StringRef Extension
250       (FileType == TargetMachine::CGFT_AssemblyFile ? "s" : "o");
251 
252   std::error_code EC =
253       sys::fs::createTemporaryFile("lto-llvm", Extension, FD, Filename);
254   if (EC) {
255     emitError(EC.message());
256     return false;
257   }
258 
259   // generate object file
260   ToolOutputFile objFile(Filename, FD);
261 
262   bool genResult = compileOptimized(&objFile.os());
263   objFile.os().close();
264   if (objFile.os().has_error()) {
265     emitError((Twine("could not write object file: ") + Filename + ": " +
266                objFile.os().error().message())
267                   .str());
268     objFile.os().clear_error();
269     sys::fs::remove(Twine(Filename));
270     return false;
271   }
272 
273   objFile.keep();
274   if (!genResult) {
275     sys::fs::remove(Twine(Filename));
276     return false;
277   }
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 =
292       MemoryBuffer::getFile(name, -1, 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, bool DisableVerify,
306                                        bool DisableInline,
307                                        bool DisableGVNLoadPRE,
308                                        bool DisableVectorization) {
309   if (!optimize(DisableVerify, DisableInline, DisableGVNLoadPRE,
310                 DisableVectorization))
311     return false;
312 
313   return compileOptimizedToFile(Name);
314 }
315 
316 std::unique_ptr<MemoryBuffer>
317 LTOCodeGenerator::compile(bool DisableVerify, bool DisableInline,
318                           bool DisableGVNLoadPRE, bool DisableVectorization) {
319   if (!optimize(DisableVerify, DisableInline, DisableGVNLoadPRE,
320                 DisableVectorization))
321     return nullptr;
322 
323   return compileOptimized();
324 }
325 
326 bool LTOCodeGenerator::determineTarget() {
327   if (TargetMach)
328     return true;
329 
330   TripleStr = MergedModule->getTargetTriple();
331   if (TripleStr.empty()) {
332     TripleStr = sys::getDefaultTargetTriple();
333     MergedModule->setTargetTriple(TripleStr);
334   }
335   llvm::Triple Triple(TripleStr);
336 
337   // create target machine from info for merged modules
338   std::string ErrMsg;
339   MArch = TargetRegistry::lookupTarget(TripleStr, ErrMsg);
340   if (!MArch) {
341     emitError(ErrMsg);
342     return false;
343   }
344 
345   // Construct LTOModule, hand over ownership of module and target. Use MAttr as
346   // the default set of features.
347   SubtargetFeatures Features(MAttr);
348   Features.getDefaultSubtargetFeatures(Triple);
349   FeatureStr = Features.getString();
350   // Set a default CPU for Darwin triples.
351   if (MCpu.empty() && Triple.isOSDarwin()) {
352     if (Triple.getArch() == llvm::Triple::x86_64)
353       MCpu = "core2";
354     else if (Triple.getArch() == llvm::Triple::x86)
355       MCpu = "yonah";
356     else if (Triple.getArch() == llvm::Triple::aarch64)
357       MCpu = "cyclone";
358   }
359 
360   TargetMach = createTargetMachine();
361   return true;
362 }
363 
364 std::unique_ptr<TargetMachine> LTOCodeGenerator::createTargetMachine() {
365   return std::unique_ptr<TargetMachine>(MArch->createTargetMachine(
366       TripleStr, MCpu, FeatureStr, Options, RelocModel, None, 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(bool DisableVerify, bool DisableInline,
508                                 bool DisableGVNLoadPRE,
509                                 bool DisableVectorization) {
510   if (!this->determineTarget())
511     return false;
512 
513   auto DiagFileOrErr = lto::setupOptimizationRemarks(
514       Context, LTORemarksFilename, LTORemarksPasses, LTOPassRemarksWithHotness);
515   if (!DiagFileOrErr) {
516     errs() << "Error: " << toString(DiagFileOrErr.takeError()) << "\n";
517     report_fatal_error("Can't get an output file for the remarks");
518   }
519   DiagnosticOutputFile = std::move(*DiagFileOrErr);
520 
521   // We always run the verifier once on the merged module, the `DisableVerify`
522   // parameter only applies to subsequent verify.
523   verifyMergedModuleOnce();
524 
525   // Mark which symbols can not be internalized
526   this->applyScopeRestrictions();
527 
528   // Instantiate the pass manager to organize the passes.
529   legacy::PassManager passes;
530 
531   // Add an appropriate DataLayout instance for this module...
532   MergedModule->setDataLayout(TargetMach->createDataLayout());
533 
534   passes.add(
535       createTargetTransformInfoWrapperPass(TargetMach->getTargetIRAnalysis()));
536 
537   Triple TargetTriple(TargetMach->getTargetTriple());
538   PassManagerBuilder PMB;
539   PMB.DisableGVNLoadPRE = DisableGVNLoadPRE;
540   PMB.LoopVectorize = !DisableVectorization;
541   PMB.SLPVectorize = !DisableVectorization;
542   if (!DisableInline)
543     PMB.Inliner = createFunctionInliningPass();
544   PMB.LibraryInfo = new TargetLibraryInfoImpl(TargetTriple);
545   if (Freestanding)
546     PMB.LibraryInfo->disableAllFunctions();
547   PMB.OptLevel = OptLevel;
548   PMB.VerifyInput = !DisableVerify;
549   PMB.VerifyOutput = !DisableVerify;
550 
551   PMB.populateLTOPassManager(passes);
552 
553   // Run our queue of passes all at once now, efficiently.
554   passes.run(*MergedModule);
555 
556   return true;
557 }
558 
559 bool LTOCodeGenerator::compileOptimized(ArrayRef<raw_pwrite_stream *> Out) {
560   if (!this->determineTarget())
561     return false;
562 
563   // We always run the verifier once on the merged module.  If it has already
564   // been called in optimize(), this call will return early.
565   verifyMergedModuleOnce();
566 
567   legacy::PassManager preCodeGenPasses;
568 
569   // If the bitcode files contain ARC code and were compiled with optimization,
570   // the ObjCARCContractPass must be run, so do it unconditionally here.
571   preCodeGenPasses.add(createObjCARCContractPass());
572   preCodeGenPasses.run(*MergedModule);
573 
574   // Re-externalize globals that may have been internalized to increase scope
575   // for splitting
576   restoreLinkageForExternals();
577 
578   // Do code generation. We need to preserve the module in case the client calls
579   // writeMergedModules() after compilation, but we only need to allow this at
580   // parallelism level 1. This is achieved by having splitCodeGen return the
581   // original module at parallelism level 1 which we then assign back to
582   // MergedModule.
583   MergedModule = splitCodeGen(std::move(MergedModule), Out, {},
584                               [&]() { return createTargetMachine(); }, FileType,
585                               ShouldRestoreGlobalsLinkage);
586 
587   // If statistics were requested, print them out after codegen.
588   if (llvm::AreStatisticsEnabled())
589     llvm::PrintStatistics();
590   reportAndResetTimings();
591 
592   finishOptimizationRemarks();
593 
594   return true;
595 }
596 
597 /// setCodeGenDebugOptions - Set codegen debugging options to aid in debugging
598 /// LTO problems.
599 void LTOCodeGenerator::setCodeGenDebugOptions(StringRef Options) {
600   for (std::pair<StringRef, StringRef> o = getToken(Options); !o.first.empty();
601        o = getToken(o.second))
602     CodegenOptions.push_back(o.first);
603 }
604 
605 void LTOCodeGenerator::parseCodeGenDebugOptions() {
606   // if options were requested, set them
607   if (!CodegenOptions.empty()) {
608     // ParseCommandLineOptions() expects argv[0] to be program name.
609     std::vector<const char *> CodegenArgv(1, "libLLVMLTO");
610     for (std::string &Arg : CodegenOptions)
611       CodegenArgv.push_back(Arg.c_str());
612     cl::ParseCommandLineOptions(CodegenArgv.size(), CodegenArgv.data());
613   }
614 }
615 
616 
617 void LTOCodeGenerator::DiagnosticHandler(const DiagnosticInfo &DI) {
618   // Map the LLVM internal diagnostic severity to the LTO diagnostic severity.
619   lto_codegen_diagnostic_severity_t Severity;
620   switch (DI.getSeverity()) {
621   case DS_Error:
622     Severity = LTO_DS_ERROR;
623     break;
624   case DS_Warning:
625     Severity = LTO_DS_WARNING;
626     break;
627   case DS_Remark:
628     Severity = LTO_DS_REMARK;
629     break;
630   case DS_Note:
631     Severity = LTO_DS_NOTE;
632     break;
633   }
634   // Create the string that will be reported to the external diagnostic handler.
635   std::string MsgStorage;
636   raw_string_ostream Stream(MsgStorage);
637   DiagnosticPrinterRawOStream DP(Stream);
638   DI.print(DP);
639   Stream.flush();
640 
641   // If this method has been called it means someone has set up an external
642   // diagnostic handler. Assert on that.
643   assert(DiagHandler && "Invalid diagnostic handler");
644   (*DiagHandler)(Severity, MsgStorage.c_str(), DiagContext);
645 }
646 
647 namespace {
648 struct LTODiagnosticHandler : public DiagnosticHandler {
649   LTOCodeGenerator *CodeGenerator;
650   LTODiagnosticHandler(LTOCodeGenerator *CodeGenPtr)
651       : CodeGenerator(CodeGenPtr) {}
652   bool handleDiagnostics(const DiagnosticInfo &DI) override {
653     CodeGenerator->DiagnosticHandler(DI);
654     return true;
655   }
656 };
657 }
658 
659 void
660 LTOCodeGenerator::setDiagnosticHandler(lto_diagnostic_handler_t DiagHandler,
661                                        void *Ctxt) {
662   this->DiagHandler = DiagHandler;
663   this->DiagContext = Ctxt;
664   if (!DiagHandler)
665     return Context.setDiagnosticHandler(nullptr);
666   // Register the LTOCodeGenerator stub in the LLVMContext to forward the
667   // diagnostic to the external DiagHandler.
668   Context.setDiagnosticHandler(llvm::make_unique<LTODiagnosticHandler>(this),
669                                true);
670 }
671 
672 namespace {
673 class LTODiagnosticInfo : public DiagnosticInfo {
674   const Twine &Msg;
675 public:
676   LTODiagnosticInfo(const Twine &DiagMsg, DiagnosticSeverity Severity=DS_Error)
677       : DiagnosticInfo(DK_Linker, Severity), Msg(DiagMsg) {}
678   void print(DiagnosticPrinter &DP) const override { DP << Msg; }
679 };
680 }
681 
682 void LTOCodeGenerator::emitError(const std::string &ErrMsg) {
683   if (DiagHandler)
684     (*DiagHandler)(LTO_DS_ERROR, ErrMsg.c_str(), DiagContext);
685   else
686     Context.diagnose(LTODiagnosticInfo(ErrMsg));
687 }
688 
689 void LTOCodeGenerator::emitWarning(const std::string &ErrMsg) {
690   if (DiagHandler)
691     (*DiagHandler)(LTO_DS_WARNING, ErrMsg.c_str(), DiagContext);
692   else
693     Context.diagnose(LTODiagnosticInfo(ErrMsg, DS_Warning));
694 }
695