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