1f785676fSDimitry Andric //===-LTOCodeGenerator.cpp - LLVM Link Time Optimizer ---------------------===//
2f785676fSDimitry Andric //
3f785676fSDimitry Andric //                     The LLVM Compiler Infrastructure
4f785676fSDimitry Andric //
5f785676fSDimitry Andric // This file is distributed under the University of Illinois Open Source
6f785676fSDimitry Andric // License. See LICENSE.TXT for details.
7f785676fSDimitry Andric //
8f785676fSDimitry Andric //===----------------------------------------------------------------------===//
9f785676fSDimitry Andric //
10f785676fSDimitry Andric // This file implements the Link Time Optimization library. This library is
11f785676fSDimitry Andric // intended to be used by linker to optimize code at link time.
12f785676fSDimitry Andric //
13f785676fSDimitry Andric //===----------------------------------------------------------------------===//
14f785676fSDimitry Andric 
153ca95b02SDimitry Andric #include "llvm/LTO/legacy/LTOCodeGenerator.h"
163ca95b02SDimitry Andric 
173ca95b02SDimitry Andric #include "llvm/ADT/Statistic.h"
18f785676fSDimitry Andric #include "llvm/ADT/StringExtras.h"
19f785676fSDimitry Andric #include "llvm/Analysis/Passes.h"
20ff0cc061SDimitry Andric #include "llvm/Analysis/TargetLibraryInfo.h"
21ff0cc061SDimitry Andric #include "llvm/Analysis/TargetTransformInfo.h"
22d88c1a5aSDimitry Andric #include "llvm/Bitcode/BitcodeWriter.h"
237d523365SDimitry Andric #include "llvm/CodeGen/ParallelCG.h"
242cab237bSDimitry Andric #include "llvm/CodeGen/TargetSubtargetInfo.h"
25f785676fSDimitry Andric #include "llvm/Config/config.h"
26f785676fSDimitry Andric #include "llvm/IR/Constants.h"
27f785676fSDimitry Andric #include "llvm/IR/DataLayout.h"
283ca95b02SDimitry Andric #include "llvm/IR/DebugInfo.h"
29f785676fSDimitry Andric #include "llvm/IR/DerivedTypes.h"
3091bc56edSDimitry Andric #include "llvm/IR/DiagnosticInfo.h"
3191bc56edSDimitry Andric #include "llvm/IR/DiagnosticPrinter.h"
32f785676fSDimitry Andric #include "llvm/IR/LLVMContext.h"
33ff0cc061SDimitry Andric #include "llvm/IR/LegacyPassManager.h"
3491bc56edSDimitry Andric #include "llvm/IR/Mangler.h"
35f785676fSDimitry Andric #include "llvm/IR/Module.h"
3691bc56edSDimitry Andric #include "llvm/IR/Verifier.h"
37f785676fSDimitry Andric #include "llvm/InitializePasses.h"
387a7e6055SDimitry Andric #include "llvm/LTO/LTO.h"
393ca95b02SDimitry Andric #include "llvm/LTO/legacy/LTOModule.h"
403ca95b02SDimitry Andric #include "llvm/LTO/legacy/UpdateCompilerUsed.h"
4191bc56edSDimitry Andric #include "llvm/Linker/Linker.h"
42f785676fSDimitry Andric #include "llvm/MC/MCAsmInfo.h"
43f785676fSDimitry Andric #include "llvm/MC/MCContext.h"
44f785676fSDimitry Andric #include "llvm/MC/SubtargetFeature.h"
45f785676fSDimitry Andric #include "llvm/Support/CommandLine.h"
46f785676fSDimitry Andric #include "llvm/Support/FileSystem.h"
47f785676fSDimitry Andric #include "llvm/Support/Host.h"
48f785676fSDimitry Andric #include "llvm/Support/MemoryBuffer.h"
49f785676fSDimitry Andric #include "llvm/Support/Signals.h"
50f785676fSDimitry Andric #include "llvm/Support/TargetRegistry.h"
51f785676fSDimitry Andric #include "llvm/Support/TargetSelect.h"
52f785676fSDimitry Andric #include "llvm/Support/ToolOutputFile.h"
53d88c1a5aSDimitry Andric #include "llvm/Support/YAMLTraits.h"
5491bc56edSDimitry Andric #include "llvm/Support/raw_ostream.h"
55f785676fSDimitry Andric #include "llvm/Target/TargetOptions.h"
56f785676fSDimitry Andric #include "llvm/Transforms/IPO.h"
573ca95b02SDimitry Andric #include "llvm/Transforms/IPO/Internalize.h"
58f785676fSDimitry Andric #include "llvm/Transforms/IPO/PassManagerBuilder.h"
59f785676fSDimitry Andric #include "llvm/Transforms/ObjCARC.h"
60d88c1a5aSDimitry Andric #include "llvm/Transforms/Utils/ModuleUtils.h"
6191bc56edSDimitry Andric #include <system_error>
62f785676fSDimitry Andric using namespace llvm;
63f785676fSDimitry Andric 
64f785676fSDimitry Andric const char* LTOCodeGenerator::getVersionString() {
65f785676fSDimitry Andric #ifdef LLVM_VERSION_INFO
66f785676fSDimitry Andric   return PACKAGE_NAME " version " PACKAGE_VERSION ", " LLVM_VERSION_INFO;
67f785676fSDimitry Andric #else
68f785676fSDimitry Andric   return PACKAGE_NAME " version " PACKAGE_VERSION;
69f785676fSDimitry Andric #endif
70f785676fSDimitry Andric }
71f785676fSDimitry Andric 
723ca95b02SDimitry Andric namespace llvm {
733ca95b02SDimitry Andric cl::opt<bool> LTODiscardValueNames(
743ca95b02SDimitry Andric     "lto-discard-value-names",
753ca95b02SDimitry Andric     cl::desc("Strip names from Value during LTO (other than GlobalValue)."),
763ca95b02SDimitry Andric #ifdef NDEBUG
773ca95b02SDimitry Andric     cl::init(true),
783ca95b02SDimitry Andric #else
793ca95b02SDimitry Andric     cl::init(false),
803ca95b02SDimitry Andric #endif
813ca95b02SDimitry Andric     cl::Hidden);
823ca95b02SDimitry Andric 
83d88c1a5aSDimitry Andric cl::opt<std::string>
84d88c1a5aSDimitry Andric     LTORemarksFilename("lto-pass-remarks-output",
85d88c1a5aSDimitry Andric                        cl::desc("Output filename for pass remarks"),
86d88c1a5aSDimitry Andric                        cl::value_desc("filename"));
87d88c1a5aSDimitry Andric 
88d88c1a5aSDimitry Andric cl::opt<bool> LTOPassRemarksWithHotness(
89d88c1a5aSDimitry Andric     "lto-pass-remarks-with-hotness",
90d88c1a5aSDimitry Andric     cl::desc("With PGO, include profile count in optimization remarks"),
91d88c1a5aSDimitry Andric     cl::Hidden);
923ca95b02SDimitry Andric }
933ca95b02SDimitry Andric 
947d523365SDimitry Andric LTOCodeGenerator::LTOCodeGenerator(LLVMContext &Context)
957d523365SDimitry Andric     : Context(Context), MergedModule(new Module("ld-temp.o", Context)),
967d523365SDimitry Andric       TheLinker(new Linker(*MergedModule)) {
973ca95b02SDimitry Andric   Context.setDiscardValueNames(LTODiscardValueNames);
983ca95b02SDimitry Andric   Context.enableDebugTypeODRUniquing();
99ff0cc061SDimitry Andric   initializeLTOPasses();
10039d628a0SDimitry Andric }
10139d628a0SDimitry Andric 
1027d523365SDimitry Andric LTOCodeGenerator::~LTOCodeGenerator() {}
103f785676fSDimitry Andric 
1047d523365SDimitry Andric // Initialize LTO passes. Please keep this function in sync with
105f785676fSDimitry Andric // PassManagerBuilder::populateLTOPassManager(), and make sure all LTO
106f785676fSDimitry Andric // passes are initialized.
107f785676fSDimitry Andric void LTOCodeGenerator::initializeLTOPasses() {
108f785676fSDimitry Andric   PassRegistry &R = *PassRegistry::getPassRegistry();
109f785676fSDimitry Andric 
1103ca95b02SDimitry Andric   initializeInternalizeLegacyPassPass(R);
1113ca95b02SDimitry Andric   initializeIPSCCPLegacyPassPass(R);
1123ca95b02SDimitry Andric   initializeGlobalOptLegacyPassPass(R);
1133ca95b02SDimitry Andric   initializeConstantMergeLegacyPassPass(R);
114f785676fSDimitry Andric   initializeDAHPass(R);
115ff0cc061SDimitry Andric   initializeInstructionCombiningPassPass(R);
116f785676fSDimitry Andric   initializeSimpleInlinerPass(R);
117f785676fSDimitry Andric   initializePruneEHPass(R);
1183ca95b02SDimitry Andric   initializeGlobalDCELegacyPassPass(R);
119f785676fSDimitry Andric   initializeArgPromotionPass(R);
120f785676fSDimitry Andric   initializeJumpThreadingPass(R);
1217d523365SDimitry Andric   initializeSROALegacyPassPass(R);
1223ca95b02SDimitry Andric   initializePostOrderFunctionAttrsLegacyPassPass(R);
1233ca95b02SDimitry Andric   initializeReversePostOrderFunctionAttrsLegacyPassPass(R);
1247d523365SDimitry Andric   initializeGlobalsAAWrapperPassPass(R);
1253ca95b02SDimitry Andric   initializeLegacyLICMPassPass(R);
1263ca95b02SDimitry Andric   initializeMergedLoadStoreMotionLegacyPassPass(R);
1273ca95b02SDimitry Andric   initializeGVNLegacyPassPass(R);
1283ca95b02SDimitry Andric   initializeMemCpyOptLegacyPassPass(R);
1293ca95b02SDimitry Andric   initializeDCELegacyPassPass(R);
130f785676fSDimitry Andric   initializeCFGSimplifyPassPass(R);
131f785676fSDimitry Andric }
132f785676fSDimitry Andric 
133d88c1a5aSDimitry Andric void LTOCodeGenerator::setAsmUndefinedRefs(LTOModule *Mod) {
134d88c1a5aSDimitry Andric   const std::vector<StringRef> &undefs = Mod->getAsmUndefinedRefs();
135d88c1a5aSDimitry Andric   for (int i = 0, e = undefs.size(); i != e; ++i)
136d88c1a5aSDimitry Andric     AsmUndefinedRefs[undefs[i]] = 1;
137d88c1a5aSDimitry Andric }
138d88c1a5aSDimitry Andric 
1397d523365SDimitry Andric bool LTOCodeGenerator::addModule(LTOModule *Mod) {
1407d523365SDimitry Andric   assert(&Mod->getModule().getContext() == &Context &&
14139d628a0SDimitry Andric          "Expected module in same context");
14239d628a0SDimitry Andric 
1437d523365SDimitry Andric   bool ret = TheLinker->linkInModule(Mod->takeModule());
144d88c1a5aSDimitry Andric   setAsmUndefinedRefs(Mod);
145f785676fSDimitry Andric 
1463ca95b02SDimitry Andric   // We've just changed the input, so let's make sure we verify it.
1473ca95b02SDimitry Andric   HasVerifiedInput = false;
1483ca95b02SDimitry Andric 
149f785676fSDimitry Andric   return !ret;
150f785676fSDimitry Andric }
151f785676fSDimitry Andric 
1527d523365SDimitry Andric void LTOCodeGenerator::setModule(std::unique_ptr<LTOModule> Mod) {
153ff0cc061SDimitry Andric   assert(&Mod->getModule().getContext() == &Context &&
154ff0cc061SDimitry Andric          "Expected module in same context");
155ff0cc061SDimitry Andric 
156ff0cc061SDimitry Andric   AsmUndefinedRefs.clear();
157ff0cc061SDimitry Andric 
1587d523365SDimitry Andric   MergedModule = Mod->takeModule();
1597d523365SDimitry Andric   TheLinker = make_unique<Linker>(*MergedModule);
160d88c1a5aSDimitry Andric   setAsmUndefinedRefs(&*Mod);
1613ca95b02SDimitry Andric 
1623ca95b02SDimitry Andric   // We've just changed the input, so let's make sure we verify it.
1633ca95b02SDimitry Andric   HasVerifiedInput = false;
164ff0cc061SDimitry Andric }
165ff0cc061SDimitry Andric 
1663ca95b02SDimitry Andric void LTOCodeGenerator::setTargetOptions(const TargetOptions &Options) {
1677d523365SDimitry Andric   this->Options = Options;
168f785676fSDimitry Andric }
169f785676fSDimitry Andric 
1707d523365SDimitry Andric void LTOCodeGenerator::setDebugInfo(lto_debug_model Debug) {
1717d523365SDimitry Andric   switch (Debug) {
172f785676fSDimitry Andric   case LTO_DEBUG_MODEL_NONE:
173f785676fSDimitry Andric     EmitDwarfDebugInfo = false;
174f785676fSDimitry Andric     return;
175f785676fSDimitry Andric 
176f785676fSDimitry Andric   case LTO_DEBUG_MODEL_DWARF:
177f785676fSDimitry Andric     EmitDwarfDebugInfo = true;
178f785676fSDimitry Andric     return;
179f785676fSDimitry Andric   }
180f785676fSDimitry Andric   llvm_unreachable("Unknown debug format!");
181f785676fSDimitry Andric }
182f785676fSDimitry Andric 
1837d523365SDimitry Andric void LTOCodeGenerator::setOptLevel(unsigned Level) {
1847d523365SDimitry Andric   OptLevel = Level;
185ff0cc061SDimitry Andric   switch (OptLevel) {
186ff0cc061SDimitry Andric   case 0:
187ff0cc061SDimitry Andric     CGOptLevel = CodeGenOpt::None;
188d88c1a5aSDimitry Andric     return;
189ff0cc061SDimitry Andric   case 1:
190ff0cc061SDimitry Andric     CGOptLevel = CodeGenOpt::Less;
191d88c1a5aSDimitry Andric     return;
192ff0cc061SDimitry Andric   case 2:
193ff0cc061SDimitry Andric     CGOptLevel = CodeGenOpt::Default;
194d88c1a5aSDimitry Andric     return;
195ff0cc061SDimitry Andric   case 3:
196ff0cc061SDimitry Andric     CGOptLevel = CodeGenOpt::Aggressive;
197d88c1a5aSDimitry Andric     return;
198ff0cc061SDimitry Andric   }
199d88c1a5aSDimitry Andric   llvm_unreachable("Unknown optimization level!");
2007d523365SDimitry Andric }
201ff0cc061SDimitry Andric 
202d88c1a5aSDimitry Andric bool LTOCodeGenerator::writeMergedModules(StringRef Path) {
2037d523365SDimitry Andric   if (!determineTarget())
2047d523365SDimitry Andric     return false;
2057d523365SDimitry Andric 
2063ca95b02SDimitry Andric   // We always run the verifier once on the merged module.
2073ca95b02SDimitry Andric   verifyMergedModuleOnce();
2083ca95b02SDimitry Andric 
2097d523365SDimitry Andric   // mark which symbols can not be internalized
2107d523365SDimitry Andric   applyScopeRestrictions();
2117d523365SDimitry Andric 
2127d523365SDimitry Andric   // create output file
2137d523365SDimitry Andric   std::error_code EC;
2142cab237bSDimitry Andric   ToolOutputFile Out(Path, EC, sys::fs::F_None);
2157d523365SDimitry Andric   if (EC) {
2167d523365SDimitry Andric     std::string ErrMsg = "could not open bitcode file for writing: ";
2172cab237bSDimitry Andric     ErrMsg += Path.str() + ": " + EC.message();
2187d523365SDimitry Andric     emitError(ErrMsg);
2197d523365SDimitry Andric     return false;
2207d523365SDimitry Andric   }
2217d523365SDimitry Andric 
2227d523365SDimitry Andric   // write bitcode to it
2237d523365SDimitry Andric   WriteBitcodeToFile(MergedModule.get(), Out.os(), ShouldEmbedUselists);
2247d523365SDimitry Andric   Out.os().close();
2257d523365SDimitry Andric 
2267d523365SDimitry Andric   if (Out.os().has_error()) {
2277d523365SDimitry Andric     std::string ErrMsg = "could not write bitcode file: ";
2282cab237bSDimitry Andric     ErrMsg += Path.str() + ": " + Out.os().error().message();
2297d523365SDimitry Andric     emitError(ErrMsg);
2307d523365SDimitry Andric     Out.os().clear_error();
2317d523365SDimitry Andric     return false;
2327d523365SDimitry Andric   }
2337d523365SDimitry Andric 
2347d523365SDimitry Andric   Out.keep();
2357d523365SDimitry Andric   return true;
2367d523365SDimitry Andric }
2377d523365SDimitry Andric 
2387d523365SDimitry Andric bool LTOCodeGenerator::compileOptimizedToFile(const char **Name) {
2397d523365SDimitry Andric   // make unique temp output file to put generated code
2407d523365SDimitry Andric   SmallString<128> Filename;
2417d523365SDimitry Andric   int FD;
2427d523365SDimitry Andric 
243d88c1a5aSDimitry Andric   StringRef Extension
2447d523365SDimitry Andric       (FileType == TargetMachine::CGFT_AssemblyFile ? "s" : "o");
2457d523365SDimitry Andric 
2467d523365SDimitry Andric   std::error_code EC =
2477d523365SDimitry Andric       sys::fs::createTemporaryFile("lto-llvm", Extension, FD, Filename);
2487d523365SDimitry Andric   if (EC) {
2497d523365SDimitry Andric     emitError(EC.message());
2507d523365SDimitry Andric     return false;
2517d523365SDimitry Andric   }
2527d523365SDimitry Andric 
2537d523365SDimitry Andric   // generate object file
2542cab237bSDimitry Andric   ToolOutputFile objFile(Filename, FD);
2557d523365SDimitry Andric 
2567d523365SDimitry Andric   bool genResult = compileOptimized(&objFile.os());
2577d523365SDimitry Andric   objFile.os().close();
2587d523365SDimitry Andric   if (objFile.os().has_error()) {
2592cab237bSDimitry Andric     emitError((Twine("could not write object file: ") + Filename + ": " +
2602cab237bSDimitry Andric                objFile.os().error().message())
2612cab237bSDimitry Andric                   .str());
2627d523365SDimitry Andric     objFile.os().clear_error();
2637d523365SDimitry Andric     sys::fs::remove(Twine(Filename));
2647d523365SDimitry Andric     return false;
2657d523365SDimitry Andric   }
2667d523365SDimitry Andric 
2677d523365SDimitry Andric   objFile.keep();
2687d523365SDimitry Andric   if (!genResult) {
2697d523365SDimitry Andric     sys::fs::remove(Twine(Filename));
2707d523365SDimitry Andric     return false;
2717d523365SDimitry Andric   }
2727d523365SDimitry Andric 
2737d523365SDimitry Andric   NativeObjectPath = Filename.c_str();
2747d523365SDimitry Andric   *Name = NativeObjectPath.c_str();
2757d523365SDimitry Andric   return true;
2767d523365SDimitry Andric }
2777d523365SDimitry Andric 
2787d523365SDimitry Andric std::unique_ptr<MemoryBuffer>
2797d523365SDimitry Andric LTOCodeGenerator::compileOptimized() {
2807d523365SDimitry Andric   const char *name;
2817d523365SDimitry Andric   if (!compileOptimizedToFile(&name))
2827d523365SDimitry Andric     return nullptr;
2837d523365SDimitry Andric 
2847d523365SDimitry Andric   // read .o file into memory buffer
2857d523365SDimitry Andric   ErrorOr<std::unique_ptr<MemoryBuffer>> BufferOrErr =
2867d523365SDimitry Andric       MemoryBuffer::getFile(name, -1, false);
2877d523365SDimitry Andric   if (std::error_code EC = BufferOrErr.getError()) {
2887d523365SDimitry Andric     emitError(EC.message());
2897d523365SDimitry Andric     sys::fs::remove(NativeObjectPath);
2907d523365SDimitry Andric     return nullptr;
2917d523365SDimitry Andric   }
2927d523365SDimitry Andric 
2937d523365SDimitry Andric   // remove temp files
2947d523365SDimitry Andric   sys::fs::remove(NativeObjectPath);
2957d523365SDimitry Andric 
2967d523365SDimitry Andric   return std::move(*BufferOrErr);
2977d523365SDimitry Andric }
2987d523365SDimitry Andric 
2997d523365SDimitry Andric bool LTOCodeGenerator::compile_to_file(const char **Name, bool DisableVerify,
3007d523365SDimitry Andric                                        bool DisableInline,
3017d523365SDimitry Andric                                        bool DisableGVNLoadPRE,
3027d523365SDimitry Andric                                        bool DisableVectorization) {
3037d523365SDimitry Andric   if (!optimize(DisableVerify, DisableInline, DisableGVNLoadPRE,
3047d523365SDimitry Andric                 DisableVectorization))
3057d523365SDimitry Andric     return false;
3067d523365SDimitry Andric 
3077d523365SDimitry Andric   return compileOptimizedToFile(Name);
3087d523365SDimitry Andric }
3097d523365SDimitry Andric 
3107d523365SDimitry Andric std::unique_ptr<MemoryBuffer>
3117d523365SDimitry Andric LTOCodeGenerator::compile(bool DisableVerify, bool DisableInline,
3127d523365SDimitry Andric                           bool DisableGVNLoadPRE, bool DisableVectorization) {
3137d523365SDimitry Andric   if (!optimize(DisableVerify, DisableInline, DisableGVNLoadPRE,
3147d523365SDimitry Andric                 DisableVectorization))
3157d523365SDimitry Andric     return nullptr;
3167d523365SDimitry Andric 
3177d523365SDimitry Andric   return compileOptimized();
3187d523365SDimitry Andric }
3197d523365SDimitry Andric 
3207d523365SDimitry Andric bool LTOCodeGenerator::determineTarget() {
3217d523365SDimitry Andric   if (TargetMach)
3227d523365SDimitry Andric     return true;
3237d523365SDimitry Andric 
3243ca95b02SDimitry Andric   TripleStr = MergedModule->getTargetTriple();
3257d523365SDimitry Andric   if (TripleStr.empty()) {
3267d523365SDimitry Andric     TripleStr = sys::getDefaultTargetTriple();
3277d523365SDimitry Andric     MergedModule->setTargetTriple(TripleStr);
3287d523365SDimitry Andric   }
3297d523365SDimitry Andric   llvm::Triple Triple(TripleStr);
3307d523365SDimitry Andric 
3317d523365SDimitry Andric   // create target machine from info for merged modules
3327d523365SDimitry Andric   std::string ErrMsg;
3333ca95b02SDimitry Andric   MArch = TargetRegistry::lookupTarget(TripleStr, ErrMsg);
3343ca95b02SDimitry Andric   if (!MArch) {
3357d523365SDimitry Andric     emitError(ErrMsg);
3367d523365SDimitry Andric     return false;
3377d523365SDimitry Andric   }
3387d523365SDimitry Andric 
3397d523365SDimitry Andric   // Construct LTOModule, hand over ownership of module and target. Use MAttr as
3407d523365SDimitry Andric   // the default set of features.
3417d523365SDimitry Andric   SubtargetFeatures Features(MAttr);
3427d523365SDimitry Andric   Features.getDefaultSubtargetFeatures(Triple);
3437d523365SDimitry Andric   FeatureStr = Features.getString();
3447d523365SDimitry Andric   // Set a default CPU for Darwin triples.
3457d523365SDimitry Andric   if (MCpu.empty() && Triple.isOSDarwin()) {
3467d523365SDimitry Andric     if (Triple.getArch() == llvm::Triple::x86_64)
3477d523365SDimitry Andric       MCpu = "core2";
3487d523365SDimitry Andric     else if (Triple.getArch() == llvm::Triple::x86)
3497d523365SDimitry Andric       MCpu = "yonah";
3507d523365SDimitry Andric     else if (Triple.getArch() == llvm::Triple::aarch64)
3517d523365SDimitry Andric       MCpu = "cyclone";
3527d523365SDimitry Andric   }
3537d523365SDimitry Andric 
3543ca95b02SDimitry Andric   TargetMach = createTargetMachine();
355f785676fSDimitry Andric   return true;
356f785676fSDimitry Andric }
357f785676fSDimitry Andric 
3583ca95b02SDimitry Andric std::unique_ptr<TargetMachine> LTOCodeGenerator::createTargetMachine() {
3592cab237bSDimitry Andric   return std::unique_ptr<TargetMachine>(MArch->createTargetMachine(
3602cab237bSDimitry Andric       TripleStr, MCpu, FeatureStr, Options, RelocModel, None, CGOptLevel));
361f785676fSDimitry Andric }
362f785676fSDimitry Andric 
3633ca95b02SDimitry Andric // If a linkonce global is present in the MustPreserveSymbols, we need to make
3643ca95b02SDimitry Andric // sure we honor this. To force the compiler to not drop it, we add it to the
3653ca95b02SDimitry Andric // "llvm.compiler.used" global.
3663ca95b02SDimitry Andric void LTOCodeGenerator::preserveDiscardableGVs(
3673ca95b02SDimitry Andric     Module &TheModule,
3683ca95b02SDimitry Andric     llvm::function_ref<bool(const GlobalValue &)> mustPreserveGV) {
369d88c1a5aSDimitry Andric   std::vector<GlobalValue *> Used;
3703ca95b02SDimitry Andric   auto mayPreserveGlobal = [&](GlobalValue &GV) {
371d88c1a5aSDimitry Andric     if (!GV.isDiscardableIfUnused() || GV.isDeclaration() ||
372d88c1a5aSDimitry Andric         !mustPreserveGV(GV))
3733ca95b02SDimitry Andric       return;
374d88c1a5aSDimitry Andric     if (GV.hasAvailableExternallyLinkage())
375d88c1a5aSDimitry Andric       return emitWarning(
3763ca95b02SDimitry Andric           (Twine("Linker asked to preserve available_externally global: '") +
3773ca95b02SDimitry Andric            GV.getName() + "'").str());
378d88c1a5aSDimitry Andric     if (GV.hasInternalLinkage())
379d88c1a5aSDimitry Andric       return emitWarning((Twine("Linker asked to preserve internal global: '") +
3803ca95b02SDimitry Andric                    GV.getName() + "'").str());
381d88c1a5aSDimitry Andric     Used.push_back(&GV);
3823ca95b02SDimitry Andric   };
3833ca95b02SDimitry Andric   for (auto &GV : TheModule)
3843ca95b02SDimitry Andric     mayPreserveGlobal(GV);
3853ca95b02SDimitry Andric   for (auto &GV : TheModule.globals())
3863ca95b02SDimitry Andric     mayPreserveGlobal(GV);
3873ca95b02SDimitry Andric   for (auto &GV : TheModule.aliases())
3883ca95b02SDimitry Andric     mayPreserveGlobal(GV);
389f785676fSDimitry Andric 
390d88c1a5aSDimitry Andric   if (Used.empty())
3913ca95b02SDimitry Andric     return;
3923ca95b02SDimitry Andric 
393d88c1a5aSDimitry Andric   appendToCompilerUsed(TheModule, Used);
394f785676fSDimitry Andric }
395f785676fSDimitry Andric 
396f785676fSDimitry Andric void LTOCodeGenerator::applyScopeRestrictions() {
3973ca95b02SDimitry Andric   if (ScopeRestrictionsDone)
398f785676fSDimitry Andric     return;
399f785676fSDimitry Andric 
4003ca95b02SDimitry Andric   // Declare a callback for the internalize pass that will ask for every
4013ca95b02SDimitry Andric   // candidate GlobalValue if it can be internalized or not.
402d88c1a5aSDimitry Andric   Mangler Mang;
4033ca95b02SDimitry Andric   SmallString<64> MangledName;
4043ca95b02SDimitry Andric   auto mustPreserveGV = [&](const GlobalValue &GV) -> bool {
4053ca95b02SDimitry Andric     // Unnamed globals can't be mangled, but they can't be preserved either.
4063ca95b02SDimitry Andric     if (!GV.hasName())
4073ca95b02SDimitry Andric       return false;
408f785676fSDimitry Andric 
4093ca95b02SDimitry Andric     // Need to mangle the GV as the "MustPreserveSymbols" StringSet is filled
4103ca95b02SDimitry Andric     // with the linker supplied name, which on Darwin includes a leading
4113ca95b02SDimitry Andric     // underscore.
4123ca95b02SDimitry Andric     MangledName.clear();
4133ca95b02SDimitry Andric     MangledName.reserve(GV.getName().size() + 1);
414d88c1a5aSDimitry Andric     Mang.getNameWithPrefix(MangledName, &GV, /*CannotUsePrivateLabel=*/false);
4153ca95b02SDimitry Andric     return MustPreserveSymbols.count(MangledName);
4163ca95b02SDimitry Andric   };
417ff0cc061SDimitry Andric 
4183ca95b02SDimitry Andric   // Preserve linkonce value on linker request
4193ca95b02SDimitry Andric   preserveDiscardableGVs(*MergedModule, mustPreserveGV);
420f785676fSDimitry Andric 
4213ca95b02SDimitry Andric   if (!ShouldInternalize)
4223ca95b02SDimitry Andric     return;
423f785676fSDimitry Andric 
4243ca95b02SDimitry Andric   if (ShouldRestoreGlobalsLinkage) {
4253ca95b02SDimitry Andric     // Record the linkage type of non-local symbols so they can be restored
4263ca95b02SDimitry Andric     // prior
4273ca95b02SDimitry Andric     // to module splitting.
4283ca95b02SDimitry Andric     auto RecordLinkage = [&](const GlobalValue &GV) {
4293ca95b02SDimitry Andric       if (!GV.hasAvailableExternallyLinkage() && !GV.hasLocalLinkage() &&
4303ca95b02SDimitry Andric           GV.hasName())
4313ca95b02SDimitry Andric         ExternalSymbols.insert(std::make_pair(GV.getName(), GV.getLinkage()));
4323ca95b02SDimitry Andric     };
4333ca95b02SDimitry Andric     for (auto &GV : *MergedModule)
4343ca95b02SDimitry Andric       RecordLinkage(GV);
4353ca95b02SDimitry Andric     for (auto &GV : MergedModule->globals())
4363ca95b02SDimitry Andric       RecordLinkage(GV);
4373ca95b02SDimitry Andric     for (auto &GV : MergedModule->aliases())
4383ca95b02SDimitry Andric       RecordLinkage(GV);
439f785676fSDimitry Andric   }
440f785676fSDimitry Andric 
4413ca95b02SDimitry Andric   // Update the llvm.compiler_used globals to force preserving libcalls and
4423ca95b02SDimitry Andric   // symbols referenced from asm
4433ca95b02SDimitry Andric   updateCompilerUsed(*MergedModule, *TargetMach, AsmUndefinedRefs);
444f785676fSDimitry Andric 
4453ca95b02SDimitry Andric   internalizeModule(*MergedModule, mustPreserveGV);
446f785676fSDimitry Andric 
447f785676fSDimitry Andric   ScopeRestrictionsDone = true;
448f785676fSDimitry Andric }
449f785676fSDimitry Andric 
4503ca95b02SDimitry Andric /// Restore original linkage for symbols that may have been internalized
4513ca95b02SDimitry Andric void LTOCodeGenerator::restoreLinkageForExternals() {
4523ca95b02SDimitry Andric   if (!ShouldInternalize || !ShouldRestoreGlobalsLinkage)
4533ca95b02SDimitry Andric     return;
4543ca95b02SDimitry Andric 
4553ca95b02SDimitry Andric   assert(ScopeRestrictionsDone &&
4563ca95b02SDimitry Andric          "Cannot externalize without internalization!");
4573ca95b02SDimitry Andric 
4583ca95b02SDimitry Andric   if (ExternalSymbols.empty())
4593ca95b02SDimitry Andric     return;
4603ca95b02SDimitry Andric 
4613ca95b02SDimitry Andric   auto externalize = [this](GlobalValue &GV) {
4623ca95b02SDimitry Andric     if (!GV.hasLocalLinkage() || !GV.hasName())
4633ca95b02SDimitry Andric       return;
4643ca95b02SDimitry Andric 
4653ca95b02SDimitry Andric     auto I = ExternalSymbols.find(GV.getName());
4663ca95b02SDimitry Andric     if (I == ExternalSymbols.end())
4673ca95b02SDimitry Andric       return;
4683ca95b02SDimitry Andric 
4693ca95b02SDimitry Andric     GV.setLinkage(I->second);
4703ca95b02SDimitry Andric   };
4713ca95b02SDimitry Andric 
4722cab237bSDimitry Andric   llvm::for_each(MergedModule->functions(), externalize);
4732cab237bSDimitry Andric   llvm::for_each(MergedModule->globals(), externalize);
4742cab237bSDimitry Andric   llvm::for_each(MergedModule->aliases(), externalize);
4753ca95b02SDimitry Andric }
4763ca95b02SDimitry Andric 
4773ca95b02SDimitry Andric void LTOCodeGenerator::verifyMergedModuleOnce() {
4783ca95b02SDimitry Andric   // Only run on the first call.
4793ca95b02SDimitry Andric   if (HasVerifiedInput)
4803ca95b02SDimitry Andric     return;
4813ca95b02SDimitry Andric   HasVerifiedInput = true;
4823ca95b02SDimitry Andric 
4833ca95b02SDimitry Andric   bool BrokenDebugInfo = false;
4842cab237bSDimitry Andric   if (verifyModule(*MergedModule, &dbgs(), &BrokenDebugInfo))
4853ca95b02SDimitry Andric     report_fatal_error("Broken module found, compilation aborted!");
4863ca95b02SDimitry Andric   if (BrokenDebugInfo) {
4873ca95b02SDimitry Andric     emitWarning("Invalid debug info found, debug info will be stripped");
4883ca95b02SDimitry Andric     StripDebugInfo(*MergedModule);
4893ca95b02SDimitry Andric   }
4903ca95b02SDimitry Andric }
4913ca95b02SDimitry Andric 
492d88c1a5aSDimitry Andric void LTOCodeGenerator::finishOptimizationRemarks() {
493d88c1a5aSDimitry Andric   if (DiagnosticOutputFile) {
494d88c1a5aSDimitry Andric     DiagnosticOutputFile->keep();
495d88c1a5aSDimitry Andric     // FIXME: LTOCodeGenerator dtor is not invoked on Darwin
496d88c1a5aSDimitry Andric     DiagnosticOutputFile->os().flush();
497d88c1a5aSDimitry Andric   }
498d88c1a5aSDimitry Andric }
499d88c1a5aSDimitry Andric 
500f785676fSDimitry Andric /// Optimize merged modules using various IPO passes
5017d523365SDimitry Andric bool LTOCodeGenerator::optimize(bool DisableVerify, bool DisableInline,
502f785676fSDimitry Andric                                 bool DisableGVNLoadPRE,
5037d523365SDimitry Andric                                 bool DisableVectorization) {
5047d523365SDimitry Andric   if (!this->determineTarget())
505f785676fSDimitry Andric     return false;
506f785676fSDimitry Andric 
5077a7e6055SDimitry Andric   auto DiagFileOrErr = lto::setupOptimizationRemarks(
5087a7e6055SDimitry Andric       Context, LTORemarksFilename, LTOPassRemarksWithHotness);
5097a7e6055SDimitry Andric   if (!DiagFileOrErr) {
5107a7e6055SDimitry Andric     errs() << "Error: " << toString(DiagFileOrErr.takeError()) << "\n";
5117a7e6055SDimitry Andric     report_fatal_error("Can't get an output file for the remarks");
5127a7e6055SDimitry Andric   }
5137a7e6055SDimitry Andric   DiagnosticOutputFile = std::move(*DiagFileOrErr);
514d88c1a5aSDimitry Andric 
5153ca95b02SDimitry Andric   // We always run the verifier once on the merged module, the `DisableVerify`
5163ca95b02SDimitry Andric   // parameter only applies to subsequent verify.
5173ca95b02SDimitry Andric   verifyMergedModuleOnce();
5183ca95b02SDimitry Andric 
519f785676fSDimitry Andric   // Mark which symbols can not be internalized
520f785676fSDimitry Andric   this->applyScopeRestrictions();
521f785676fSDimitry Andric 
522f785676fSDimitry Andric   // Instantiate the pass manager to organize the passes.
523ff0cc061SDimitry Andric   legacy::PassManager passes;
524f785676fSDimitry Andric 
525f785676fSDimitry Andric   // Add an appropriate DataLayout instance for this module...
5267d523365SDimitry Andric   MergedModule->setDataLayout(TargetMach->createDataLayout());
527ff0cc061SDimitry Andric 
528ff0cc061SDimitry Andric   passes.add(
529ff0cc061SDimitry Andric       createTargetTransformInfoWrapperPass(TargetMach->getTargetIRAnalysis()));
53091bc56edSDimitry Andric 
53139d628a0SDimitry Andric   Triple TargetTriple(TargetMach->getTargetTriple());
53239d628a0SDimitry Andric   PassManagerBuilder PMB;
53339d628a0SDimitry Andric   PMB.DisableGVNLoadPRE = DisableGVNLoadPRE;
53439d628a0SDimitry Andric   PMB.LoopVectorize = !DisableVectorization;
53539d628a0SDimitry Andric   PMB.SLPVectorize = !DisableVectorization;
53639d628a0SDimitry Andric   if (!DisableInline)
53739d628a0SDimitry Andric     PMB.Inliner = createFunctionInliningPass();
538ff0cc061SDimitry Andric   PMB.LibraryInfo = new TargetLibraryInfoImpl(TargetTriple);
5397a7e6055SDimitry Andric   if (Freestanding)
5407a7e6055SDimitry Andric     PMB.LibraryInfo->disableAllFunctions();
541ff0cc061SDimitry Andric   PMB.OptLevel = OptLevel;
5427d523365SDimitry Andric   PMB.VerifyInput = !DisableVerify;
5437d523365SDimitry Andric   PMB.VerifyOutput = !DisableVerify;
54491bc56edSDimitry Andric 
545ff0cc061SDimitry Andric   PMB.populateLTOPassManager(passes);
546f785676fSDimitry Andric 
547ff0cc061SDimitry Andric   // Run our queue of passes all at once now, efficiently.
5487d523365SDimitry Andric   passes.run(*MergedModule);
549f785676fSDimitry Andric 
550ff0cc061SDimitry Andric   return true;
551ff0cc061SDimitry Andric }
552f785676fSDimitry Andric 
5537d523365SDimitry Andric bool LTOCodeGenerator::compileOptimized(ArrayRef<raw_pwrite_stream *> Out) {
5547d523365SDimitry Andric   if (!this->determineTarget())
555ff0cc061SDimitry Andric     return false;
556ff0cc061SDimitry Andric 
5573ca95b02SDimitry Andric   // We always run the verifier once on the merged module.  If it has already
5583ca95b02SDimitry Andric   // been called in optimize(), this call will return early.
5593ca95b02SDimitry Andric   verifyMergedModuleOnce();
5603ca95b02SDimitry Andric 
5617d523365SDimitry Andric   legacy::PassManager preCodeGenPasses;
562f785676fSDimitry Andric 
563f785676fSDimitry Andric   // If the bitcode files contain ARC code and were compiled with optimization,
564f785676fSDimitry Andric   // the ObjCARCContractPass must be run, so do it unconditionally here.
5657d523365SDimitry Andric   preCodeGenPasses.add(createObjCARCContractPass());
5667d523365SDimitry Andric   preCodeGenPasses.run(*MergedModule);
567f785676fSDimitry Andric 
5683ca95b02SDimitry Andric   // Re-externalize globals that may have been internalized to increase scope
5693ca95b02SDimitry Andric   // for splitting
5703ca95b02SDimitry Andric   restoreLinkageForExternals();
5713ca95b02SDimitry Andric 
5727d523365SDimitry Andric   // Do code generation. We need to preserve the module in case the client calls
5737d523365SDimitry Andric   // writeMergedModules() after compilation, but we only need to allow this at
5747d523365SDimitry Andric   // parallelism level 1. This is achieved by having splitCodeGen return the
5757d523365SDimitry Andric   // original module at parallelism level 1 which we then assign back to
5767d523365SDimitry Andric   // MergedModule.
5773ca95b02SDimitry Andric   MergedModule = splitCodeGen(std::move(MergedModule), Out, {},
5783ca95b02SDimitry Andric                               [&]() { return createTargetMachine(); }, FileType,
5793ca95b02SDimitry Andric                               ShouldRestoreGlobalsLinkage);
5803ca95b02SDimitry Andric 
5813ca95b02SDimitry Andric   // If statistics were requested, print them out after codegen.
5823ca95b02SDimitry Andric   if (llvm::AreStatisticsEnabled())
5833ca95b02SDimitry Andric     llvm::PrintStatistics();
5845517e702SDimitry Andric   reportAndResetTimings();
585f785676fSDimitry Andric 
586d88c1a5aSDimitry Andric   finishOptimizationRemarks();
587d88c1a5aSDimitry Andric 
588f785676fSDimitry Andric   return true;
589f785676fSDimitry Andric }
590f785676fSDimitry Andric 
591f785676fSDimitry Andric /// setCodeGenDebugOptions - Set codegen debugging options to aid in debugging
592f785676fSDimitry Andric /// LTO problems.
593d88c1a5aSDimitry Andric void LTOCodeGenerator::setCodeGenDebugOptions(StringRef Options) {
5947d523365SDimitry Andric   for (std::pair<StringRef, StringRef> o = getToken(Options); !o.first.empty();
5957d523365SDimitry Andric        o = getToken(o.second))
5967d523365SDimitry Andric     CodegenOptions.push_back(o.first);
597f785676fSDimitry Andric }
598f785676fSDimitry Andric 
599f785676fSDimitry Andric void LTOCodeGenerator::parseCodeGenDebugOptions() {
600f785676fSDimitry Andric   // if options were requested, set them
6017d523365SDimitry Andric   if (!CodegenOptions.empty()) {
6027d523365SDimitry Andric     // ParseCommandLineOptions() expects argv[0] to be program name.
6037d523365SDimitry Andric     std::vector<const char *> CodegenArgv(1, "libLLVMLTO");
6047d523365SDimitry Andric     for (std::string &Arg : CodegenOptions)
6057d523365SDimitry Andric       CodegenArgv.push_back(Arg.c_str());
6067d523365SDimitry Andric     cl::ParseCommandLineOptions(CodegenArgv.size(), CodegenArgv.data());
6077d523365SDimitry Andric   }
608f785676fSDimitry Andric }
60991bc56edSDimitry Andric 
61091bc56edSDimitry Andric 
6112cab237bSDimitry Andric void LTOCodeGenerator::DiagnosticHandler(const DiagnosticInfo &DI) {
61291bc56edSDimitry Andric   // Map the LLVM internal diagnostic severity to the LTO diagnostic severity.
61391bc56edSDimitry Andric   lto_codegen_diagnostic_severity_t Severity;
61491bc56edSDimitry Andric   switch (DI.getSeverity()) {
61591bc56edSDimitry Andric   case DS_Error:
61691bc56edSDimitry Andric     Severity = LTO_DS_ERROR;
61791bc56edSDimitry Andric     break;
61891bc56edSDimitry Andric   case DS_Warning:
61991bc56edSDimitry Andric     Severity = LTO_DS_WARNING;
62091bc56edSDimitry Andric     break;
62191bc56edSDimitry Andric   case DS_Remark:
62291bc56edSDimitry Andric     Severity = LTO_DS_REMARK;
62391bc56edSDimitry Andric     break;
62491bc56edSDimitry Andric   case DS_Note:
62591bc56edSDimitry Andric     Severity = LTO_DS_NOTE;
62691bc56edSDimitry Andric     break;
62791bc56edSDimitry Andric   }
62891bc56edSDimitry Andric   // Create the string that will be reported to the external diagnostic handler.
62991bc56edSDimitry Andric   std::string MsgStorage;
63091bc56edSDimitry Andric   raw_string_ostream Stream(MsgStorage);
63191bc56edSDimitry Andric   DiagnosticPrinterRawOStream DP(Stream);
63291bc56edSDimitry Andric   DI.print(DP);
63391bc56edSDimitry Andric   Stream.flush();
63491bc56edSDimitry Andric 
63591bc56edSDimitry Andric   // If this method has been called it means someone has set up an external
63691bc56edSDimitry Andric   // diagnostic handler. Assert on that.
63791bc56edSDimitry Andric   assert(DiagHandler && "Invalid diagnostic handler");
63891bc56edSDimitry Andric   (*DiagHandler)(Severity, MsgStorage.c_str(), DiagContext);
63991bc56edSDimitry Andric }
64091bc56edSDimitry Andric 
6412cab237bSDimitry Andric namespace {
6422cab237bSDimitry Andric struct LTODiagnosticHandler : public DiagnosticHandler {
6432cab237bSDimitry Andric   LTOCodeGenerator *CodeGenerator;
6442cab237bSDimitry Andric   LTODiagnosticHandler(LTOCodeGenerator *CodeGenPtr)
6452cab237bSDimitry Andric       : CodeGenerator(CodeGenPtr) {}
6462cab237bSDimitry Andric   bool handleDiagnostics(const DiagnosticInfo &DI) override {
6472cab237bSDimitry Andric     CodeGenerator->DiagnosticHandler(DI);
6482cab237bSDimitry Andric     return true;
6492cab237bSDimitry Andric   }
6502cab237bSDimitry Andric };
6512cab237bSDimitry Andric }
6522cab237bSDimitry Andric 
65391bc56edSDimitry Andric void
65491bc56edSDimitry Andric LTOCodeGenerator::setDiagnosticHandler(lto_diagnostic_handler_t DiagHandler,
65591bc56edSDimitry Andric                                        void *Ctxt) {
65691bc56edSDimitry Andric   this->DiagHandler = DiagHandler;
65791bc56edSDimitry Andric   this->DiagContext = Ctxt;
65891bc56edSDimitry Andric   if (!DiagHandler)
6592cab237bSDimitry Andric     return Context.setDiagnosticHandler(nullptr);
66091bc56edSDimitry Andric   // Register the LTOCodeGenerator stub in the LLVMContext to forward the
66191bc56edSDimitry Andric   // diagnostic to the external DiagHandler.
6622cab237bSDimitry Andric   Context.setDiagnosticHandler(llvm::make_unique<LTODiagnosticHandler>(this),
6632cab237bSDimitry Andric                                true);
66491bc56edSDimitry Andric }
6657d523365SDimitry Andric 
6667d523365SDimitry Andric namespace {
6677d523365SDimitry Andric class LTODiagnosticInfo : public DiagnosticInfo {
6687d523365SDimitry Andric   const Twine &Msg;
6697d523365SDimitry Andric public:
6707d523365SDimitry Andric   LTODiagnosticInfo(const Twine &DiagMsg, DiagnosticSeverity Severity=DS_Error)
6717d523365SDimitry Andric       : DiagnosticInfo(DK_Linker, Severity), Msg(DiagMsg) {}
6727d523365SDimitry Andric   void print(DiagnosticPrinter &DP) const override { DP << Msg; }
6737d523365SDimitry Andric };
6747d523365SDimitry Andric }
6757d523365SDimitry Andric 
6767d523365SDimitry Andric void LTOCodeGenerator::emitError(const std::string &ErrMsg) {
6777d523365SDimitry Andric   if (DiagHandler)
6787d523365SDimitry Andric     (*DiagHandler)(LTO_DS_ERROR, ErrMsg.c_str(), DiagContext);
6797d523365SDimitry Andric   else
6807d523365SDimitry Andric     Context.diagnose(LTODiagnosticInfo(ErrMsg));
6817d523365SDimitry Andric }
6823ca95b02SDimitry Andric 
6833ca95b02SDimitry Andric void LTOCodeGenerator::emitWarning(const std::string &ErrMsg) {
6843ca95b02SDimitry Andric   if (DiagHandler)
6853ca95b02SDimitry Andric     (*DiagHandler)(LTO_DS_WARNING, ErrMsg.c_str(), DiagContext);
6863ca95b02SDimitry Andric   else
6873ca95b02SDimitry Andric     Context.diagnose(LTODiagnosticInfo(ErrMsg, DS_Warning));
6883ca95b02SDimitry Andric }
689