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   return true;
378 }
379 
380 std::unique_ptr<TargetMachine> LTOCodeGenerator::createTargetMachine() {
381   return std::unique_ptr<TargetMachine>(MArch->createTargetMachine(
382       TripleStr, MCpu, FeatureStr, Options, RelocModel, None, CGOptLevel));
383 }
384 
385 // If a linkonce global is present in the MustPreserveSymbols, we need to make
386 // sure we honor this. To force the compiler to not drop it, we add it to the
387 // "llvm.compiler.used" global.
388 void LTOCodeGenerator::preserveDiscardableGVs(
389     Module &TheModule,
390     llvm::function_ref<bool(const GlobalValue &)> mustPreserveGV) {
391   std::vector<GlobalValue *> Used;
392   auto mayPreserveGlobal = [&](GlobalValue &GV) {
393     if (!GV.isDiscardableIfUnused() || GV.isDeclaration() ||
394         !mustPreserveGV(GV))
395       return;
396     if (GV.hasAvailableExternallyLinkage())
397       return emitWarning(
398           (Twine("Linker asked to preserve available_externally global: '") +
399            GV.getName() + "'").str());
400     if (GV.hasInternalLinkage())
401       return emitWarning((Twine("Linker asked to preserve internal global: '") +
402                    GV.getName() + "'").str());
403     Used.push_back(&GV);
404   };
405   for (auto &GV : TheModule)
406     mayPreserveGlobal(GV);
407   for (auto &GV : TheModule.globals())
408     mayPreserveGlobal(GV);
409   for (auto &GV : TheModule.aliases())
410     mayPreserveGlobal(GV);
411 
412   if (Used.empty())
413     return;
414 
415   appendToCompilerUsed(TheModule, Used);
416 }
417 
418 void LTOCodeGenerator::applyScopeRestrictions() {
419   if (ScopeRestrictionsDone)
420     return;
421 
422   // Declare a callback for the internalize pass that will ask for every
423   // candidate GlobalValue if it can be internalized or not.
424   Mangler Mang;
425   SmallString<64> MangledName;
426   auto mustPreserveGV = [&](const GlobalValue &GV) -> bool {
427     // Unnamed globals can't be mangled, but they can't be preserved either.
428     if (!GV.hasName())
429       return false;
430 
431     // Need to mangle the GV as the "MustPreserveSymbols" StringSet is filled
432     // with the linker supplied name, which on Darwin includes a leading
433     // underscore.
434     MangledName.clear();
435     MangledName.reserve(GV.getName().size() + 1);
436     Mang.getNameWithPrefix(MangledName, &GV, /*CannotUsePrivateLabel=*/false);
437     return MustPreserveSymbols.count(MangledName);
438   };
439 
440   // Preserve linkonce value on linker request
441   preserveDiscardableGVs(*MergedModule, mustPreserveGV);
442 
443   if (!ShouldInternalize)
444     return;
445 
446   if (ShouldRestoreGlobalsLinkage) {
447     // Record the linkage type of non-local symbols so they can be restored
448     // prior
449     // to module splitting.
450     auto RecordLinkage = [&](const GlobalValue &GV) {
451       if (!GV.hasAvailableExternallyLinkage() && !GV.hasLocalLinkage() &&
452           GV.hasName())
453         ExternalSymbols.insert(std::make_pair(GV.getName(), GV.getLinkage()));
454     };
455     for (auto &GV : *MergedModule)
456       RecordLinkage(GV);
457     for (auto &GV : MergedModule->globals())
458       RecordLinkage(GV);
459     for (auto &GV : MergedModule->aliases())
460       RecordLinkage(GV);
461   }
462 
463   // Update the llvm.compiler_used globals to force preserving libcalls and
464   // symbols referenced from asm
465   updateCompilerUsed(*MergedModule, *TargetMach, AsmUndefinedRefs);
466 
467   internalizeModule(*MergedModule, mustPreserveGV);
468 
469   ScopeRestrictionsDone = true;
470 }
471 
472 /// Restore original linkage for symbols that may have been internalized
473 void LTOCodeGenerator::restoreLinkageForExternals() {
474   if (!ShouldInternalize || !ShouldRestoreGlobalsLinkage)
475     return;
476 
477   assert(ScopeRestrictionsDone &&
478          "Cannot externalize without internalization!");
479 
480   if (ExternalSymbols.empty())
481     return;
482 
483   auto externalize = [this](GlobalValue &GV) {
484     if (!GV.hasLocalLinkage() || !GV.hasName())
485       return;
486 
487     auto I = ExternalSymbols.find(GV.getName());
488     if (I == ExternalSymbols.end())
489       return;
490 
491     GV.setLinkage(I->second);
492   };
493 
494   llvm::for_each(MergedModule->functions(), externalize);
495   llvm::for_each(MergedModule->globals(), externalize);
496   llvm::for_each(MergedModule->aliases(), externalize);
497 }
498 
499 void LTOCodeGenerator::verifyMergedModuleOnce() {
500   // Only run on the first call.
501   if (HasVerifiedInput)
502     return;
503   HasVerifiedInput = true;
504 
505   bool BrokenDebugInfo = false;
506   if (verifyModule(*MergedModule, &dbgs(), &BrokenDebugInfo))
507     report_fatal_error("Broken module found, compilation aborted!");
508   if (BrokenDebugInfo) {
509     emitWarning("Invalid debug info found, debug info will be stripped");
510     StripDebugInfo(*MergedModule);
511   }
512 }
513 
514 void LTOCodeGenerator::finishOptimizationRemarks() {
515   if (DiagnosticOutputFile) {
516     DiagnosticOutputFile->keep();
517     // FIXME: LTOCodeGenerator dtor is not invoked on Darwin
518     DiagnosticOutputFile->os().flush();
519   }
520 }
521 
522 /// Optimize merged modules using various IPO passes
523 bool LTOCodeGenerator::optimize(bool DisableVerify, bool DisableInline,
524                                 bool DisableGVNLoadPRE,
525                                 bool DisableVectorization) {
526   if (!this->determineTarget())
527     return false;
528 
529   auto DiagFileOrErr =
530       lto::setupLLVMOptimizationRemarks(Context, RemarksFilename, RemarksPasses,
531                                         RemarksFormat, RemarksWithHotness);
532   if (!DiagFileOrErr) {
533     errs() << "Error: " << toString(DiagFileOrErr.takeError()) << "\n";
534     report_fatal_error("Can't get an output file for the remarks");
535   }
536   DiagnosticOutputFile = std::move(*DiagFileOrErr);
537 
538   // Setup output file to emit statistics.
539   auto StatsFileOrErr = lto::setupStatsFile(LTOStatsFile);
540   if (!StatsFileOrErr) {
541     errs() << "Error: " << toString(StatsFileOrErr.takeError()) << "\n";
542     report_fatal_error("Can't get an output file for the statistics");
543   }
544   StatsFile = std::move(StatsFileOrErr.get());
545 
546   // Currently there is no support for enabling whole program visibility via a
547   // linker option in the old LTO API, but this call allows it to be specified
548   // via the internal option. Must be done before WPD invoked via the optimizer
549   // pipeline run below.
550   updateVCallVisibilityInModule(*MergedModule,
551                                 /* WholeProgramVisibilityEnabledInLTO */ false);
552 
553   // We always run the verifier once on the merged module, the `DisableVerify`
554   // parameter only applies to subsequent verify.
555   verifyMergedModuleOnce();
556 
557   // Mark which symbols can not be internalized
558   this->applyScopeRestrictions();
559 
560   // Write LTOPostLink flag for passes that require all the modules.
561   MergedModule->addModuleFlag(Module::Error, "LTOPostLink", 1);
562 
563   // Instantiate the pass manager to organize the passes.
564   legacy::PassManager passes;
565 
566   // Add an appropriate DataLayout instance for this module...
567   MergedModule->setDataLayout(TargetMach->createDataLayout());
568 
569   passes.add(
570       createTargetTransformInfoWrapperPass(TargetMach->getTargetIRAnalysis()));
571 
572   Triple TargetTriple(TargetMach->getTargetTriple());
573   PassManagerBuilder PMB;
574   PMB.DisableGVNLoadPRE = DisableGVNLoadPRE;
575   PMB.LoopVectorize = !DisableVectorization;
576   PMB.SLPVectorize = !DisableVectorization;
577   if (!DisableInline)
578     PMB.Inliner = createFunctionInliningPass();
579   PMB.LibraryInfo = new TargetLibraryInfoImpl(TargetTriple);
580   if (Freestanding)
581     PMB.LibraryInfo->disableAllFunctions();
582   PMB.OptLevel = OptLevel;
583   PMB.VerifyInput = !DisableVerify;
584   PMB.VerifyOutput = !DisableVerify;
585 
586   PMB.populateLTOPassManager(passes);
587 
588   // Run our queue of passes all at once now, efficiently.
589   passes.run(*MergedModule);
590 
591   return true;
592 }
593 
594 bool LTOCodeGenerator::compileOptimized(ArrayRef<raw_pwrite_stream *> Out) {
595   if (!this->determineTarget())
596     return false;
597 
598   // We always run the verifier once on the merged module.  If it has already
599   // been called in optimize(), this call will return early.
600   verifyMergedModuleOnce();
601 
602   legacy::PassManager preCodeGenPasses;
603 
604   // If the bitcode files contain ARC code and were compiled with optimization,
605   // the ObjCARCContractPass must be run, so do it unconditionally here.
606   preCodeGenPasses.add(createObjCARCContractPass());
607   preCodeGenPasses.run(*MergedModule);
608 
609   // Re-externalize globals that may have been internalized to increase scope
610   // for splitting
611   restoreLinkageForExternals();
612 
613   // Do code generation. We need to preserve the module in case the client calls
614   // writeMergedModules() after compilation, but we only need to allow this at
615   // parallelism level 1. This is achieved by having splitCodeGen return the
616   // original module at parallelism level 1 which we then assign back to
617   // MergedModule.
618   MergedModule = splitCodeGen(std::move(MergedModule), Out, {},
619                               [&]() { return createTargetMachine(); }, FileType,
620                               ShouldRestoreGlobalsLinkage);
621 
622   // If statistics were requested, save them to the specified file or
623   // print them out after codegen.
624   if (StatsFile)
625     PrintStatisticsJSON(StatsFile->os());
626   else if (AreStatisticsEnabled())
627     PrintStatistics();
628 
629   reportAndResetTimings();
630 
631   finishOptimizationRemarks();
632 
633   return true;
634 }
635 
636 void LTOCodeGenerator::setCodeGenDebugOptions(ArrayRef<StringRef> Options) {
637   for (StringRef Option : Options)
638     CodegenOptions.push_back(Option.str());
639 }
640 
641 void LTOCodeGenerator::parseCodeGenDebugOptions() {
642   // if options were requested, set them
643   if (!CodegenOptions.empty()) {
644     // ParseCommandLineOptions() expects argv[0] to be program name.
645     std::vector<const char *> CodegenArgv(1, "libLLVMLTO");
646     for (std::string &Arg : CodegenOptions)
647       CodegenArgv.push_back(Arg.c_str());
648     cl::ParseCommandLineOptions(CodegenArgv.size(), CodegenArgv.data());
649   }
650 }
651 
652 
653 void LTOCodeGenerator::DiagnosticHandler(const DiagnosticInfo &DI) {
654   // Map the LLVM internal diagnostic severity to the LTO diagnostic severity.
655   lto_codegen_diagnostic_severity_t Severity;
656   switch (DI.getSeverity()) {
657   case DS_Error:
658     Severity = LTO_DS_ERROR;
659     break;
660   case DS_Warning:
661     Severity = LTO_DS_WARNING;
662     break;
663   case DS_Remark:
664     Severity = LTO_DS_REMARK;
665     break;
666   case DS_Note:
667     Severity = LTO_DS_NOTE;
668     break;
669   }
670   // Create the string that will be reported to the external diagnostic handler.
671   std::string MsgStorage;
672   raw_string_ostream Stream(MsgStorage);
673   DiagnosticPrinterRawOStream DP(Stream);
674   DI.print(DP);
675   Stream.flush();
676 
677   // If this method has been called it means someone has set up an external
678   // diagnostic handler. Assert on that.
679   assert(DiagHandler && "Invalid diagnostic handler");
680   (*DiagHandler)(Severity, MsgStorage.c_str(), DiagContext);
681 }
682 
683 namespace {
684 struct LTODiagnosticHandler : public DiagnosticHandler {
685   LTOCodeGenerator *CodeGenerator;
686   LTODiagnosticHandler(LTOCodeGenerator *CodeGenPtr)
687       : CodeGenerator(CodeGenPtr) {}
688   bool handleDiagnostics(const DiagnosticInfo &DI) override {
689     CodeGenerator->DiagnosticHandler(DI);
690     return true;
691   }
692 };
693 }
694 
695 void
696 LTOCodeGenerator::setDiagnosticHandler(lto_diagnostic_handler_t DiagHandler,
697                                        void *Ctxt) {
698   this->DiagHandler = DiagHandler;
699   this->DiagContext = Ctxt;
700   if (!DiagHandler)
701     return Context.setDiagnosticHandler(nullptr);
702   // Register the LTOCodeGenerator stub in the LLVMContext to forward the
703   // diagnostic to the external DiagHandler.
704   Context.setDiagnosticHandler(std::make_unique<LTODiagnosticHandler>(this),
705                                true);
706 }
707 
708 namespace {
709 class LTODiagnosticInfo : public DiagnosticInfo {
710   const Twine &Msg;
711 public:
712   LTODiagnosticInfo(const Twine &DiagMsg, DiagnosticSeverity Severity=DS_Error)
713       : DiagnosticInfo(DK_Linker, Severity), Msg(DiagMsg) {}
714   void print(DiagnosticPrinter &DP) const override { DP << Msg; }
715 };
716 }
717 
718 void LTOCodeGenerator::emitError(const std::string &ErrMsg) {
719   if (DiagHandler)
720     (*DiagHandler)(LTO_DS_ERROR, ErrMsg.c_str(), DiagContext);
721   else
722     Context.diagnose(LTODiagnosticInfo(ErrMsg));
723 }
724 
725 void LTOCodeGenerator::emitWarning(const std::string &ErrMsg) {
726   if (DiagHandler)
727     (*DiagHandler)(LTO_DS_WARNING, ErrMsg.c_str(), DiagContext);
728   else
729     Context.diagnose(LTODiagnosticInfo(ErrMsg, DS_Warning));
730 }
731