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