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