14ccf0f1bSPeter Collingbourne //===-LTOCodeGenerator.cpp - LLVM Link Time Optimizer ---------------------===//
24ccf0f1bSPeter Collingbourne //
32946cd70SChandler Carruth // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
42946cd70SChandler Carruth // See https://llvm.org/LICENSE.txt for license information.
52946cd70SChandler Carruth // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
64ccf0f1bSPeter Collingbourne //
74ccf0f1bSPeter Collingbourne //===----------------------------------------------------------------------===//
84ccf0f1bSPeter Collingbourne //
94ccf0f1bSPeter Collingbourne // This file implements the Link Time Optimization library. This library is
104ccf0f1bSPeter Collingbourne // intended to be used by linker to optimize code at link time.
114ccf0f1bSPeter Collingbourne //
124ccf0f1bSPeter Collingbourne //===----------------------------------------------------------------------===//
134ccf0f1bSPeter Collingbourne 
145c73220fSPeter Collingbourne #include "llvm/LTO/legacy/LTOCodeGenerator.h"
15f59f2bb1SMehdi Amini 
16106fedabSAdam Nemet #include "llvm/ADT/Statistic.h"
174ccf0f1bSPeter Collingbourne #include "llvm/ADT/StringExtras.h"
184ccf0f1bSPeter Collingbourne #include "llvm/Analysis/Passes.h"
1962d4215bSChandler Carruth #include "llvm/Analysis/TargetLibraryInfo.h"
2093dcdc47SChandler Carruth #include "llvm/Analysis/TargetTransformInfo.h"
21ad17679aSTeresa Johnson #include "llvm/Bitcode/BitcodeWriter.h"
22c269ed51SPeter Collingbourne #include "llvm/CodeGen/ParallelCG.h"
23b3bde2eaSDavid Blaikie #include "llvm/CodeGen/TargetSubtargetInfo.h"
244ccf0f1bSPeter Collingbourne #include "llvm/Config/config.h"
254ccf0f1bSPeter Collingbourne #include "llvm/IR/Constants.h"
264ccf0f1bSPeter Collingbourne #include "llvm/IR/DataLayout.h"
27fe7a3824SAdrian Prantl #include "llvm/IR/DebugInfo.h"
284ccf0f1bSPeter Collingbourne #include "llvm/IR/DerivedTypes.h"
295fa1f6f5SQuentin Colombet #include "llvm/IR/DiagnosticInfo.h"
305fa1f6f5SQuentin Colombet #include "llvm/IR/DiagnosticPrinter.h"
314ccf0f1bSPeter Collingbourne #include "llvm/IR/LLVMContext.h"
327531a503SFrancis Visoiu Mistrih #include "llvm/IR/LLVMRemarkStreamer.h"
3330d69c2eSChandler Carruth #include "llvm/IR/LegacyPassManager.h"
34894843cbSRafael Espindola #include "llvm/IR/Mangler.h"
354ccf0f1bSPeter Collingbourne #include "llvm/IR/Module.h"
36a43fd952SFedor Sergeev #include "llvm/IR/PassTimingInfo.h"
375ad5f15cSChandler Carruth #include "llvm/IR/Verifier.h"
384ccf0f1bSPeter Collingbourne #include "llvm/InitializePasses.h"
39690ed9deSDavide Italiano #include "llvm/LTO/LTO.h"
40c70737baSFlorian Hahn #include "llvm/LTO/LTOBackend.h"
415c73220fSPeter Collingbourne #include "llvm/LTO/legacy/LTOModule.h"
425c73220fSPeter Collingbourne #include "llvm/LTO/legacy/UpdateCompilerUsed.h"
436cc07df4SChandler Carruth #include "llvm/Linker/Linker.h"
444ccf0f1bSPeter Collingbourne #include "llvm/MC/MCAsmInfo.h"
454ccf0f1bSPeter Collingbourne #include "llvm/MC/MCContext.h"
464ccf0f1bSPeter Collingbourne #include "llvm/MC/SubtargetFeature.h"
4789b57061SReid Kleckner #include "llvm/MC/TargetRegistry.h"
483acda917SWei Wang #include "llvm/Remarks/HotnessThresholdParser.h"
494ccf0f1bSPeter Collingbourne #include "llvm/Support/CommandLine.h"
504ccf0f1bSPeter Collingbourne #include "llvm/Support/FileSystem.h"
514ccf0f1bSPeter Collingbourne #include "llvm/Support/Host.h"
524ccf0f1bSPeter Collingbourne #include "llvm/Support/MemoryBuffer.h"
534ccf0f1bSPeter Collingbourne #include "llvm/Support/Signals.h"
544ccf0f1bSPeter Collingbourne #include "llvm/Support/TargetSelect.h"
554ccf0f1bSPeter Collingbourne #include "llvm/Support/ToolOutputFile.h"
56e9bd022cSAdam Nemet #include "llvm/Support/YAMLTraits.h"
57442f7848SChandler Carruth #include "llvm/Support/raw_ostream.h"
580b385c77SRafael Espindola #include "llvm/Target/TargetOptions.h"
594ccf0f1bSPeter Collingbourne #include "llvm/Transforms/IPO.h"
60ce23e970SMehdi Amini #include "llvm/Transforms/IPO/Internalize.h"
614ccf0f1bSPeter Collingbourne #include "llvm/Transforms/IPO/PassManagerBuilder.h"
622f63d549STeresa Johnson #include "llvm/Transforms/IPO/WholeProgramDevirt.h"
634ccf0f1bSPeter Collingbourne #include "llvm/Transforms/ObjCARC.h"
64ea6d49d3SEvgeniy Stepanov #include "llvm/Transforms/Utils/ModuleUtils.h"
65a6e9c3e4SRafael Espindola #include <system_error>
664ccf0f1bSPeter Collingbourne using namespace llvm;
674ccf0f1bSPeter Collingbourne 
getVersionString()684ccf0f1bSPeter Collingbourne const char* LTOCodeGenerator::getVersionString() {
694ccf0f1bSPeter Collingbourne   return PACKAGE_NAME " version " PACKAGE_VERSION;
704ccf0f1bSPeter Collingbourne }
714ccf0f1bSPeter Collingbourne 
7209b4a8daSMehdi Amini namespace llvm {
7309b4a8daSMehdi Amini cl::opt<bool> LTODiscardValueNames(
741592cb9aSMehdi Amini     "lto-discard-value-names",
751592cb9aSMehdi Amini     cl::desc("Strip names from Value during LTO (other than GlobalValue)."),
7609b4a8daSMehdi Amini #ifdef NDEBUG
7709b4a8daSMehdi Amini     cl::init(true),
7809b4a8daSMehdi Amini #else
7909b4a8daSMehdi Amini     cl::init(false),
8009b4a8daSMehdi Amini #endif
8109b4a8daSMehdi Amini     cl::Hidden);
82fe7a3824SAdrian Prantl 
837a21113cSFrancis Visoiu Mistrih cl::opt<bool> RemarksWithHotness(
847a21113cSFrancis Visoiu Mistrih     "lto-pass-remarks-with-hotness",
857a21113cSFrancis Visoiu Mistrih     cl::desc("With PGO, include profile count in optimization remarks"),
867a21113cSFrancis Visoiu Mistrih     cl::Hidden);
877a21113cSFrancis Visoiu Mistrih 
883acda917SWei Wang cl::opt<Optional<uint64_t>, false, remarks::HotnessThresholdParser>
893acda917SWei Wang     RemarksHotnessThreshold(
903acda917SWei Wang         "lto-pass-remarks-hotness-threshold",
913acda917SWei Wang         cl::desc("Minimum profile count required for an "
923acda917SWei Wang                  "optimization remark to be output."
933acda917SWei Wang                  " Use 'auto' to apply the threshold from profile summary."),
943acda917SWei Wang         cl::value_desc("uint or 'auto'"), cl::init(0), cl::Hidden);
953acda917SWei Wang 
9619f176b9SMehdi Amini cl::opt<std::string>
977a21113cSFrancis Visoiu Mistrih     RemarksFilename("lto-pass-remarks-output",
98e9bd022cSAdam Nemet                     cl::desc("Output filename for pass remarks"),
99e9bd022cSAdam Nemet                     cl::value_desc("filename"));
1004c207a6aSAdam Nemet 
101dd42236cSFrancis Visoiu Mistrih cl::opt<std::string>
1027a21113cSFrancis Visoiu Mistrih     RemarksPasses("lto-pass-remarks-filter",
1037a21113cSFrancis Visoiu Mistrih                   cl::desc("Only record optimization remarks from passes whose "
1047a21113cSFrancis Visoiu Mistrih                            "names match the given regular expression"),
105dd42236cSFrancis Visoiu Mistrih                   cl::value_desc("regex"));
106dd42236cSFrancis Visoiu Mistrih 
10734667519SFrancis Visoiu Mistrih cl::opt<std::string> RemarksFormat(
10834667519SFrancis Visoiu Mistrih     "lto-pass-remarks-format",
10934667519SFrancis Visoiu Mistrih     cl::desc("The format used for serializing remarks (default: YAML)"),
11034667519SFrancis Visoiu Mistrih     cl::value_desc("format"), cl::init("yaml"));
11134667519SFrancis Visoiu Mistrih 
112b340497fSFlorian Hahn cl::opt<std::string> LTOStatsFile(
113b340497fSFlorian Hahn     "lto-stats-file",
114b340497fSFlorian Hahn     cl::desc("Save statistics to the specified file"),
115b340497fSFlorian Hahn     cl::Hidden);
11619f176b9SMehdi Amini }
117e9bd022cSAdam Nemet 
LTOCodeGenerator(LLVMContext & Context)1187b8a24e5SRafael Espindola LTOCodeGenerator::LTOCodeGenerator(LLVMContext &Context)
119f49a38fcSRafael Espindola     : Context(Context), MergedModule(new Module("ld-temp.o", Context)),
120bef54363STeresa Johnson       TheLinker(new Linker(*MergedModule)) {
12109b4a8daSMehdi Amini   Context.setDiscardValueNames(LTODiscardValueNames);
122ed8fdb2aSDuncan P. N. Exon Smith   Context.enableDebugTypeODRUniquing();
123c70737baSFlorian Hahn 
124c70737baSFlorian Hahn   Config.CodeModel = None;
125c70737baSFlorian Hahn   Config.StatsFile = LTOStatsFile;
126c70737baSFlorian Hahn   Config.PreCodeGenPassesHook = [](legacy::PassManager &PM) {
127c70737baSFlorian Hahn     PM.add(createObjCARCContractPass());
128c70737baSFlorian Hahn   };
129de5e32b5SDuncan P. N. Exon Smith }
130de5e32b5SDuncan P. N. Exon Smith 
1313a3cb929SKazu Hirata LTOCodeGenerator::~LTOCodeGenerator() = default;
1324ccf0f1bSPeter Collingbourne 
setAsmUndefinedRefs(LTOModule * Mod)133fc4430eaSDavide Italiano void LTOCodeGenerator::setAsmUndefinedRefs(LTOModule *Mod) {
134ccdd5bb2SKazu Hirata   for (const StringRef &Undef : Mod->getAsmUndefinedRefs())
135ccdd5bb2SKazu Hirata     AsmUndefinedRefs.insert(Undef);
136fc4430eaSDavide Italiano }
137fc4430eaSDavide Italiano 
addModule(LTOModule * Mod)138f4967754SDuncan P. N. Exon Smith bool LTOCodeGenerator::addModule(LTOModule *Mod) {
139f4967754SDuncan P. N. Exon Smith   assert(&Mod->getModule().getContext() == &Context &&
14094198639SDuncan P. N. Exon Smith          "Expected module in same context");
14194198639SDuncan P. N. Exon Smith 
142bef54363STeresa Johnson   bool ret = TheLinker->linkInModule(Mod->takeModule());
143fc4430eaSDavide Italiano   setAsmUndefinedRefs(Mod);
1444ccf0f1bSPeter Collingbourne 
145b011ad73SDuncan P. N. Exon Smith   // We've just changed the input, so let's make sure we verify it.
146b011ad73SDuncan P. N. Exon Smith   HasVerifiedInput = false;
147b011ad73SDuncan P. N. Exon Smith 
1484ccf0f1bSPeter Collingbourne   return !ret;
1494ccf0f1bSPeter Collingbourne }
1504ccf0f1bSPeter Collingbourne 
setModule(std::unique_ptr<LTOModule> Mod)1519c8909dbSPeter Collingbourne void LTOCodeGenerator::setModule(std::unique_ptr<LTOModule> Mod) {
1526487ce95SManman Ren   assert(&Mod->getModule().getContext() == &Context &&
1536487ce95SManman Ren          "Expected module in same context");
1546487ce95SManman Ren 
1556487ce95SManman Ren   AsmUndefinedRefs.clear();
1566487ce95SManman Ren 
1579c8909dbSPeter Collingbourne   MergedModule = Mod->takeModule();
1580eaee545SJonas Devlieghere   TheLinker = std::make_unique<Linker>(*MergedModule);
159fc4430eaSDavide Italiano   setAsmUndefinedRefs(&*Mod);
160b011ad73SDuncan P. N. Exon Smith 
161b011ad73SDuncan P. N. Exon Smith   // We've just changed the input, so let's make sure we verify it.
162b011ad73SDuncan P. N. Exon Smith   HasVerifiedInput = false;
1636487ce95SManman Ren }
1646487ce95SManman Ren 
setTargetOptions(const TargetOptions & Options)165c321e534SBenjamin Kramer void LTOCodeGenerator::setTargetOptions(const TargetOptions &Options) {
166c70737baSFlorian Hahn   Config.Options = Options;
1670b385c77SRafael Espindola }
1680b385c77SRafael Espindola 
setDebugInfo(lto_debug_model Debug)169f4967754SDuncan P. N. Exon Smith void LTOCodeGenerator::setDebugInfo(lto_debug_model Debug) {
170f4967754SDuncan P. N. Exon Smith   switch (Debug) {
1714ccf0f1bSPeter Collingbourne   case LTO_DEBUG_MODEL_NONE:
1724ccf0f1bSPeter Collingbourne     EmitDwarfDebugInfo = false;
1734ccf0f1bSPeter Collingbourne     return;
1744ccf0f1bSPeter Collingbourne 
1754ccf0f1bSPeter Collingbourne   case LTO_DEBUG_MODEL_DWARF:
1764ccf0f1bSPeter Collingbourne     EmitDwarfDebugInfo = true;
1774ccf0f1bSPeter Collingbourne     return;
1784ccf0f1bSPeter Collingbourne   }
1794ccf0f1bSPeter Collingbourne   llvm_unreachable("Unknown debug format!");
1804ccf0f1bSPeter Collingbourne }
1814ccf0f1bSPeter Collingbourne 
setOptLevel(unsigned Level)182f4967754SDuncan P. N. Exon Smith void LTOCodeGenerator::setOptLevel(unsigned Level) {
183c70737baSFlorian Hahn   Config.OptLevel = Level;
184c70737baSFlorian Hahn   Config.PTO.LoopVectorization = Config.OptLevel > 1;
185c70737baSFlorian Hahn   Config.PTO.SLPVectorization = Config.OptLevel > 1;
186c70737baSFlorian Hahn   switch (Config.OptLevel) {
187c7b675f4SPeter Collingbourne   case 0:
188c70737baSFlorian Hahn     Config.CGOptLevel = CodeGenOpt::None;
189f8014f82SDavide Italiano     return;
190c7b675f4SPeter Collingbourne   case 1:
191c70737baSFlorian Hahn     Config.CGOptLevel = CodeGenOpt::Less;
192f8014f82SDavide Italiano     return;
193c7b675f4SPeter Collingbourne   case 2:
194c70737baSFlorian Hahn     Config.CGOptLevel = CodeGenOpt::Default;
195f8014f82SDavide Italiano     return;
196c7b675f4SPeter Collingbourne   case 3:
197c70737baSFlorian Hahn     Config.CGOptLevel = CodeGenOpt::Aggressive;
198f8014f82SDavide Italiano     return;
199c7b675f4SPeter Collingbourne   }
200f8014f82SDavide Italiano   llvm_unreachable("Unknown optimization level!");
201c7b675f4SPeter Collingbourne }
202c7b675f4SPeter Collingbourne 
writeMergedModules(StringRef Path)2034cc259a4SMehdi Amini bool LTOCodeGenerator::writeMergedModules(StringRef Path) {
2048e348cc7SYunzhong Gao   if (!determineTarget())
2054ccf0f1bSPeter Collingbourne     return false;
2064ccf0f1bSPeter Collingbourne 
207b011ad73SDuncan P. N. Exon Smith   // We always run the verifier once on the merged module.
208b011ad73SDuncan P. N. Exon Smith   verifyMergedModuleOnce();
209b011ad73SDuncan P. N. Exon Smith 
2104ccf0f1bSPeter Collingbourne   // mark which symbols can not be internalized
2114ccf0f1bSPeter Collingbourne   applyScopeRestrictions();
2124ccf0f1bSPeter Collingbourne 
2134ccf0f1bSPeter Collingbourne   // create output file
2143fd1e993SRafael Espindola   std::error_code EC;
215d9b948b6SFangrui Song   ToolOutputFile Out(Path, EC, sys::fs::OF_None);
2163fd1e993SRafael Espindola   if (EC) {
2178e348cc7SYunzhong Gao     std::string ErrMsg = "could not open bitcode file for writing: ";
2189ce2d03eSBob Haarman     ErrMsg += Path.str() + ": " + EC.message();
2198e348cc7SYunzhong Gao     emitError(ErrMsg);
2204ccf0f1bSPeter Collingbourne     return false;
2214ccf0f1bSPeter Collingbourne   }
2224ccf0f1bSPeter Collingbourne 
2234ccf0f1bSPeter Collingbourne   // write bitcode to it
2246a86e25dSRafael Espindola   WriteBitcodeToFile(*MergedModule, Out.os(), ShouldEmbedUselists);
2254ccf0f1bSPeter Collingbourne   Out.os().close();
2264ccf0f1bSPeter Collingbourne 
2274ccf0f1bSPeter Collingbourne   if (Out.os().has_error()) {
2288e348cc7SYunzhong Gao     std::string ErrMsg = "could not write bitcode file: ";
2299ce2d03eSBob Haarman     ErrMsg += Path.str() + ": " + Out.os().error().message();
2308e348cc7SYunzhong Gao     emitError(ErrMsg);
2314ccf0f1bSPeter Collingbourne     Out.os().clear_error();
2324ccf0f1bSPeter Collingbourne     return false;
2334ccf0f1bSPeter Collingbourne   }
2344ccf0f1bSPeter Collingbourne 
2354ccf0f1bSPeter Collingbourne   Out.keep();
2364ccf0f1bSPeter Collingbourne   return true;
2374ccf0f1bSPeter Collingbourne }
2384ccf0f1bSPeter Collingbourne 
compileOptimizedToFile(const char ** Name)2398e348cc7SYunzhong Gao bool LTOCodeGenerator::compileOptimizedToFile(const char **Name) {
2404d450906STobias Edler von Koch   // make unique temp output file to put generated code
2414ccf0f1bSPeter Collingbourne   SmallString<128> Filename;
242c70737baSFlorian Hahn 
243d788c44fSNoah Shutty   auto AddStream = [&](size_t Task) -> std::unique_ptr<CachedFileStream> {
244c70737baSFlorian Hahn     StringRef Extension(Config.CGFileType == CGFT_AssemblyFile ? "s" : "o");
245c70737baSFlorian Hahn 
2464ccf0f1bSPeter Collingbourne     int FD;
247db4ed0bdSRafael Espindola     std::error_code EC =
2484d450906STobias Edler von Koch         sys::fs::createTemporaryFile("lto-llvm", Extension, FD, Filename);
249c70737baSFlorian Hahn     if (EC)
2508e348cc7SYunzhong Gao       emitError(EC.message());
2514ccf0f1bSPeter Collingbourne 
252d788c44fSNoah Shutty     return std::make_unique<CachedFileStream>(
253c70737baSFlorian Hahn         std::make_unique<llvm::raw_fd_ostream>(FD, true));
254c70737baSFlorian Hahn   };
2554ccf0f1bSPeter Collingbourne 
256c70737baSFlorian Hahn   bool genResult = compileOptimized(AddStream, 1);
2574ccf0f1bSPeter Collingbourne 
2587db390ccSFlorian Hahn   if (!genResult) {
2597db390ccSFlorian Hahn     sys::fs::remove(Twine(Filename));
2607db390ccSFlorian Hahn     return false;
2617db390ccSFlorian Hahn   }
2626a59f056SFlorian Hahn 
263c70737baSFlorian Hahn   // If statistics were requested, save them to the specified file or
264c70737baSFlorian Hahn   // print them out after codegen.
265c70737baSFlorian Hahn   if (StatsFile)
266c70737baSFlorian Hahn     PrintStatisticsJSON(StatsFile->os());
267c70737baSFlorian Hahn   else if (AreStatisticsEnabled())
268c70737baSFlorian Hahn     PrintStatistics();
269c70737baSFlorian Hahn 
2704ccf0f1bSPeter Collingbourne   NativeObjectPath = Filename.c_str();
271f4967754SDuncan P. N. Exon Smith   *Name = NativeObjectPath.c_str();
2724ccf0f1bSPeter Collingbourne   return true;
2734ccf0f1bSPeter Collingbourne }
2744ccf0f1bSPeter Collingbourne 
2753cc69d90SPeter Collingbourne std::unique_ptr<MemoryBuffer>
compileOptimized()2768e348cc7SYunzhong Gao LTOCodeGenerator::compileOptimized() {
2774ccf0f1bSPeter Collingbourne   const char *name;
2788e348cc7SYunzhong Gao   if (!compileOptimizedToFile(&name))
2792617dcceSCraig Topper     return nullptr;
2804ccf0f1bSPeter Collingbourne 
2814ccf0f1bSPeter Collingbourne   // read .o file into memory buffer
282c83cd8feSAbhina Sreeskantharajan   ErrorOr<std::unique_ptr<MemoryBuffer>> BufferOrErr = MemoryBuffer::getFile(
283c83cd8feSAbhina Sreeskantharajan       name, /*IsText=*/false, /*RequiresNullTerminator=*/false);
284adf21f2aSRafael Espindola   if (std::error_code EC = BufferOrErr.getError()) {
2858e348cc7SYunzhong Gao     emitError(EC.message());
2864ccf0f1bSPeter Collingbourne     sys::fs::remove(NativeObjectPath);
2872617dcceSCraig Topper     return nullptr;
2884ccf0f1bSPeter Collingbourne   }
2894ccf0f1bSPeter Collingbourne 
2904ccf0f1bSPeter Collingbourne   // remove temp files
2914ccf0f1bSPeter Collingbourne   sys::fs::remove(NativeObjectPath);
2924ccf0f1bSPeter Collingbourne 
2933cc69d90SPeter Collingbourne   return std::move(*BufferOrErr);
2944ccf0f1bSPeter Collingbourne }
2954ccf0f1bSPeter Collingbourne 
compile_to_file(const char ** Name)296f959d819SFlorian Hahn bool LTOCodeGenerator::compile_to_file(const char **Name) {
297f959d819SFlorian Hahn   if (!optimize())
2988121e1dbSManman Ren     return false;
2998121e1dbSManman Ren 
3008e348cc7SYunzhong Gao   return compileOptimizedToFile(Name);
3018121e1dbSManman Ren }
3028121e1dbSManman Ren 
compile()303f959d819SFlorian Hahn std::unique_ptr<MemoryBuffer> LTOCodeGenerator::compile() {
304f959d819SFlorian Hahn   if (!optimize())
3058121e1dbSManman Ren     return nullptr;
3068121e1dbSManman Ren 
3078e348cc7SYunzhong Gao   return compileOptimized();
3088121e1dbSManman Ren }
3098121e1dbSManman Ren 
determineTarget()3108e348cc7SYunzhong Gao bool LTOCodeGenerator::determineTarget() {
3112617dcceSCraig Topper   if (TargetMach)
3124ccf0f1bSPeter Collingbourne     return true;
3134ccf0f1bSPeter Collingbourne 
3143c1c9875SRafael Espindola   TripleStr = MergedModule->getTargetTriple();
315c7b675f4SPeter Collingbourne   if (TripleStr.empty()) {
3164ccf0f1bSPeter Collingbourne     TripleStr = sys::getDefaultTargetTriple();
3179c8909dbSPeter Collingbourne     MergedModule->setTargetTriple(TripleStr);
318c7b675f4SPeter Collingbourne   }
3194ccf0f1bSPeter Collingbourne   llvm::Triple Triple(TripleStr);
3204ccf0f1bSPeter Collingbourne 
3214ccf0f1bSPeter Collingbourne   // create target machine from info for merged modules
3228e348cc7SYunzhong Gao   std::string ErrMsg;
3233c1c9875SRafael Espindola   MArch = TargetRegistry::lookupTarget(TripleStr, ErrMsg);
3243c1c9875SRafael Espindola   if (!MArch) {
3258e348cc7SYunzhong Gao     emitError(ErrMsg);
3264ccf0f1bSPeter Collingbourne     return false;
3278e348cc7SYunzhong Gao   }
3284ccf0f1bSPeter Collingbourne 
329fd1bc602STom Roeder   // Construct LTOModule, hand over ownership of module and target. Use MAttr as
330fd1bc602STom Roeder   // the default set of features.
331c70737baSFlorian Hahn   SubtargetFeatures Features(join(Config.MAttrs, ""));
3324ccf0f1bSPeter Collingbourne   Features.getDefaultSubtargetFeatures(Triple);
333c7b675f4SPeter Collingbourne   FeatureStr = Features.getString();
3344ccf0f1bSPeter Collingbourne   // Set a default CPU for Darwin triples.
335c70737baSFlorian Hahn   if (Config.CPU.empty() && Triple.isOSDarwin()) {
3364ccf0f1bSPeter Collingbourne     if (Triple.getArch() == llvm::Triple::x86_64)
337c70737baSFlorian Hahn       Config.CPU = "core2";
3384ccf0f1bSPeter Collingbourne     else if (Triple.getArch() == llvm::Triple::x86)
339c70737baSFlorian Hahn       Config.CPU = "yonah";
340f77c948dSAhmed Bougacha     else if (Triple.isArm64e())
341c70737baSFlorian Hahn       Config.CPU = "apple-a12";
342f1c28929STim Northover     else if (Triple.getArch() == llvm::Triple::aarch64 ||
343f1c28929STim Northover              Triple.getArch() == llvm::Triple::aarch64_32)
344c70737baSFlorian Hahn       Config.CPU = "cyclone";
3454ccf0f1bSPeter Collingbourne   }
3460b385c77SRafael Espindola 
3473c1c9875SRafael Espindola   TargetMach = createTargetMachine();
3481756d679SElla Ma   assert(TargetMach && "Unable to create target machine");
3491756d679SElla Ma 
3504ccf0f1bSPeter Collingbourne   return true;
3514ccf0f1bSPeter Collingbourne }
3524ccf0f1bSPeter Collingbourne 
createTargetMachine()3533c1c9875SRafael Espindola std::unique_ptr<TargetMachine> LTOCodeGenerator::createTargetMachine() {
3541756d679SElla Ma   assert(MArch && "MArch is not set!");
35579e238afSRafael Espindola   return std::unique_ptr<TargetMachine>(MArch->createTargetMachine(
356c70737baSFlorian Hahn       TripleStr, Config.CPU, FeatureStr, Config.Options, Config.RelocModel,
357c70737baSFlorian Hahn       None, Config.CGOptLevel));
3583c1c9875SRafael Espindola }
3593c1c9875SRafael Espindola 
360022b5bcbSMehdi Amini // If a linkonce global is present in the MustPreserveSymbols, we need to make
361022b5bcbSMehdi Amini // sure we honor this. To force the compiler to not drop it, we add it to the
362022b5bcbSMehdi Amini // "llvm.compiler.used" global.
preserveDiscardableGVs(Module & TheModule,llvm::function_ref<bool (const GlobalValue &)> mustPreserveGV)3638eb3397aSMehdi Amini void LTOCodeGenerator::preserveDiscardableGVs(
364022b5bcbSMehdi Amini     Module &TheModule,
365022b5bcbSMehdi Amini     llvm::function_ref<bool(const GlobalValue &)> mustPreserveGV) {
366ea6d49d3SEvgeniy Stepanov   std::vector<GlobalValue *> Used;
367022b5bcbSMehdi Amini   auto mayPreserveGlobal = [&](GlobalValue &GV) {
36841bfd6bdSDavide Italiano     if (!GV.isDiscardableIfUnused() || GV.isDeclaration() ||
36941bfd6bdSDavide Italiano         !mustPreserveGV(GV))
370022b5bcbSMehdi Amini       return;
37141bfd6bdSDavide Italiano     if (GV.hasAvailableExternallyLinkage())
37241bfd6bdSDavide Italiano       return emitWarning(
3738eb3397aSMehdi Amini           (Twine("Linker asked to preserve available_externally global: '") +
3748eb3397aSMehdi Amini            GV.getName() + "'").str());
37541bfd6bdSDavide Italiano     if (GV.hasInternalLinkage())
37641bfd6bdSDavide Italiano       return emitWarning((Twine("Linker asked to preserve internal global: '") +
3778eb3397aSMehdi Amini                    GV.getName() + "'").str());
378ea6d49d3SEvgeniy Stepanov     Used.push_back(&GV);
379022b5bcbSMehdi Amini   };
380022b5bcbSMehdi Amini   for (auto &GV : TheModule)
381022b5bcbSMehdi Amini     mayPreserveGlobal(GV);
382022b5bcbSMehdi Amini   for (auto &GV : TheModule.globals())
383022b5bcbSMehdi Amini     mayPreserveGlobal(GV);
384022b5bcbSMehdi Amini   for (auto &GV : TheModule.aliases())
385022b5bcbSMehdi Amini     mayPreserveGlobal(GV);
386022b5bcbSMehdi Amini 
387ea6d49d3SEvgeniy Stepanov   if (Used.empty())
388022b5bcbSMehdi Amini     return;
389022b5bcbSMehdi Amini 
390ea6d49d3SEvgeniy Stepanov   appendToCompilerUsed(TheModule, Used);
391022b5bcbSMehdi Amini }
392022b5bcbSMehdi Amini 
applyScopeRestrictions()3934ccf0f1bSPeter Collingbourne void LTOCodeGenerator::applyScopeRestrictions() {
394022b5bcbSMehdi Amini   if (ScopeRestrictionsDone)
395022b5bcbSMehdi Amini     return;
396022b5bcbSMehdi Amini 
397022b5bcbSMehdi Amini   // Declare a callback for the internalize pass that will ask for every
398022b5bcbSMehdi Amini   // candidate GlobalValue if it can be internalized or not.
39946aafc16SPeter Collingbourne   Mangler Mang;
400022b5bcbSMehdi Amini   SmallString<64> MangledName;
401022b5bcbSMehdi Amini   auto mustPreserveGV = [&](const GlobalValue &GV) -> bool {
402022b5bcbSMehdi Amini     // Unnamed globals can't be mangled, but they can't be preserved either.
403022b5bcbSMehdi Amini     if (!GV.hasName())
404022b5bcbSMehdi Amini       return false;
405022b5bcbSMehdi Amini 
406022b5bcbSMehdi Amini     // Need to mangle the GV as the "MustPreserveSymbols" StringSet is filled
407022b5bcbSMehdi Amini     // with the linker supplied name, which on Darwin includes a leading
408022b5bcbSMehdi Amini     // underscore.
409022b5bcbSMehdi Amini     MangledName.clear();
410022b5bcbSMehdi Amini     MangledName.reserve(GV.getName().size() + 1);
41146aafc16SPeter Collingbourne     Mang.getNameWithPrefix(MangledName, &GV, /*CannotUsePrivateLabel=*/false);
412022b5bcbSMehdi Amini     return MustPreserveSymbols.count(MangledName);
413022b5bcbSMehdi Amini   };
414022b5bcbSMehdi Amini 
415022b5bcbSMehdi Amini   // Preserve linkonce value on linker request
416022b5bcbSMehdi Amini   preserveDiscardableGVs(*MergedModule, mustPreserveGV);
417022b5bcbSMehdi Amini 
418022b5bcbSMehdi Amini   if (!ShouldInternalize)
4194ccf0f1bSPeter Collingbourne     return;
4204ccf0f1bSPeter Collingbourne 
421deee003aSMehdi Amini   if (ShouldRestoreGlobalsLinkage) {
422deee003aSMehdi Amini     // Record the linkage type of non-local symbols so they can be restored
423752ffe9cSMehdi Amini     // prior
424752ffe9cSMehdi Amini     // to module splitting.
425deee003aSMehdi Amini     auto RecordLinkage = [&](const GlobalValue &GV) {
426deee003aSMehdi Amini       if (!GV.hasAvailableExternallyLinkage() && !GV.hasLocalLinkage() &&
427deee003aSMehdi Amini           GV.hasName())
428deee003aSMehdi Amini         ExternalSymbols.insert(std::make_pair(GV.getName(), GV.getLinkage()));
429deee003aSMehdi Amini     };
430deee003aSMehdi Amini     for (auto &GV : *MergedModule)
431deee003aSMehdi Amini       RecordLinkage(GV);
432deee003aSMehdi Amini     for (auto &GV : MergedModule->globals())
433deee003aSMehdi Amini       RecordLinkage(GV);
434deee003aSMehdi Amini     for (auto &GV : MergedModule->aliases())
435deee003aSMehdi Amini       RecordLinkage(GV);
436deee003aSMehdi Amini   }
437deee003aSMehdi Amini 
438ce23e970SMehdi Amini   // Update the llvm.compiler_used globals to force preserving libcalls and
439ce23e970SMehdi Amini   // symbols referenced from asm
44053d457c6SDavide Italiano   updateCompilerUsed(*MergedModule, *TargetMach, AsmUndefinedRefs);
441ce23e970SMehdi Amini 
442022b5bcbSMehdi Amini   internalizeModule(*MergedModule, mustPreserveGV);
4434ccf0f1bSPeter Collingbourne 
4444ccf0f1bSPeter Collingbourne   ScopeRestrictionsDone = true;
4454ccf0f1bSPeter Collingbourne }
4464ccf0f1bSPeter Collingbourne 
4478ecaf692STobias Edler von Koch /// Restore original linkage for symbols that may have been internalized
restoreLinkageForExternals()4488ecaf692STobias Edler von Koch void LTOCodeGenerator::restoreLinkageForExternals() {
4498ecaf692STobias Edler von Koch   if (!ShouldInternalize || !ShouldRestoreGlobalsLinkage)
4508ecaf692STobias Edler von Koch     return;
4518ecaf692STobias Edler von Koch 
4528ecaf692STobias Edler von Koch   assert(ScopeRestrictionsDone &&
4538ecaf692STobias Edler von Koch          "Cannot externalize without internalization!");
4548ecaf692STobias Edler von Koch 
4558ecaf692STobias Edler von Koch   if (ExternalSymbols.empty())
4568ecaf692STobias Edler von Koch     return;
4578ecaf692STobias Edler von Koch 
4588ecaf692STobias Edler von Koch   auto externalize = [this](GlobalValue &GV) {
4598ecaf692STobias Edler von Koch     if (!GV.hasLocalLinkage() || !GV.hasName())
4608ecaf692STobias Edler von Koch       return;
4618ecaf692STobias Edler von Koch 
4628ecaf692STobias Edler von Koch     auto I = ExternalSymbols.find(GV.getName());
4638ecaf692STobias Edler von Koch     if (I == ExternalSymbols.end())
4648ecaf692STobias Edler von Koch       return;
4658ecaf692STobias Edler von Koch 
4668ecaf692STobias Edler von Koch     GV.setLinkage(I->second);
4678ecaf692STobias Edler von Koch   };
4688ecaf692STobias Edler von Koch 
469ecf0e952SAaron Ballman   llvm::for_each(MergedModule->functions(), externalize);
470ecf0e952SAaron Ballman   llvm::for_each(MergedModule->globals(), externalize);
471ecf0e952SAaron Ballman   llvm::for_each(MergedModule->aliases(), externalize);
4728ecaf692STobias Edler von Koch }
4738ecaf692STobias Edler von Koch 
verifyMergedModuleOnce()474b011ad73SDuncan P. N. Exon Smith void LTOCodeGenerator::verifyMergedModuleOnce() {
475b011ad73SDuncan P. N. Exon Smith   // Only run on the first call.
476b011ad73SDuncan P. N. Exon Smith   if (HasVerifiedInput)
477b011ad73SDuncan P. N. Exon Smith     return;
478b011ad73SDuncan P. N. Exon Smith   HasVerifiedInput = true;
479b011ad73SDuncan P. N. Exon Smith 
480fe7a3824SAdrian Prantl   bool BrokenDebugInfo = false;
481a8b2ddbdSAdrian Prantl   if (verifyModule(*MergedModule, &dbgs(), &BrokenDebugInfo))
482fe7a3824SAdrian Prantl     report_fatal_error("Broken module found, compilation aborted!");
483fe7a3824SAdrian Prantl   if (BrokenDebugInfo) {
484fe7a3824SAdrian Prantl     emitWarning("Invalid debug info found, debug info will be stripped");
485fe7a3824SAdrian Prantl     StripDebugInfo(*MergedModule);
486fe7a3824SAdrian Prantl   }
487fe7a3824SAdrian Prantl }
488b011ad73SDuncan P. N. Exon Smith 
finishOptimizationRemarks()489e9bd022cSAdam Nemet void LTOCodeGenerator::finishOptimizationRemarks() {
490e9bd022cSAdam Nemet   if (DiagnosticOutputFile) {
491e9bd022cSAdam Nemet     DiagnosticOutputFile->keep();
492e9bd022cSAdam Nemet     // FIXME: LTOCodeGenerator dtor is not invoked on Darwin
493e9bd022cSAdam Nemet     DiagnosticOutputFile->os().flush();
494e9bd022cSAdam Nemet   }
495e9bd022cSAdam Nemet }
496e9bd022cSAdam Nemet 
4974ccf0f1bSPeter Collingbourne /// Optimize merged modules using various IPO passes
optimize()498f959d819SFlorian Hahn bool LTOCodeGenerator::optimize() {
4998e348cc7SYunzhong Gao   if (!this->determineTarget())
5004ccf0f1bSPeter Collingbourne     return false;
5014ccf0f1bSPeter Collingbourne 
5023acda917SWei Wang   auto DiagFileOrErr = lto::setupLLVMOptimizationRemarks(
5033acda917SWei Wang       Context, RemarksFilename, RemarksPasses, RemarksFormat,
5043acda917SWei Wang       RemarksWithHotness, RemarksHotnessThreshold);
50546d72b1bSDavide Italiano   if (!DiagFileOrErr) {
50646d72b1bSDavide Italiano     errs() << "Error: " << toString(DiagFileOrErr.takeError()) << "\n";
50746d72b1bSDavide Italiano     report_fatal_error("Can't get an output file for the remarks");
50846d72b1bSDavide Italiano   }
50946d72b1bSDavide Italiano   DiagnosticOutputFile = std::move(*DiagFileOrErr);
510e9bd022cSAdam Nemet 
511b340497fSFlorian Hahn   // Setup output file to emit statistics.
512b340497fSFlorian Hahn   auto StatsFileOrErr = lto::setupStatsFile(LTOStatsFile);
513b340497fSFlorian Hahn   if (!StatsFileOrErr) {
514b340497fSFlorian Hahn     errs() << "Error: " << toString(StatsFileOrErr.takeError()) << "\n";
515b340497fSFlorian Hahn     report_fatal_error("Can't get an output file for the statistics");
516b340497fSFlorian Hahn   }
517b340497fSFlorian Hahn   StatsFile = std::move(StatsFileOrErr.get());
518b340497fSFlorian Hahn 
5192f63d549STeresa Johnson   // Currently there is no support for enabling whole program visibility via a
5202f63d549STeresa Johnson   // linker option in the old LTO API, but this call allows it to be specified
5212f63d549STeresa Johnson   // via the internal option. Must be done before WPD invoked via the optimizer
5222f63d549STeresa Johnson   // pipeline run below.
523*2eade1dbSArthur Eubanks   updatePublicTypeTestCalls(*MergedModule,
524*2eade1dbSArthur Eubanks                             /* WholeProgramVisibilityEnabledInLTO */ false);
5252f63d549STeresa Johnson   updateVCallVisibilityInModule(*MergedModule,
5261487747eSTeresa Johnson                                 /* WholeProgramVisibilityEnabledInLTO */ false,
5271487747eSTeresa Johnson                                 // FIXME: This needs linker information via a
5281487747eSTeresa Johnson                                 // TBD new interface.
5291487747eSTeresa Johnson                                 /* DynamicExportSymbols */ {});
5302f63d549STeresa Johnson 
531f59f2bb1SMehdi Amini   // We always run the verifier once on the merged module, the `DisableVerify`
532f59f2bb1SMehdi Amini   // parameter only applies to subsequent verify.
533b011ad73SDuncan P. N. Exon Smith   verifyMergedModuleOnce();
534f59f2bb1SMehdi Amini 
5354ccf0f1bSPeter Collingbourne   // Mark which symbols can not be internalized
5364ccf0f1bSPeter Collingbourne   this->applyScopeRestrictions();
5374ccf0f1bSPeter Collingbourne 
538476ca330SSteven Wu   // Write LTOPostLink flag for passes that require all the modules.
539476ca330SSteven Wu   MergedModule->addModuleFlag(Module::Error, "LTOPostLink", 1);
540476ca330SSteven Wu 
5414ccf0f1bSPeter Collingbourne   // Add an appropriate DataLayout instance for this module...
542e34034c8SPeter Collingbourne   MergedModule->setDataLayout(TargetMach->createDataLayout());
5434ccf0f1bSPeter Collingbourne 
544*2eade1dbSArthur Eubanks   if (!SaveIRBeforeOptPath.empty()) {
545*2eade1dbSArthur Eubanks     std::error_code EC;
546*2eade1dbSArthur Eubanks     raw_fd_ostream OS(SaveIRBeforeOptPath, EC, sys::fs::OF_None);
547*2eade1dbSArthur Eubanks     if (EC)
548*2eade1dbSArthur Eubanks       report_fatal_error(Twine("Failed to open ") + SaveIRBeforeOptPath +
549*2eade1dbSArthur Eubanks                          " to save optimized bitcode\n");
550*2eade1dbSArthur Eubanks     WriteBitcodeToFile(*MergedModule, OS,
551*2eade1dbSArthur Eubanks                        /* ShouldPreserveUseListOrder */ true);
552*2eade1dbSArthur Eubanks   }
553*2eade1dbSArthur Eubanks 
554c70737baSFlorian Hahn   ModuleSummaryIndex CombinedIndex(false);
555c70737baSFlorian Hahn   TargetMach = createTargetMachine();
556c70737baSFlorian Hahn   if (!opt(Config, TargetMach.get(), 0, *MergedModule, /*IsThinLTO=*/false,
557c70737baSFlorian Hahn            /*ExportSummary=*/&CombinedIndex, /*ImportSummary=*/nullptr,
558c70737baSFlorian Hahn            /*CmdArgs*/ std::vector<uint8_t>())) {
559c70737baSFlorian Hahn     emitError("LTO middle-end optimizations failed");
560c70737baSFlorian Hahn     return false;
561c70737baSFlorian Hahn   }
5628121e1dbSManman Ren 
5638121e1dbSManman Ren   return true;
5648121e1dbSManman Ren }
5658121e1dbSManman Ren 
compileOptimized(AddStreamFn AddStream,unsigned ParallelismLevel)566e678c511SNoah Shutty bool LTOCodeGenerator::compileOptimized(AddStreamFn AddStream,
567c70737baSFlorian Hahn                                         unsigned ParallelismLevel) {
5688e348cc7SYunzhong Gao   if (!this->determineTarget())
5698121e1dbSManman Ren     return false;
5708121e1dbSManman Ren 
571b011ad73SDuncan P. N. Exon Smith   // We always run the verifier once on the merged module.  If it has already
572b011ad73SDuncan P. N. Exon Smith   // been called in optimize(), this call will return early.
573b011ad73SDuncan P. N. Exon Smith   verifyMergedModuleOnce();
574b011ad73SDuncan P. N. Exon Smith 
5758ecaf692STobias Edler von Koch   // Re-externalize globals that may have been internalized to increase scope
5768ecaf692STobias Edler von Koch   // for splitting
5778ecaf692STobias Edler von Koch   restoreLinkageForExternals();
5788ecaf692STobias Edler von Koch 
579c70737baSFlorian Hahn   ModuleSummaryIndex CombinedIndex(false);
580c70737baSFlorian Hahn 
581c70737baSFlorian Hahn   Config.CodeGenOnly = true;
582c70737baSFlorian Hahn   Error Err = backend(Config, AddStream, ParallelismLevel, *MergedModule,
583c70737baSFlorian Hahn                       CombinedIndex);
584c70737baSFlorian Hahn   assert(!Err && "unexpected code-generation failure");
585c70737baSFlorian Hahn   (void)Err;
5864ccf0f1bSPeter Collingbourne 
587b340497fSFlorian Hahn   // If statistics were requested, save them to the specified file or
588b340497fSFlorian Hahn   // print them out after codegen.
589b340497fSFlorian Hahn   if (StatsFile)
590b340497fSFlorian Hahn     PrintStatisticsJSON(StatsFile->os());
591b340497fSFlorian Hahn   else if (AreStatisticsEnabled())
592b340497fSFlorian Hahn     PrintStatistics();
593b340497fSFlorian Hahn 
594852f6fdeSJames Henderson   reportAndResetTimings();
595106fedabSAdam Nemet 
59658951d38SAdam Nemet   finishOptimizationRemarks();
59758951d38SAdam Nemet 
5984ccf0f1bSPeter Collingbourne   return true;
5994ccf0f1bSPeter Collingbourne }
6004ccf0f1bSPeter Collingbourne 
setCodeGenDebugOptions(ArrayRef<StringRef> Options)60175b0bbcaSMomchil Velikov void LTOCodeGenerator::setCodeGenDebugOptions(ArrayRef<StringRef> Options) {
602bffdee8eSFrancis Visoiu Mistrih   for (StringRef Option : Options)
60375b0bbcaSMomchil Velikov     CodegenOptions.push_back(Option.str());
6044ccf0f1bSPeter Collingbourne }
605efa02d53SRafael Espindola 
parseCodeGenDebugOptions()606efa02d53SRafael Espindola void LTOCodeGenerator::parseCodeGenDebugOptions() {
607563cdeaaSWael Yehia   if (!CodegenOptions.empty())
608563cdeaaSWael Yehia     llvm::parseCommandLineOptions(CodegenOptions);
609563cdeaaSWael Yehia }
610563cdeaaSWael Yehia 
parseCommandLineOptions(std::vector<std::string> & Options)611563cdeaaSWael Yehia void llvm::parseCommandLineOptions(std::vector<std::string> &Options) {
612563cdeaaSWael Yehia   if (!Options.empty()) {
6132257512fSPeter Collingbourne     // ParseCommandLineOptions() expects argv[0] to be program name.
6142257512fSPeter Collingbourne     std::vector<const char *> CodegenArgv(1, "libLLVMLTO");
615563cdeaaSWael Yehia     for (std::string &Arg : Options)
6162257512fSPeter Collingbourne       CodegenArgv.push_back(Arg.c_str());
6172257512fSPeter Collingbourne     cl::ParseCommandLineOptions(CodegenArgv.size(), CodegenArgv.data());
6182257512fSPeter Collingbourne   }
619efa02d53SRafael Espindola }
6205fa1f6f5SQuentin Colombet 
DiagnosticHandler(const DiagnosticInfo & DI)621b5ab895eSVivek Pandya void LTOCodeGenerator::DiagnosticHandler(const DiagnosticInfo &DI) {
6225fa1f6f5SQuentin Colombet   // Map the LLVM internal diagnostic severity to the LTO diagnostic severity.
6235fa1f6f5SQuentin Colombet   lto_codegen_diagnostic_severity_t Severity;
6245fa1f6f5SQuentin Colombet   switch (DI.getSeverity()) {
6255fa1f6f5SQuentin Colombet   case DS_Error:
6265fa1f6f5SQuentin Colombet     Severity = LTO_DS_ERROR;
6275fa1f6f5SQuentin Colombet     break;
6285fa1f6f5SQuentin Colombet   case DS_Warning:
6295fa1f6f5SQuentin Colombet     Severity = LTO_DS_WARNING;
6305fa1f6f5SQuentin Colombet     break;
631e8d4c9a2STobias Grosser   case DS_Remark:
632e8d4c9a2STobias Grosser     Severity = LTO_DS_REMARK;
633e8d4c9a2STobias Grosser     break;
6345fa1f6f5SQuentin Colombet   case DS_Note:
6355fa1f6f5SQuentin Colombet     Severity = LTO_DS_NOTE;
6365fa1f6f5SQuentin Colombet     break;
6375fa1f6f5SQuentin Colombet   }
6385fa1f6f5SQuentin Colombet   // Create the string that will be reported to the external diagnostic handler.
639e69170a1SAlp Toker   std::string MsgStorage;
640e69170a1SAlp Toker   raw_string_ostream Stream(MsgStorage);
641e69170a1SAlp Toker   DiagnosticPrinterRawOStream DP(Stream);
6425fa1f6f5SQuentin Colombet   DI.print(DP);
643e69170a1SAlp Toker   Stream.flush();
6445fa1f6f5SQuentin Colombet 
6455fa1f6f5SQuentin Colombet   // If this method has been called it means someone has set up an external
6465fa1f6f5SQuentin Colombet   // diagnostic handler. Assert on that.
6475fa1f6f5SQuentin Colombet   assert(DiagHandler && "Invalid diagnostic handler");
648e69170a1SAlp Toker   (*DiagHandler)(Severity, MsgStorage.c_str(), DiagContext);
6495fa1f6f5SQuentin Colombet }
6505fa1f6f5SQuentin Colombet 
651b5ab895eSVivek Pandya namespace {
652b5ab895eSVivek Pandya struct LTODiagnosticHandler : public DiagnosticHandler {
653b5ab895eSVivek Pandya   LTOCodeGenerator *CodeGenerator;
LTODiagnosticHandler__anon8640e98f0711::LTODiagnosticHandler654b5ab895eSVivek Pandya   LTODiagnosticHandler(LTOCodeGenerator *CodeGenPtr)
655b5ab895eSVivek Pandya       : CodeGenerator(CodeGenPtr) {}
handleDiagnostics__anon8640e98f0711::LTODiagnosticHandler656b5ab895eSVivek Pandya   bool handleDiagnostics(const DiagnosticInfo &DI) override {
657b5ab895eSVivek Pandya     CodeGenerator->DiagnosticHandler(DI);
658b5ab895eSVivek Pandya     return true;
659b5ab895eSVivek Pandya   }
660b5ab895eSVivek Pandya };
661b5ab895eSVivek Pandya }
662b5ab895eSVivek Pandya 
6635fa1f6f5SQuentin Colombet void
setDiagnosticHandler(lto_diagnostic_handler_t DiagHandler,void * Ctxt)6645fa1f6f5SQuentin Colombet LTOCodeGenerator::setDiagnosticHandler(lto_diagnostic_handler_t DiagHandler,
6655fa1f6f5SQuentin Colombet                                        void *Ctxt) {
6665fa1f6f5SQuentin Colombet   this->DiagHandler = DiagHandler;
6675fa1f6f5SQuentin Colombet   this->DiagContext = Ctxt;
6685fa1f6f5SQuentin Colombet   if (!DiagHandler)
669b5ab895eSVivek Pandya     return Context.setDiagnosticHandler(nullptr);
6705fa1f6f5SQuentin Colombet   // Register the LTOCodeGenerator stub in the LLVMContext to forward the
6715fa1f6f5SQuentin Colombet   // diagnostic to the external DiagHandler.
6720eaee545SJonas Devlieghere   Context.setDiagnosticHandler(std::make_unique<LTODiagnosticHandler>(this),
673b5ab895eSVivek Pandya                                true);
6745fa1f6f5SQuentin Colombet }
6758e348cc7SYunzhong Gao 
6768e348cc7SYunzhong Gao namespace {
6778e348cc7SYunzhong Gao class LTODiagnosticInfo : public DiagnosticInfo {
6788e348cc7SYunzhong Gao   const Twine &Msg;
6798e348cc7SYunzhong Gao public:
LTODiagnosticInfo(const Twine & DiagMsg,DiagnosticSeverity Severity=DS_Error)6808e348cc7SYunzhong Gao   LTODiagnosticInfo(const Twine &DiagMsg, DiagnosticSeverity Severity=DS_Error)
6818e348cc7SYunzhong Gao       : DiagnosticInfo(DK_Linker, Severity), Msg(DiagMsg) {}
print(DiagnosticPrinter & DP) const6828e348cc7SYunzhong Gao   void print(DiagnosticPrinter &DP) const override { DP << Msg; }
6838e348cc7SYunzhong Gao };
6848e348cc7SYunzhong Gao }
6858e348cc7SYunzhong Gao 
emitError(const std::string & ErrMsg)6868e348cc7SYunzhong Gao void LTOCodeGenerator::emitError(const std::string &ErrMsg) {
6878e348cc7SYunzhong Gao   if (DiagHandler)
6888e348cc7SYunzhong Gao     (*DiagHandler)(LTO_DS_ERROR, ErrMsg.c_str(), DiagContext);
6898e348cc7SYunzhong Gao   else
6908e348cc7SYunzhong Gao     Context.diagnose(LTODiagnosticInfo(ErrMsg));
6918e348cc7SYunzhong Gao }
6928eb3397aSMehdi Amini 
emitWarning(const std::string & ErrMsg)6938eb3397aSMehdi Amini void LTOCodeGenerator::emitWarning(const std::string &ErrMsg) {
6948eb3397aSMehdi Amini   if (DiagHandler)
6958eb3397aSMehdi Amini     (*DiagHandler)(LTO_DS_WARNING, ErrMsg.c_str(), DiagContext);
6968eb3397aSMehdi Amini   else
6978eb3397aSMehdi Amini     Context.diagnose(LTODiagnosticInfo(ErrMsg, DS_Warning));
6988eb3397aSMehdi Amini }
699