1 //===-LTOCodeGenerator.cpp - LLVM Link Time Optimizer ---------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file implements the Link Time Optimization library. This library is
10 // intended to be used by linker to optimize code at link time.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "llvm/LTO/legacy/LTOCodeGenerator.h"
15 
16 #include "llvm/ADT/Statistic.h"
17 #include "llvm/ADT/StringExtras.h"
18 #include "llvm/Analysis/Passes.h"
19 #include "llvm/Analysis/TargetLibraryInfo.h"
20 #include "llvm/Analysis/TargetTransformInfo.h"
21 #include "llvm/Bitcode/BitcodeWriter.h"
22 #include "llvm/CodeGen/ParallelCG.h"
23 #include "llvm/CodeGen/TargetSubtargetInfo.h"
24 #include "llvm/Config/config.h"
25 #include "llvm/IR/Constants.h"
26 #include "llvm/IR/DataLayout.h"
27 #include "llvm/IR/DebugInfo.h"
28 #include "llvm/IR/DerivedTypes.h"
29 #include "llvm/IR/DiagnosticInfo.h"
30 #include "llvm/IR/DiagnosticPrinter.h"
31 #include "llvm/IR/LLVMContext.h"
32 #include "llvm/IR/LegacyPassManager.h"
33 #include "llvm/IR/Mangler.h"
34 #include "llvm/IR/Module.h"
35 #include "llvm/IR/PassTimingInfo.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/TargetOptions.h"
56 #include "llvm/Transforms/IPO.h"
57 #include "llvm/Transforms/IPO/Internalize.h"
58 #include "llvm/Transforms/IPO/PassManagerBuilder.h"
59 #include "llvm/Transforms/ObjCARC.h"
60 #include "llvm/Transforms/Utils/ModuleUtils.h"
61 #include <system_error>
62 using namespace llvm;
63 
64 const char* LTOCodeGenerator::getVersionString() {
65 #ifdef LLVM_VERSION_INFO
66   return PACKAGE_NAME " version " PACKAGE_VERSION ", " LLVM_VERSION_INFO;
67 #else
68   return PACKAGE_NAME " version " PACKAGE_VERSION;
69 #endif
70 }
71 
72 namespace llvm {
73 cl::opt<bool> LTODiscardValueNames(
74     "lto-discard-value-names",
75     cl::desc("Strip names from Value during LTO (other than GlobalValue)."),
76 #ifdef NDEBUG
77     cl::init(true),
78 #else
79     cl::init(false),
80 #endif
81     cl::Hidden);
82 
83 cl::opt<std::string>
84     LTORemarksFilename("lto-pass-remarks-output",
85                        cl::desc("Output filename for pass remarks"),
86                        cl::value_desc("filename"));
87 
88 cl::opt<std::string>
89     LTORemarksPasses("lto-pass-remarks-filter",
90                      cl::desc("Only record optimization remarks from passes "
91                               "whose names match the given regular expression"),
92                      cl::value_desc("regex"));
93 
94 cl::opt<bool> LTOPassRemarksWithHotness(
95     "lto-pass-remarks-with-hotness",
96     cl::desc("With PGO, include profile count in optimization remarks"),
97     cl::Hidden);
98 
99 cl::opt<std::string> LTOStatsFile(
100     "lto-stats-file",
101     cl::desc("Save statistics to the specified file"),
102     cl::Hidden);
103 }
104 
105 LTOCodeGenerator::LTOCodeGenerator(LLVMContext &Context)
106     : Context(Context), MergedModule(new Module("ld-temp.o", Context)),
107       TheLinker(new Linker(*MergedModule)) {
108   Context.setDiscardValueNames(LTODiscardValueNames);
109   Context.enableDebugTypeODRUniquing();
110   initializeLTOPasses();
111 }
112 
113 LTOCodeGenerator::~LTOCodeGenerator() {}
114 
115 // Initialize LTO passes. Please keep this function in sync with
116 // PassManagerBuilder::populateLTOPassManager(), and make sure all LTO
117 // passes are initialized.
118 void LTOCodeGenerator::initializeLTOPasses() {
119   PassRegistry &R = *PassRegistry::getPassRegistry();
120 
121   initializeInternalizeLegacyPassPass(R);
122   initializeIPSCCPLegacyPassPass(R);
123   initializeGlobalOptLegacyPassPass(R);
124   initializeConstantMergeLegacyPassPass(R);
125   initializeDAHPass(R);
126   initializeInstructionCombiningPassPass(R);
127   initializeSimpleInlinerPass(R);
128   initializePruneEHPass(R);
129   initializeGlobalDCELegacyPassPass(R);
130   initializeArgPromotionPass(R);
131   initializeJumpThreadingPass(R);
132   initializeSROALegacyPassPass(R);
133   initializeAttributorLegacyPassPass(R);
134   initializePostOrderFunctionAttrsLegacyPassPass(R);
135   initializeReversePostOrderFunctionAttrsLegacyPassPass(R);
136   initializeGlobalsAAWrapperPassPass(R);
137   initializeLegacyLICMPassPass(R);
138   initializeMergedLoadStoreMotionLegacyPassPass(R);
139   initializeGVNLegacyPassPass(R);
140   initializeMemCpyOptLegacyPassPass(R);
141   initializeDCELegacyPassPass(R);
142   initializeCFGSimplifyPassPass(R);
143 }
144 
145 void LTOCodeGenerator::setAsmUndefinedRefs(LTOModule *Mod) {
146   const std::vector<StringRef> &undefs = Mod->getAsmUndefinedRefs();
147   for (int i = 0, e = undefs.size(); i != e; ++i)
148     AsmUndefinedRefs[undefs[i]] = 1;
149 }
150 
151 bool LTOCodeGenerator::addModule(LTOModule *Mod) {
152   assert(&Mod->getModule().getContext() == &Context &&
153          "Expected module in same context");
154 
155   bool ret = TheLinker->linkInModule(Mod->takeModule());
156   setAsmUndefinedRefs(Mod);
157 
158   // We've just changed the input, so let's make sure we verify it.
159   HasVerifiedInput = false;
160 
161   return !ret;
162 }
163 
164 void LTOCodeGenerator::setModule(std::unique_ptr<LTOModule> Mod) {
165   assert(&Mod->getModule().getContext() == &Context &&
166          "Expected module in same context");
167 
168   AsmUndefinedRefs.clear();
169 
170   MergedModule = Mod->takeModule();
171   TheLinker = make_unique<Linker>(*MergedModule);
172   setAsmUndefinedRefs(&*Mod);
173 
174   // We've just changed the input, so let's make sure we verify it.
175   HasVerifiedInput = false;
176 }
177 
178 void LTOCodeGenerator::setTargetOptions(const TargetOptions &Options) {
179   this->Options = Options;
180 }
181 
182 void LTOCodeGenerator::setDebugInfo(lto_debug_model Debug) {
183   switch (Debug) {
184   case LTO_DEBUG_MODEL_NONE:
185     EmitDwarfDebugInfo = false;
186     return;
187 
188   case LTO_DEBUG_MODEL_DWARF:
189     EmitDwarfDebugInfo = true;
190     return;
191   }
192   llvm_unreachable("Unknown debug format!");
193 }
194 
195 void LTOCodeGenerator::setOptLevel(unsigned Level) {
196   OptLevel = Level;
197   switch (OptLevel) {
198   case 0:
199     CGOptLevel = CodeGenOpt::None;
200     return;
201   case 1:
202     CGOptLevel = CodeGenOpt::Less;
203     return;
204   case 2:
205     CGOptLevel = CodeGenOpt::Default;
206     return;
207   case 3:
208     CGOptLevel = CodeGenOpt::Aggressive;
209     return;
210   }
211   llvm_unreachable("Unknown optimization level!");
212 }
213 
214 bool LTOCodeGenerator::writeMergedModules(StringRef Path) {
215   if (!determineTarget())
216     return false;
217 
218   // We always run the verifier once on the merged module.
219   verifyMergedModuleOnce();
220 
221   // mark which symbols can not be internalized
222   applyScopeRestrictions();
223 
224   // create output file
225   std::error_code EC;
226   ToolOutputFile Out(Path, EC, sys::fs::F_None);
227   if (EC) {
228     std::string ErrMsg = "could not open bitcode file for writing: ";
229     ErrMsg += Path.str() + ": " + EC.message();
230     emitError(ErrMsg);
231     return false;
232   }
233 
234   // write bitcode to it
235   WriteBitcodeToFile(*MergedModule, Out.os(), ShouldEmbedUselists);
236   Out.os().close();
237 
238   if (Out.os().has_error()) {
239     std::string ErrMsg = "could not write bitcode file: ";
240     ErrMsg += Path.str() + ": " + Out.os().error().message();
241     emitError(ErrMsg);
242     Out.os().clear_error();
243     return false;
244   }
245 
246   Out.keep();
247   return true;
248 }
249 
250 bool LTOCodeGenerator::compileOptimizedToFile(const char **Name) {
251   // make unique temp output file to put generated code
252   SmallString<128> Filename;
253   int FD;
254 
255   StringRef Extension
256       (FileType == TargetMachine::CGFT_AssemblyFile ? "s" : "o");
257 
258   std::error_code EC =
259       sys::fs::createTemporaryFile("lto-llvm", Extension, FD, Filename);
260   if (EC) {
261     emitError(EC.message());
262     return false;
263   }
264 
265   // generate object file
266   ToolOutputFile objFile(Filename, FD);
267 
268   bool genResult = compileOptimized(&objFile.os());
269   objFile.os().close();
270   if (objFile.os().has_error()) {
271     emitError((Twine("could not write object file: ") + Filename + ": " +
272                objFile.os().error().message())
273                   .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   llvm::for_each(MergedModule->functions(), externalize);
485   llvm::for_each(MergedModule->globals(), externalize);
486   llvm::for_each(MergedModule->aliases(), externalize);
487 }
488 
489 void LTOCodeGenerator::verifyMergedModuleOnce() {
490   // Only run on the first call.
491   if (HasVerifiedInput)
492     return;
493   HasVerifiedInput = true;
494 
495   bool BrokenDebugInfo = false;
496   if (verifyModule(*MergedModule, &dbgs(), &BrokenDebugInfo))
497     report_fatal_error("Broken module found, compilation aborted!");
498   if (BrokenDebugInfo) {
499     emitWarning("Invalid debug info found, debug info will be stripped");
500     StripDebugInfo(*MergedModule);
501   }
502 }
503 
504 void LTOCodeGenerator::finishOptimizationRemarks() {
505   if (DiagnosticOutputFile) {
506     DiagnosticOutputFile->keep();
507     // FIXME: LTOCodeGenerator dtor is not invoked on Darwin
508     DiagnosticOutputFile->os().flush();
509   }
510 }
511 
512 /// Optimize merged modules using various IPO passes
513 bool LTOCodeGenerator::optimize(bool DisableVerify, bool DisableInline,
514                                 bool DisableGVNLoadPRE,
515                                 bool DisableVectorization) {
516   if (!this->determineTarget())
517     return false;
518 
519   auto DiagFileOrErr = lto::setupOptimizationRemarks(
520       Context, LTORemarksFilename, LTORemarksPasses, LTOPassRemarksWithHotness);
521   if (!DiagFileOrErr) {
522     errs() << "Error: " << toString(DiagFileOrErr.takeError()) << "\n";
523     report_fatal_error("Can't get an output file for the remarks");
524   }
525   DiagnosticOutputFile = std::move(*DiagFileOrErr);
526 
527   // Setup output file to emit statistics.
528   auto StatsFileOrErr = lto::setupStatsFile(LTOStatsFile);
529   if (!StatsFileOrErr) {
530     errs() << "Error: " << toString(StatsFileOrErr.takeError()) << "\n";
531     report_fatal_error("Can't get an output file for the statistics");
532   }
533   StatsFile = std::move(StatsFileOrErr.get());
534 
535   // We always run the verifier once on the merged module, the `DisableVerify`
536   // parameter only applies to subsequent verify.
537   verifyMergedModuleOnce();
538 
539   // Mark which symbols can not be internalized
540   this->applyScopeRestrictions();
541 
542   // Instantiate the pass manager to organize the passes.
543   legacy::PassManager passes;
544 
545   // Add an appropriate DataLayout instance for this module...
546   MergedModule->setDataLayout(TargetMach->createDataLayout());
547 
548   passes.add(
549       createTargetTransformInfoWrapperPass(TargetMach->getTargetIRAnalysis()));
550 
551   Triple TargetTriple(TargetMach->getTargetTriple());
552   PassManagerBuilder PMB;
553   PMB.DisableGVNLoadPRE = DisableGVNLoadPRE;
554   PMB.LoopVectorize = !DisableVectorization;
555   PMB.SLPVectorize = !DisableVectorization;
556   if (!DisableInline)
557     PMB.Inliner = createFunctionInliningPass();
558   PMB.LibraryInfo = new TargetLibraryInfoImpl(TargetTriple);
559   if (Freestanding)
560     PMB.LibraryInfo->disableAllFunctions();
561   PMB.OptLevel = OptLevel;
562   PMB.VerifyInput = !DisableVerify;
563   PMB.VerifyOutput = !DisableVerify;
564 
565   PMB.populateLTOPassManager(passes);
566 
567   // Run our queue of passes all at once now, efficiently.
568   passes.run(*MergedModule);
569 
570   return true;
571 }
572 
573 bool LTOCodeGenerator::compileOptimized(ArrayRef<raw_pwrite_stream *> Out) {
574   if (!this->determineTarget())
575     return false;
576 
577   // We always run the verifier once on the merged module.  If it has already
578   // been called in optimize(), this call will return early.
579   verifyMergedModuleOnce();
580 
581   legacy::PassManager preCodeGenPasses;
582 
583   // If the bitcode files contain ARC code and were compiled with optimization,
584   // the ObjCARCContractPass must be run, so do it unconditionally here.
585   preCodeGenPasses.add(createObjCARCContractPass());
586   preCodeGenPasses.run(*MergedModule);
587 
588   // Re-externalize globals that may have been internalized to increase scope
589   // for splitting
590   restoreLinkageForExternals();
591 
592   // Do code generation. We need to preserve the module in case the client calls
593   // writeMergedModules() after compilation, but we only need to allow this at
594   // parallelism level 1. This is achieved by having splitCodeGen return the
595   // original module at parallelism level 1 which we then assign back to
596   // MergedModule.
597   MergedModule = splitCodeGen(std::move(MergedModule), Out, {},
598                               [&]() { return createTargetMachine(); }, FileType,
599                               ShouldRestoreGlobalsLinkage);
600 
601   // If statistics were requested, save them to the specified file or
602   // print them out after codegen.
603   if (StatsFile)
604     PrintStatisticsJSON(StatsFile->os());
605   else if (AreStatisticsEnabled())
606     PrintStatistics();
607 
608   reportAndResetTimings();
609 
610   finishOptimizationRemarks();
611 
612   return true;
613 }
614 
615 /// setCodeGenDebugOptions - Set codegen debugging options to aid in debugging
616 /// LTO problems.
617 void LTOCodeGenerator::setCodeGenDebugOptions(StringRef Options) {
618   for (std::pair<StringRef, StringRef> o = getToken(Options); !o.first.empty();
619        o = getToken(o.second))
620     CodegenOptions.push_back(o.first);
621 }
622 
623 void LTOCodeGenerator::parseCodeGenDebugOptions() {
624   // if options were requested, set them
625   if (!CodegenOptions.empty()) {
626     // ParseCommandLineOptions() expects argv[0] to be program name.
627     std::vector<const char *> CodegenArgv(1, "libLLVMLTO");
628     for (std::string &Arg : CodegenOptions)
629       CodegenArgv.push_back(Arg.c_str());
630     cl::ParseCommandLineOptions(CodegenArgv.size(), CodegenArgv.data());
631   }
632 }
633 
634 
635 void LTOCodeGenerator::DiagnosticHandler(const DiagnosticInfo &DI) {
636   // Map the LLVM internal diagnostic severity to the LTO diagnostic severity.
637   lto_codegen_diagnostic_severity_t Severity;
638   switch (DI.getSeverity()) {
639   case DS_Error:
640     Severity = LTO_DS_ERROR;
641     break;
642   case DS_Warning:
643     Severity = LTO_DS_WARNING;
644     break;
645   case DS_Remark:
646     Severity = LTO_DS_REMARK;
647     break;
648   case DS_Note:
649     Severity = LTO_DS_NOTE;
650     break;
651   }
652   // Create the string that will be reported to the external diagnostic handler.
653   std::string MsgStorage;
654   raw_string_ostream Stream(MsgStorage);
655   DiagnosticPrinterRawOStream DP(Stream);
656   DI.print(DP);
657   Stream.flush();
658 
659   // If this method has been called it means someone has set up an external
660   // diagnostic handler. Assert on that.
661   assert(DiagHandler && "Invalid diagnostic handler");
662   (*DiagHandler)(Severity, MsgStorage.c_str(), DiagContext);
663 }
664 
665 namespace {
666 struct LTODiagnosticHandler : public DiagnosticHandler {
667   LTOCodeGenerator *CodeGenerator;
668   LTODiagnosticHandler(LTOCodeGenerator *CodeGenPtr)
669       : CodeGenerator(CodeGenPtr) {}
670   bool handleDiagnostics(const DiagnosticInfo &DI) override {
671     CodeGenerator->DiagnosticHandler(DI);
672     return true;
673   }
674 };
675 }
676 
677 void
678 LTOCodeGenerator::setDiagnosticHandler(lto_diagnostic_handler_t DiagHandler,
679                                        void *Ctxt) {
680   this->DiagHandler = DiagHandler;
681   this->DiagContext = Ctxt;
682   if (!DiagHandler)
683     return Context.setDiagnosticHandler(nullptr);
684   // Register the LTOCodeGenerator stub in the LLVMContext to forward the
685   // diagnostic to the external DiagHandler.
686   Context.setDiagnosticHandler(llvm::make_unique<LTODiagnosticHandler>(this),
687                                true);
688 }
689 
690 namespace {
691 class LTODiagnosticInfo : public DiagnosticInfo {
692   const Twine &Msg;
693 public:
694   LTODiagnosticInfo(const Twine &DiagMsg, DiagnosticSeverity Severity=DS_Error)
695       : DiagnosticInfo(DK_Linker, Severity), Msg(DiagMsg) {}
696   void print(DiagnosticPrinter &DP) const override { DP << Msg; }
697 };
698 }
699 
700 void LTOCodeGenerator::emitError(const std::string &ErrMsg) {
701   if (DiagHandler)
702     (*DiagHandler)(LTO_DS_ERROR, ErrMsg.c_str(), DiagContext);
703   else
704     Context.diagnose(LTODiagnosticInfo(ErrMsg));
705 }
706 
707 void LTOCodeGenerator::emitWarning(const std::string &ErrMsg) {
708   if (DiagHandler)
709     (*DiagHandler)(LTO_DS_WARNING, ErrMsg.c_str(), DiagContext);
710   else
711     Context.diagnose(LTODiagnosticInfo(ErrMsg, DS_Warning));
712 }
713