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