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 #include "llvm/ADT/StringExtras.h"
17 #include "llvm/Analysis/Passes.h"
18 #include "llvm/Analysis/TargetLibraryInfo.h"
19 #include "llvm/Analysis/TargetTransformInfo.h"
20 #include "llvm/Bitcode/ReaderWriter.h"
21 #include "llvm/CodeGen/ParallelCG.h"
22 #include "llvm/CodeGen/RuntimeLibcalls.h"
23 #include "llvm/Config/config.h"
24 #include "llvm/IR/Constants.h"
25 #include "llvm/IR/DataLayout.h"
26 #include "llvm/IR/DerivedTypes.h"
27 #include "llvm/IR/DiagnosticInfo.h"
28 #include "llvm/IR/DiagnosticPrinter.h"
29 #include "llvm/IR/LLVMContext.h"
30 #include "llvm/IR/LegacyPassManager.h"
31 #include "llvm/IR/Mangler.h"
32 #include "llvm/IR/Module.h"
33 #include "llvm/IR/Verifier.h"
34 #include "llvm/InitializePasses.h"
35 #include "llvm/LTO/LTOModule.h"
36 #include "llvm/Linker/Linker.h"
37 #include "llvm/MC/MCAsmInfo.h"
38 #include "llvm/MC/MCContext.h"
39 #include "llvm/MC/SubtargetFeature.h"
40 #include "llvm/Support/CommandLine.h"
41 #include "llvm/Support/FileSystem.h"
42 #include "llvm/Support/Host.h"
43 #include "llvm/Support/MemoryBuffer.h"
44 #include "llvm/Support/Signals.h"
45 #include "llvm/Support/TargetRegistry.h"
46 #include "llvm/Support/TargetSelect.h"
47 #include "llvm/Support/ToolOutputFile.h"
48 #include "llvm/Support/raw_ostream.h"
49 #include "llvm/Target/TargetLowering.h"
50 #include "llvm/Target/TargetOptions.h"
51 #include "llvm/Target/TargetRegisterInfo.h"
52 #include "llvm/Target/TargetSubtargetInfo.h"
53 #include "llvm/Transforms/IPO.h"
54 #include "llvm/Transforms/IPO/PassManagerBuilder.h"
55 #include "llvm/Transforms/ObjCARC.h"
56 #include <system_error>
57 using namespace llvm;
58 
59 const char* LTOCodeGenerator::getVersionString() {
60 #ifdef LLVM_VERSION_INFO
61   return PACKAGE_NAME " version " PACKAGE_VERSION ", " LLVM_VERSION_INFO;
62 #else
63   return PACKAGE_NAME " version " PACKAGE_VERSION;
64 #endif
65 }
66 
67 LTOCodeGenerator::LTOCodeGenerator(LLVMContext &Context)
68     : Context(Context), MergedModule(new Module("ld-temp.o", Context)),
69       TheLinker(new Linker(*MergedModule)) {
70   initializeLTOPasses();
71 }
72 
73 LTOCodeGenerator::~LTOCodeGenerator() {}
74 
75 // Initialize LTO passes. Please keep this function in sync with
76 // PassManagerBuilder::populateLTOPassManager(), and make sure all LTO
77 // passes are initialized.
78 void LTOCodeGenerator::initializeLTOPasses() {
79   PassRegistry &R = *PassRegistry::getPassRegistry();
80 
81   initializeInternalizePassPass(R);
82   initializeIPSCCPPass(R);
83   initializeGlobalOptPass(R);
84   initializeConstantMergePass(R);
85   initializeDAHPass(R);
86   initializeInstructionCombiningPassPass(R);
87   initializeSimpleInlinerPass(R);
88   initializePruneEHPass(R);
89   initializeGlobalDCEPass(R);
90   initializeArgPromotionPass(R);
91   initializeJumpThreadingPass(R);
92   initializeSROALegacyPassPass(R);
93   initializeSROA_DTPass(R);
94   initializeSROA_SSAUpPass(R);
95   initializePostOrderFunctionAttrsPass(R);
96   initializeReversePostOrderFunctionAttrsPass(R);
97   initializeGlobalsAAWrapperPassPass(R);
98   initializeLICMPass(R);
99   initializeMergedLoadStoreMotionPass(R);
100   initializeGVNPass(R);
101   initializeMemCpyOptPass(R);
102   initializeDCEPass(R);
103   initializeCFGSimplifyPassPass(R);
104 }
105 
106 bool LTOCodeGenerator::addModule(LTOModule *Mod) {
107   assert(&Mod->getModule().getContext() == &Context &&
108          "Expected module in same context");
109 
110   bool ret = TheLinker->linkInModule(Mod->takeModule());
111 
112   const std::vector<const char *> &undefs = Mod->getAsmUndefinedRefs();
113   for (int i = 0, e = undefs.size(); i != e; ++i)
114     AsmUndefinedRefs[undefs[i]] = 1;
115 
116   return !ret;
117 }
118 
119 void LTOCodeGenerator::setModule(std::unique_ptr<LTOModule> Mod) {
120   assert(&Mod->getModule().getContext() == &Context &&
121          "Expected module in same context");
122 
123   AsmUndefinedRefs.clear();
124 
125   MergedModule = Mod->takeModule();
126   TheLinker = make_unique<Linker>(*MergedModule);
127 
128   const std::vector<const char*> &Undefs = Mod->getAsmUndefinedRefs();
129   for (int I = 0, E = Undefs.size(); I != E; ++I)
130     AsmUndefinedRefs[Undefs[I]] = 1;
131 }
132 
133 void LTOCodeGenerator::setTargetOptions(TargetOptions Options) {
134   this->Options = Options;
135 }
136 
137 void LTOCodeGenerator::setDebugInfo(lto_debug_model Debug) {
138   switch (Debug) {
139   case LTO_DEBUG_MODEL_NONE:
140     EmitDwarfDebugInfo = false;
141     return;
142 
143   case LTO_DEBUG_MODEL_DWARF:
144     EmitDwarfDebugInfo = true;
145     return;
146   }
147   llvm_unreachable("Unknown debug format!");
148 }
149 
150 void LTOCodeGenerator::setOptLevel(unsigned Level) {
151   OptLevel = Level;
152   switch (OptLevel) {
153   case 0:
154     CGOptLevel = CodeGenOpt::None;
155     break;
156   case 1:
157     CGOptLevel = CodeGenOpt::Less;
158     break;
159   case 2:
160     CGOptLevel = CodeGenOpt::Default;
161     break;
162   case 3:
163     CGOptLevel = CodeGenOpt::Aggressive;
164     break;
165   }
166 }
167 
168 bool LTOCodeGenerator::writeMergedModules(const char *Path) {
169   if (!determineTarget())
170     return false;
171 
172   // mark which symbols can not be internalized
173   applyScopeRestrictions();
174 
175   // create output file
176   std::error_code EC;
177   tool_output_file Out(Path, EC, sys::fs::F_None);
178   if (EC) {
179     std::string ErrMsg = "could not open bitcode file for writing: ";
180     ErrMsg += Path;
181     emitError(ErrMsg);
182     return false;
183   }
184 
185   // write bitcode to it
186   WriteBitcodeToFile(MergedModule.get(), Out.os(), ShouldEmbedUselists);
187   Out.os().close();
188 
189   if (Out.os().has_error()) {
190     std::string ErrMsg = "could not write bitcode file: ";
191     ErrMsg += Path;
192     emitError(ErrMsg);
193     Out.os().clear_error();
194     return false;
195   }
196 
197   Out.keep();
198   return true;
199 }
200 
201 bool LTOCodeGenerator::compileOptimizedToFile(const char **Name) {
202   // make unique temp output file to put generated code
203   SmallString<128> Filename;
204   int FD;
205 
206   const char *Extension =
207       (FileType == TargetMachine::CGFT_AssemblyFile ? "s" : "o");
208 
209   std::error_code EC =
210       sys::fs::createTemporaryFile("lto-llvm", Extension, FD, Filename);
211   if (EC) {
212     emitError(EC.message());
213     return false;
214   }
215 
216   // generate object file
217   tool_output_file objFile(Filename.c_str(), FD);
218 
219   bool genResult = compileOptimized(&objFile.os());
220   objFile.os().close();
221   if (objFile.os().has_error()) {
222     objFile.os().clear_error();
223     sys::fs::remove(Twine(Filename));
224     return false;
225   }
226 
227   objFile.keep();
228   if (!genResult) {
229     sys::fs::remove(Twine(Filename));
230     return false;
231   }
232 
233   NativeObjectPath = Filename.c_str();
234   *Name = NativeObjectPath.c_str();
235   return true;
236 }
237 
238 std::unique_ptr<MemoryBuffer>
239 LTOCodeGenerator::compileOptimized() {
240   const char *name;
241   if (!compileOptimizedToFile(&name))
242     return nullptr;
243 
244   // read .o file into memory buffer
245   ErrorOr<std::unique_ptr<MemoryBuffer>> BufferOrErr =
246       MemoryBuffer::getFile(name, -1, false);
247   if (std::error_code EC = BufferOrErr.getError()) {
248     emitError(EC.message());
249     sys::fs::remove(NativeObjectPath);
250     return nullptr;
251   }
252 
253   // remove temp files
254   sys::fs::remove(NativeObjectPath);
255 
256   return std::move(*BufferOrErr);
257 }
258 
259 bool LTOCodeGenerator::compile_to_file(const char **Name, bool DisableVerify,
260                                        bool DisableInline,
261                                        bool DisableGVNLoadPRE,
262                                        bool DisableVectorization) {
263   if (!optimize(DisableVerify, DisableInline, DisableGVNLoadPRE,
264                 DisableVectorization))
265     return false;
266 
267   return compileOptimizedToFile(Name);
268 }
269 
270 std::unique_ptr<MemoryBuffer>
271 LTOCodeGenerator::compile(bool DisableVerify, bool DisableInline,
272                           bool DisableGVNLoadPRE, bool DisableVectorization) {
273   if (!optimize(DisableVerify, DisableInline, DisableGVNLoadPRE,
274                 DisableVectorization))
275     return nullptr;
276 
277   return compileOptimized();
278 }
279 
280 bool LTOCodeGenerator::determineTarget() {
281   if (TargetMach)
282     return true;
283 
284   std::string TripleStr = MergedModule->getTargetTriple();
285   if (TripleStr.empty()) {
286     TripleStr = sys::getDefaultTargetTriple();
287     MergedModule->setTargetTriple(TripleStr);
288   }
289   llvm::Triple Triple(TripleStr);
290 
291   // create target machine from info for merged modules
292   std::string ErrMsg;
293   const Target *march = TargetRegistry::lookupTarget(TripleStr, ErrMsg);
294   if (!march) {
295     emitError(ErrMsg);
296     return false;
297   }
298 
299   // Construct LTOModule, hand over ownership of module and target. Use MAttr as
300   // the default set of features.
301   SubtargetFeatures Features(MAttr);
302   Features.getDefaultSubtargetFeatures(Triple);
303   FeatureStr = Features.getString();
304   // Set a default CPU for Darwin triples.
305   if (MCpu.empty() && Triple.isOSDarwin()) {
306     if (Triple.getArch() == llvm::Triple::x86_64)
307       MCpu = "core2";
308     else if (Triple.getArch() == llvm::Triple::x86)
309       MCpu = "yonah";
310     else if (Triple.getArch() == llvm::Triple::aarch64)
311       MCpu = "cyclone";
312   }
313 
314   TargetMach.reset(march->createTargetMachine(TripleStr, MCpu, FeatureStr,
315                                               Options, RelocModel,
316                                               CodeModel::Default, CGOptLevel));
317   return true;
318 }
319 
320 void LTOCodeGenerator::
321 applyRestriction(GlobalValue &GV,
322                  ArrayRef<StringRef> Libcalls,
323                  std::vector<const char*> &MustPreserveList,
324                  SmallPtrSetImpl<GlobalValue*> &AsmUsed,
325                  Mangler &Mangler) {
326   // There are no restrictions to apply to declarations.
327   if (GV.isDeclaration())
328     return;
329 
330   // There is nothing more restrictive than private linkage.
331   if (GV.hasPrivateLinkage())
332     return;
333 
334   SmallString<64> Buffer;
335   TargetMach->getNameWithPrefix(Buffer, &GV, Mangler);
336 
337   if (MustPreserveSymbols.count(Buffer))
338     MustPreserveList.push_back(GV.getName().data());
339   if (AsmUndefinedRefs.count(Buffer))
340     AsmUsed.insert(&GV);
341 
342   // Conservatively append user-supplied runtime library functions to
343   // llvm.compiler.used.  These could be internalized and deleted by
344   // optimizations like -globalopt, causing problems when later optimizations
345   // add new library calls (e.g., llvm.memset => memset and printf => puts).
346   // Leave it to the linker to remove any dead code (e.g. with -dead_strip).
347   if (isa<Function>(GV) &&
348       std::binary_search(Libcalls.begin(), Libcalls.end(), GV.getName()))
349     AsmUsed.insert(&GV);
350 
351   // Record the linkage type of non-local symbols so they can be restored prior
352   // to module splitting.
353   if (ShouldRestoreGlobalsLinkage && !GV.hasAvailableExternallyLinkage() &&
354       !GV.hasLocalLinkage() && GV.hasName())
355     ExternalSymbols.insert(std::make_pair(GV.getName(), GV.getLinkage()));
356 }
357 
358 static void findUsedValues(GlobalVariable *LLVMUsed,
359                            SmallPtrSetImpl<GlobalValue*> &UsedValues) {
360   if (!LLVMUsed) return;
361 
362   ConstantArray *Inits = cast<ConstantArray>(LLVMUsed->getInitializer());
363   for (unsigned i = 0, e = Inits->getNumOperands(); i != e; ++i)
364     if (GlobalValue *GV =
365         dyn_cast<GlobalValue>(Inits->getOperand(i)->stripPointerCasts()))
366       UsedValues.insert(GV);
367 }
368 
369 // Collect names of runtime library functions. User-defined functions with the
370 // same names are added to llvm.compiler.used to prevent them from being
371 // deleted by optimizations.
372 static void accumulateAndSortLibcalls(std::vector<StringRef> &Libcalls,
373                                       const TargetLibraryInfo& TLI,
374                                       const Module &Mod,
375                                       const TargetMachine &TM) {
376   // TargetLibraryInfo has info on C runtime library calls on the current
377   // target.
378   for (unsigned I = 0, E = static_cast<unsigned>(LibFunc::NumLibFuncs);
379        I != E; ++I) {
380     LibFunc::Func F = static_cast<LibFunc::Func>(I);
381     if (TLI.has(F))
382       Libcalls.push_back(TLI.getName(F));
383   }
384 
385   SmallPtrSet<const TargetLowering *, 1> TLSet;
386 
387   for (const Function &F : Mod) {
388     const TargetLowering *Lowering =
389         TM.getSubtargetImpl(F)->getTargetLowering();
390 
391     if (Lowering && TLSet.insert(Lowering).second)
392       // TargetLowering has info on library calls that CodeGen expects to be
393       // available, both from the C runtime and compiler-rt.
394       for (unsigned I = 0, E = static_cast<unsigned>(RTLIB::UNKNOWN_LIBCALL);
395            I != E; ++I)
396         if (const char *Name =
397                 Lowering->getLibcallName(static_cast<RTLIB::Libcall>(I)))
398           Libcalls.push_back(Name);
399   }
400 
401   array_pod_sort(Libcalls.begin(), Libcalls.end());
402   Libcalls.erase(std::unique(Libcalls.begin(), Libcalls.end()),
403                  Libcalls.end());
404 }
405 
406 void LTOCodeGenerator::applyScopeRestrictions() {
407   if (ScopeRestrictionsDone || !ShouldInternalize)
408     return;
409 
410   // Start off with a verification pass.
411   legacy::PassManager passes;
412   passes.add(createVerifierPass());
413 
414   // mark which symbols can not be internalized
415   Mangler Mangler;
416   std::vector<const char*> MustPreserveList;
417   SmallPtrSet<GlobalValue*, 8> AsmUsed;
418   std::vector<StringRef> Libcalls;
419   TargetLibraryInfoImpl TLII(Triple(TargetMach->getTargetTriple()));
420   TargetLibraryInfo TLI(TLII);
421 
422   accumulateAndSortLibcalls(Libcalls, TLI, *MergedModule, *TargetMach);
423 
424   for (Function &f : *MergedModule)
425     applyRestriction(f, Libcalls, MustPreserveList, AsmUsed, Mangler);
426   for (GlobalVariable &v : MergedModule->globals())
427     applyRestriction(v, Libcalls, MustPreserveList, AsmUsed, Mangler);
428   for (GlobalAlias &a : MergedModule->aliases())
429     applyRestriction(a, Libcalls, MustPreserveList, AsmUsed, Mangler);
430 
431   GlobalVariable *LLVMCompilerUsed =
432     MergedModule->getGlobalVariable("llvm.compiler.used");
433   findUsedValues(LLVMCompilerUsed, AsmUsed);
434   if (LLVMCompilerUsed)
435     LLVMCompilerUsed->eraseFromParent();
436 
437   if (!AsmUsed.empty()) {
438     llvm::Type *i8PTy = llvm::Type::getInt8PtrTy(Context);
439     std::vector<Constant*> asmUsed2;
440     for (auto *GV : AsmUsed) {
441       Constant *c = ConstantExpr::getBitCast(GV, i8PTy);
442       asmUsed2.push_back(c);
443     }
444 
445     llvm::ArrayType *ATy = llvm::ArrayType::get(i8PTy, asmUsed2.size());
446     LLVMCompilerUsed =
447       new llvm::GlobalVariable(*MergedModule, ATy, false,
448                                llvm::GlobalValue::AppendingLinkage,
449                                llvm::ConstantArray::get(ATy, asmUsed2),
450                                "llvm.compiler.used");
451 
452     LLVMCompilerUsed->setSection("llvm.metadata");
453   }
454 
455   passes.add(createInternalizePass(MustPreserveList));
456 
457   // apply scope restrictions
458   passes.run(*MergedModule);
459 
460   ScopeRestrictionsDone = true;
461 }
462 
463 /// Restore original linkage for symbols that may have been internalized
464 void LTOCodeGenerator::restoreLinkageForExternals() {
465   if (!ShouldInternalize || !ShouldRestoreGlobalsLinkage)
466     return;
467 
468   assert(ScopeRestrictionsDone &&
469          "Cannot externalize without internalization!");
470 
471   if (ExternalSymbols.empty())
472     return;
473 
474   auto externalize = [this](GlobalValue &GV) {
475     if (!GV.hasLocalLinkage() || !GV.hasName())
476       return;
477 
478     auto I = ExternalSymbols.find(GV.getName());
479     if (I == ExternalSymbols.end())
480       return;
481 
482     GV.setLinkage(I->second);
483   };
484 
485   std::for_each(MergedModule->begin(), MergedModule->end(), externalize);
486   std::for_each(MergedModule->global_begin(), MergedModule->global_end(),
487                 externalize);
488   std::for_each(MergedModule->alias_begin(), MergedModule->alias_end(),
489                 externalize);
490 }
491 
492 /// Optimize merged modules using various IPO passes
493 bool LTOCodeGenerator::optimize(bool DisableVerify, bool DisableInline,
494                                 bool DisableGVNLoadPRE,
495                                 bool DisableVectorization) {
496   if (!this->determineTarget())
497     return false;
498 
499   // Mark which symbols can not be internalized
500   this->applyScopeRestrictions();
501 
502   // Instantiate the pass manager to organize the passes.
503   legacy::PassManager passes;
504 
505   // Add an appropriate DataLayout instance for this module...
506   MergedModule->setDataLayout(TargetMach->createDataLayout());
507 
508   passes.add(
509       createTargetTransformInfoWrapperPass(TargetMach->getTargetIRAnalysis()));
510 
511   Triple TargetTriple(TargetMach->getTargetTriple());
512   PassManagerBuilder PMB;
513   PMB.DisableGVNLoadPRE = DisableGVNLoadPRE;
514   PMB.LoopVectorize = !DisableVectorization;
515   PMB.SLPVectorize = !DisableVectorization;
516   if (!DisableInline)
517     PMB.Inliner = createFunctionInliningPass();
518   PMB.LibraryInfo = new TargetLibraryInfoImpl(TargetTriple);
519   PMB.OptLevel = OptLevel;
520   PMB.VerifyInput = !DisableVerify;
521   PMB.VerifyOutput = !DisableVerify;
522 
523   PMB.populateLTOPassManager(passes);
524 
525   // Run our queue of passes all at once now, efficiently.
526   passes.run(*MergedModule);
527 
528   return true;
529 }
530 
531 bool LTOCodeGenerator::compileOptimized(ArrayRef<raw_pwrite_stream *> Out) {
532   if (!this->determineTarget())
533     return false;
534 
535   legacy::PassManager preCodeGenPasses;
536 
537   // If the bitcode files contain ARC code and were compiled with optimization,
538   // the ObjCARCContractPass must be run, so do it unconditionally here.
539   preCodeGenPasses.add(createObjCARCContractPass());
540   preCodeGenPasses.run(*MergedModule);
541 
542   // Re-externalize globals that may have been internalized to increase scope
543   // for splitting
544   restoreLinkageForExternals();
545 
546   // Do code generation. We need to preserve the module in case the client calls
547   // writeMergedModules() after compilation, but we only need to allow this at
548   // parallelism level 1. This is achieved by having splitCodeGen return the
549   // original module at parallelism level 1 which we then assign back to
550   // MergedModule.
551   MergedModule =
552       splitCodeGen(std::move(MergedModule), Out, MCpu, FeatureStr, Options,
553                    RelocModel, CodeModel::Default, CGOptLevel, FileType,
554                    ShouldRestoreGlobalsLinkage);
555 
556   return true;
557 }
558 
559 /// setCodeGenDebugOptions - Set codegen debugging options to aid in debugging
560 /// LTO problems.
561 void LTOCodeGenerator::setCodeGenDebugOptions(const char *Options) {
562   for (std::pair<StringRef, StringRef> o = getToken(Options); !o.first.empty();
563        o = getToken(o.second))
564     CodegenOptions.push_back(o.first);
565 }
566 
567 void LTOCodeGenerator::parseCodeGenDebugOptions() {
568   // if options were requested, set them
569   if (!CodegenOptions.empty()) {
570     // ParseCommandLineOptions() expects argv[0] to be program name.
571     std::vector<const char *> CodegenArgv(1, "libLLVMLTO");
572     for (std::string &Arg : CodegenOptions)
573       CodegenArgv.push_back(Arg.c_str());
574     cl::ParseCommandLineOptions(CodegenArgv.size(), CodegenArgv.data());
575   }
576 }
577 
578 void LTOCodeGenerator::DiagnosticHandler(const DiagnosticInfo &DI,
579                                          void *Context) {
580   ((LTOCodeGenerator *)Context)->DiagnosticHandler2(DI);
581 }
582 
583 void LTOCodeGenerator::DiagnosticHandler2(const DiagnosticInfo &DI) {
584   // Map the LLVM internal diagnostic severity to the LTO diagnostic severity.
585   lto_codegen_diagnostic_severity_t Severity;
586   switch (DI.getSeverity()) {
587   case DS_Error:
588     Severity = LTO_DS_ERROR;
589     break;
590   case DS_Warning:
591     Severity = LTO_DS_WARNING;
592     break;
593   case DS_Remark:
594     Severity = LTO_DS_REMARK;
595     break;
596   case DS_Note:
597     Severity = LTO_DS_NOTE;
598     break;
599   }
600   // Create the string that will be reported to the external diagnostic handler.
601   std::string MsgStorage;
602   raw_string_ostream Stream(MsgStorage);
603   DiagnosticPrinterRawOStream DP(Stream);
604   DI.print(DP);
605   Stream.flush();
606 
607   // If this method has been called it means someone has set up an external
608   // diagnostic handler. Assert on that.
609   assert(DiagHandler && "Invalid diagnostic handler");
610   (*DiagHandler)(Severity, MsgStorage.c_str(), DiagContext);
611 }
612 
613 void
614 LTOCodeGenerator::setDiagnosticHandler(lto_diagnostic_handler_t DiagHandler,
615                                        void *Ctxt) {
616   this->DiagHandler = DiagHandler;
617   this->DiagContext = Ctxt;
618   if (!DiagHandler)
619     return Context.setDiagnosticHandler(nullptr, nullptr);
620   // Register the LTOCodeGenerator stub in the LLVMContext to forward the
621   // diagnostic to the external DiagHandler.
622   Context.setDiagnosticHandler(LTOCodeGenerator::DiagnosticHandler, this,
623                                /* RespectFilters */ true);
624 }
625 
626 namespace {
627 class LTODiagnosticInfo : public DiagnosticInfo {
628   const Twine &Msg;
629 public:
630   LTODiagnosticInfo(const Twine &DiagMsg, DiagnosticSeverity Severity=DS_Error)
631       : DiagnosticInfo(DK_Linker, Severity), Msg(DiagMsg) {}
632   void print(DiagnosticPrinter &DP) const override { DP << Msg; }
633 };
634 }
635 
636 void LTOCodeGenerator::emitError(const std::string &ErrMsg) {
637   if (DiagHandler)
638     (*DiagHandler)(LTO_DS_ERROR, ErrMsg.c_str(), DiagContext);
639   else
640     Context.diagnose(LTODiagnosticInfo(ErrMsg));
641 }
642