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