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