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"
22f785676fSDimitry Andric #include "llvm/Bitcode/ReaderWriter.h"
237d523365SDimitry Andric #include "llvm/CodeGen/ParallelCG.h"
24f785676fSDimitry Andric #include "llvm/CodeGen/RuntimeLibcalls.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"
383ca95b02SDimitry Andric #include "llvm/LTO/legacy/LTOModule.h"
393ca95b02SDimitry Andric #include "llvm/LTO/legacy/UpdateCompilerUsed.h"
4091bc56edSDimitry Andric #include "llvm/Linker/Linker.h"
41f785676fSDimitry Andric #include "llvm/MC/MCAsmInfo.h"
42f785676fSDimitry Andric #include "llvm/MC/MCContext.h"
43f785676fSDimitry Andric #include "llvm/MC/SubtargetFeature.h"
44f785676fSDimitry Andric #include "llvm/Support/CommandLine.h"
45f785676fSDimitry Andric #include "llvm/Support/FileSystem.h"
46f785676fSDimitry Andric #include "llvm/Support/Host.h"
47f785676fSDimitry Andric #include "llvm/Support/MemoryBuffer.h"
48f785676fSDimitry Andric #include "llvm/Support/Signals.h"
49f785676fSDimitry Andric #include "llvm/Support/TargetRegistry.h"
50f785676fSDimitry Andric #include "llvm/Support/TargetSelect.h"
51f785676fSDimitry Andric #include "llvm/Support/ToolOutputFile.h"
5291bc56edSDimitry Andric #include "llvm/Support/raw_ostream.h"
53f785676fSDimitry Andric #include "llvm/Target/TargetLowering.h"
54f785676fSDimitry Andric #include "llvm/Target/TargetOptions.h"
55f785676fSDimitry Andric #include "llvm/Target/TargetRegisterInfo.h"
5639d628a0SDimitry Andric #include "llvm/Target/TargetSubtargetInfo.h"
57f785676fSDimitry Andric #include "llvm/Transforms/IPO.h"
583ca95b02SDimitry Andric #include "llvm/Transforms/IPO/Internalize.h"
59f785676fSDimitry Andric #include "llvm/Transforms/IPO/PassManagerBuilder.h"
60f785676fSDimitry Andric #include "llvm/Transforms/ObjCARC.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 
833ca95b02SDimitry Andric cl::opt<bool> LTOStripInvalidDebugInfo(
843ca95b02SDimitry Andric     "lto-strip-invalid-debug-info",
853ca95b02SDimitry Andric     cl::desc("Strip invalid debug info metadata during LTO instead of aborting."),
863ca95b02SDimitry Andric #ifdef NDEBUG
873ca95b02SDimitry Andric     cl::init(true),
883ca95b02SDimitry Andric #else
893ca95b02SDimitry Andric     cl::init(false),
903ca95b02SDimitry Andric #endif
913ca95b02SDimitry 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 
1337d523365SDimitry Andric bool LTOCodeGenerator::addModule(LTOModule *Mod) {
1347d523365SDimitry Andric   assert(&Mod->getModule().getContext() == &Context &&
13539d628a0SDimitry Andric          "Expected module in same context");
13639d628a0SDimitry Andric 
1377d523365SDimitry Andric   bool ret = TheLinker->linkInModule(Mod->takeModule());
138f785676fSDimitry Andric 
1397d523365SDimitry Andric   const std::vector<const char *> &undefs = Mod->getAsmUndefinedRefs();
140f785676fSDimitry Andric   for (int i = 0, e = undefs.size(); i != e; ++i)
141f785676fSDimitry Andric     AsmUndefinedRefs[undefs[i]] = 1;
142f785676fSDimitry Andric 
1433ca95b02SDimitry Andric   // We've just changed the input, so let's make sure we verify it.
1443ca95b02SDimitry Andric   HasVerifiedInput = false;
1453ca95b02SDimitry Andric 
146f785676fSDimitry Andric   return !ret;
147f785676fSDimitry Andric }
148f785676fSDimitry Andric 
1497d523365SDimitry Andric void LTOCodeGenerator::setModule(std::unique_ptr<LTOModule> Mod) {
150ff0cc061SDimitry Andric   assert(&Mod->getModule().getContext() == &Context &&
151ff0cc061SDimitry Andric          "Expected module in same context");
152ff0cc061SDimitry Andric 
153ff0cc061SDimitry Andric   AsmUndefinedRefs.clear();
154ff0cc061SDimitry Andric 
1557d523365SDimitry Andric   MergedModule = Mod->takeModule();
1567d523365SDimitry Andric   TheLinker = make_unique<Linker>(*MergedModule);
157ff0cc061SDimitry Andric 
158ff0cc061SDimitry Andric   const std::vector<const char*> &Undefs = Mod->getAsmUndefinedRefs();
159ff0cc061SDimitry Andric   for (int I = 0, E = Undefs.size(); I != E; ++I)
160ff0cc061SDimitry Andric     AsmUndefinedRefs[Undefs[I]] = 1;
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;
188ff0cc061SDimitry Andric     break;
189ff0cc061SDimitry Andric   case 1:
190ff0cc061SDimitry Andric     CGOptLevel = CodeGenOpt::Less;
191ff0cc061SDimitry Andric     break;
192ff0cc061SDimitry Andric   case 2:
193ff0cc061SDimitry Andric     CGOptLevel = CodeGenOpt::Default;
194ff0cc061SDimitry Andric     break;
195ff0cc061SDimitry Andric   case 3:
196ff0cc061SDimitry Andric     CGOptLevel = CodeGenOpt::Aggressive;
197ff0cc061SDimitry Andric     break;
198ff0cc061SDimitry Andric   }
1997d523365SDimitry Andric }
200ff0cc061SDimitry Andric 
2017d523365SDimitry Andric bool LTOCodeGenerator::writeMergedModules(const char *Path) {
2027d523365SDimitry Andric   if (!determineTarget())
2037d523365SDimitry Andric     return false;
2047d523365SDimitry Andric 
2053ca95b02SDimitry Andric   // We always run the verifier once on the merged module.
2063ca95b02SDimitry Andric   verifyMergedModuleOnce();
2073ca95b02SDimitry Andric 
2087d523365SDimitry Andric   // mark which symbols can not be internalized
2097d523365SDimitry Andric   applyScopeRestrictions();
2107d523365SDimitry Andric 
2117d523365SDimitry Andric   // create output file
2127d523365SDimitry Andric   std::error_code EC;
2137d523365SDimitry Andric   tool_output_file Out(Path, EC, sys::fs::F_None);
2147d523365SDimitry Andric   if (EC) {
2157d523365SDimitry Andric     std::string ErrMsg = "could not open bitcode file for writing: ";
2167d523365SDimitry Andric     ErrMsg += Path;
2177d523365SDimitry Andric     emitError(ErrMsg);
2187d523365SDimitry Andric     return false;
2197d523365SDimitry Andric   }
2207d523365SDimitry Andric 
2217d523365SDimitry Andric   // write bitcode to it
2227d523365SDimitry Andric   WriteBitcodeToFile(MergedModule.get(), Out.os(), ShouldEmbedUselists);
2237d523365SDimitry Andric   Out.os().close();
2247d523365SDimitry Andric 
2257d523365SDimitry Andric   if (Out.os().has_error()) {
2267d523365SDimitry Andric     std::string ErrMsg = "could not write bitcode file: ";
2277d523365SDimitry Andric     ErrMsg += Path;
2287d523365SDimitry Andric     emitError(ErrMsg);
2297d523365SDimitry Andric     Out.os().clear_error();
2307d523365SDimitry Andric     return false;
2317d523365SDimitry Andric   }
2327d523365SDimitry Andric 
2337d523365SDimitry Andric   Out.keep();
2347d523365SDimitry Andric   return true;
2357d523365SDimitry Andric }
2367d523365SDimitry Andric 
2377d523365SDimitry Andric bool LTOCodeGenerator::compileOptimizedToFile(const char **Name) {
2387d523365SDimitry Andric   // make unique temp output file to put generated code
2397d523365SDimitry Andric   SmallString<128> Filename;
2407d523365SDimitry Andric   int FD;
2417d523365SDimitry Andric 
2427d523365SDimitry Andric   const char *Extension =
2437d523365SDimitry Andric       (FileType == TargetMachine::CGFT_AssemblyFile ? "s" : "o");
2447d523365SDimitry Andric 
2457d523365SDimitry Andric   std::error_code EC =
2467d523365SDimitry Andric       sys::fs::createTemporaryFile("lto-llvm", Extension, FD, Filename);
2477d523365SDimitry Andric   if (EC) {
2487d523365SDimitry Andric     emitError(EC.message());
2497d523365SDimitry Andric     return false;
2507d523365SDimitry Andric   }
2517d523365SDimitry Andric 
2527d523365SDimitry Andric   // generate object file
2537d523365SDimitry Andric   tool_output_file objFile(Filename.c_str(), FD);
2547d523365SDimitry Andric 
2557d523365SDimitry Andric   bool genResult = compileOptimized(&objFile.os());
2567d523365SDimitry Andric   objFile.os().close();
2577d523365SDimitry Andric   if (objFile.os().has_error()) {
2587d523365SDimitry Andric     objFile.os().clear_error();
2597d523365SDimitry Andric     sys::fs::remove(Twine(Filename));
2607d523365SDimitry Andric     return false;
2617d523365SDimitry Andric   }
2627d523365SDimitry Andric 
2637d523365SDimitry Andric   objFile.keep();
2647d523365SDimitry Andric   if (!genResult) {
2657d523365SDimitry Andric     sys::fs::remove(Twine(Filename));
2667d523365SDimitry Andric     return false;
2677d523365SDimitry Andric   }
2687d523365SDimitry Andric 
2697d523365SDimitry Andric   NativeObjectPath = Filename.c_str();
2707d523365SDimitry Andric   *Name = NativeObjectPath.c_str();
2717d523365SDimitry Andric   return true;
2727d523365SDimitry Andric }
2737d523365SDimitry Andric 
2747d523365SDimitry Andric std::unique_ptr<MemoryBuffer>
2757d523365SDimitry Andric LTOCodeGenerator::compileOptimized() {
2767d523365SDimitry Andric   const char *name;
2777d523365SDimitry Andric   if (!compileOptimizedToFile(&name))
2787d523365SDimitry Andric     return nullptr;
2797d523365SDimitry Andric 
2807d523365SDimitry Andric   // read .o file into memory buffer
2817d523365SDimitry Andric   ErrorOr<std::unique_ptr<MemoryBuffer>> BufferOrErr =
2827d523365SDimitry Andric       MemoryBuffer::getFile(name, -1, false);
2837d523365SDimitry Andric   if (std::error_code EC = BufferOrErr.getError()) {
2847d523365SDimitry Andric     emitError(EC.message());
2857d523365SDimitry Andric     sys::fs::remove(NativeObjectPath);
2867d523365SDimitry Andric     return nullptr;
2877d523365SDimitry Andric   }
2887d523365SDimitry Andric 
2897d523365SDimitry Andric   // remove temp files
2907d523365SDimitry Andric   sys::fs::remove(NativeObjectPath);
2917d523365SDimitry Andric 
2927d523365SDimitry Andric   return std::move(*BufferOrErr);
2937d523365SDimitry Andric }
2947d523365SDimitry Andric 
2957d523365SDimitry Andric bool LTOCodeGenerator::compile_to_file(const char **Name, bool DisableVerify,
2967d523365SDimitry Andric                                        bool DisableInline,
2977d523365SDimitry Andric                                        bool DisableGVNLoadPRE,
2987d523365SDimitry Andric                                        bool DisableVectorization) {
2997d523365SDimitry Andric   if (!optimize(DisableVerify, DisableInline, DisableGVNLoadPRE,
3007d523365SDimitry Andric                 DisableVectorization))
3017d523365SDimitry Andric     return false;
3027d523365SDimitry Andric 
3037d523365SDimitry Andric   return compileOptimizedToFile(Name);
3047d523365SDimitry Andric }
3057d523365SDimitry Andric 
3067d523365SDimitry Andric std::unique_ptr<MemoryBuffer>
3077d523365SDimitry Andric LTOCodeGenerator::compile(bool DisableVerify, bool DisableInline,
3087d523365SDimitry Andric                           bool DisableGVNLoadPRE, bool DisableVectorization) {
3097d523365SDimitry Andric   if (!optimize(DisableVerify, DisableInline, DisableGVNLoadPRE,
3107d523365SDimitry Andric                 DisableVectorization))
3117d523365SDimitry Andric     return nullptr;
3127d523365SDimitry Andric 
3137d523365SDimitry Andric   return compileOptimized();
3147d523365SDimitry Andric }
3157d523365SDimitry Andric 
3167d523365SDimitry Andric bool LTOCodeGenerator::determineTarget() {
3177d523365SDimitry Andric   if (TargetMach)
3187d523365SDimitry Andric     return true;
3197d523365SDimitry Andric 
3203ca95b02SDimitry Andric   TripleStr = MergedModule->getTargetTriple();
3217d523365SDimitry Andric   if (TripleStr.empty()) {
3227d523365SDimitry Andric     TripleStr = sys::getDefaultTargetTriple();
3237d523365SDimitry Andric     MergedModule->setTargetTriple(TripleStr);
3247d523365SDimitry Andric   }
3257d523365SDimitry Andric   llvm::Triple Triple(TripleStr);
3267d523365SDimitry Andric 
3277d523365SDimitry Andric   // create target machine from info for merged modules
3287d523365SDimitry Andric   std::string ErrMsg;
3293ca95b02SDimitry Andric   MArch = TargetRegistry::lookupTarget(TripleStr, ErrMsg);
3303ca95b02SDimitry Andric   if (!MArch) {
3317d523365SDimitry Andric     emitError(ErrMsg);
3327d523365SDimitry Andric     return false;
3337d523365SDimitry Andric   }
3347d523365SDimitry Andric 
3357d523365SDimitry Andric   // Construct LTOModule, hand over ownership of module and target. Use MAttr as
3367d523365SDimitry Andric   // the default set of features.
3377d523365SDimitry Andric   SubtargetFeatures Features(MAttr);
3387d523365SDimitry Andric   Features.getDefaultSubtargetFeatures(Triple);
3397d523365SDimitry Andric   FeatureStr = Features.getString();
3407d523365SDimitry Andric   // Set a default CPU for Darwin triples.
3417d523365SDimitry Andric   if (MCpu.empty() && Triple.isOSDarwin()) {
3427d523365SDimitry Andric     if (Triple.getArch() == llvm::Triple::x86_64)
3437d523365SDimitry Andric       MCpu = "core2";
3447d523365SDimitry Andric     else if (Triple.getArch() == llvm::Triple::x86)
3457d523365SDimitry Andric       MCpu = "yonah";
3467d523365SDimitry Andric     else if (Triple.getArch() == llvm::Triple::aarch64)
3477d523365SDimitry Andric       MCpu = "cyclone";
3487d523365SDimitry Andric   }
3497d523365SDimitry Andric 
3503ca95b02SDimitry Andric   TargetMach = createTargetMachine();
351f785676fSDimitry Andric   return true;
352f785676fSDimitry Andric }
353f785676fSDimitry Andric 
3543ca95b02SDimitry Andric std::unique_ptr<TargetMachine> LTOCodeGenerator::createTargetMachine() {
3553ca95b02SDimitry Andric   return std::unique_ptr<TargetMachine>(
3563ca95b02SDimitry Andric       MArch->createTargetMachine(TripleStr, MCpu, FeatureStr, Options,
3573ca95b02SDimitry Andric                                  RelocModel, CodeModel::Default, CGOptLevel));
358f785676fSDimitry Andric }
359f785676fSDimitry Andric 
3603ca95b02SDimitry Andric // If a linkonce global is present in the MustPreserveSymbols, we need to make
3613ca95b02SDimitry Andric // sure we honor this. To force the compiler to not drop it, we add it to the
3623ca95b02SDimitry Andric // "llvm.compiler.used" global.
3633ca95b02SDimitry Andric void LTOCodeGenerator::preserveDiscardableGVs(
3643ca95b02SDimitry Andric     Module &TheModule,
3653ca95b02SDimitry Andric     llvm::function_ref<bool(const GlobalValue &)> mustPreserveGV) {
3663ca95b02SDimitry Andric   SetVector<Constant *> UsedValuesSet;
3673ca95b02SDimitry Andric   if (GlobalVariable *LLVMUsed =
3683ca95b02SDimitry Andric           TheModule.getGlobalVariable("llvm.compiler.used")) {
369f785676fSDimitry Andric     ConstantArray *Inits = cast<ConstantArray>(LLVMUsed->getInitializer());
3703ca95b02SDimitry Andric     for (auto &V : Inits->operands())
3713ca95b02SDimitry Andric       UsedValuesSet.insert(cast<Constant>(&V));
3723ca95b02SDimitry Andric     LLVMUsed->eraseFromParent();
373f785676fSDimitry Andric   }
3743ca95b02SDimitry Andric   llvm::Type *i8PTy = llvm::Type::getInt8PtrTy(TheModule.getContext());
3753ca95b02SDimitry Andric   auto mayPreserveGlobal = [&](GlobalValue &GV) {
3763ca95b02SDimitry Andric     if (!GV.isDiscardableIfUnused() || GV.isDeclaration())
3773ca95b02SDimitry Andric       return;
3783ca95b02SDimitry Andric     if (!mustPreserveGV(GV))
3793ca95b02SDimitry Andric       return;
3803ca95b02SDimitry Andric     if (GV.hasAvailableExternallyLinkage()) {
3813ca95b02SDimitry Andric       emitWarning(
3823ca95b02SDimitry Andric           (Twine("Linker asked to preserve available_externally global: '") +
3833ca95b02SDimitry Andric            GV.getName() + "'").str());
3843ca95b02SDimitry Andric       return;
385f785676fSDimitry Andric     }
3863ca95b02SDimitry Andric     if (GV.hasInternalLinkage()) {
3873ca95b02SDimitry Andric       emitWarning((Twine("Linker asked to preserve internal global: '") +
3883ca95b02SDimitry Andric                    GV.getName() + "'").str());
3893ca95b02SDimitry Andric       return;
390ff0cc061SDimitry Andric     }
3913ca95b02SDimitry Andric     UsedValuesSet.insert(ConstantExpr::getBitCast(&GV, i8PTy));
3923ca95b02SDimitry Andric   };
3933ca95b02SDimitry Andric   for (auto &GV : TheModule)
3943ca95b02SDimitry Andric     mayPreserveGlobal(GV);
3953ca95b02SDimitry Andric   for (auto &GV : TheModule.globals())
3963ca95b02SDimitry Andric     mayPreserveGlobal(GV);
3973ca95b02SDimitry Andric   for (auto &GV : TheModule.aliases())
3983ca95b02SDimitry Andric     mayPreserveGlobal(GV);
399f785676fSDimitry Andric 
4003ca95b02SDimitry Andric   if (UsedValuesSet.empty())
4013ca95b02SDimitry Andric     return;
4023ca95b02SDimitry Andric 
4033ca95b02SDimitry Andric   llvm::ArrayType *ATy = llvm::ArrayType::get(i8PTy, UsedValuesSet.size());
4043ca95b02SDimitry Andric   auto *LLVMUsed = new llvm::GlobalVariable(
4053ca95b02SDimitry Andric       TheModule, ATy, false, llvm::GlobalValue::AppendingLinkage,
4063ca95b02SDimitry Andric       llvm::ConstantArray::get(ATy, UsedValuesSet.getArrayRef()),
4073ca95b02SDimitry Andric       "llvm.compiler.used");
4083ca95b02SDimitry Andric   LLVMUsed->setSection("llvm.metadata");
409f785676fSDimitry Andric }
410f785676fSDimitry Andric 
411f785676fSDimitry Andric void LTOCodeGenerator::applyScopeRestrictions() {
4123ca95b02SDimitry Andric   if (ScopeRestrictionsDone)
413f785676fSDimitry Andric     return;
414f785676fSDimitry Andric 
4153ca95b02SDimitry Andric   // Declare a callback for the internalize pass that will ask for every
4163ca95b02SDimitry Andric   // candidate GlobalValue if it can be internalized or not.
4173ca95b02SDimitry Andric   SmallString<64> MangledName;
4183ca95b02SDimitry Andric   auto mustPreserveGV = [&](const GlobalValue &GV) -> bool {
4193ca95b02SDimitry Andric     // Unnamed globals can't be mangled, but they can't be preserved either.
4203ca95b02SDimitry Andric     if (!GV.hasName())
4213ca95b02SDimitry Andric       return false;
422f785676fSDimitry Andric 
4233ca95b02SDimitry Andric     // Need to mangle the GV as the "MustPreserveSymbols" StringSet is filled
4243ca95b02SDimitry Andric     // with the linker supplied name, which on Darwin includes a leading
4253ca95b02SDimitry Andric     // underscore.
4263ca95b02SDimitry Andric     MangledName.clear();
4273ca95b02SDimitry Andric     MangledName.reserve(GV.getName().size() + 1);
4283ca95b02SDimitry Andric     Mangler::getNameWithPrefix(MangledName, GV.getName(),
4293ca95b02SDimitry Andric                                MergedModule->getDataLayout());
4303ca95b02SDimitry Andric     return MustPreserveSymbols.count(MangledName);
4313ca95b02SDimitry Andric   };
432ff0cc061SDimitry Andric 
4333ca95b02SDimitry Andric   // Preserve linkonce value on linker request
4343ca95b02SDimitry Andric   preserveDiscardableGVs(*MergedModule, mustPreserveGV);
435f785676fSDimitry Andric 
4363ca95b02SDimitry Andric   if (!ShouldInternalize)
4373ca95b02SDimitry Andric     return;
438f785676fSDimitry Andric 
4393ca95b02SDimitry Andric   if (ShouldRestoreGlobalsLinkage) {
4403ca95b02SDimitry Andric     // Record the linkage type of non-local symbols so they can be restored
4413ca95b02SDimitry Andric     // prior
4423ca95b02SDimitry Andric     // to module splitting.
4433ca95b02SDimitry Andric     auto RecordLinkage = [&](const GlobalValue &GV) {
4443ca95b02SDimitry Andric       if (!GV.hasAvailableExternallyLinkage() && !GV.hasLocalLinkage() &&
4453ca95b02SDimitry Andric           GV.hasName())
4463ca95b02SDimitry Andric         ExternalSymbols.insert(std::make_pair(GV.getName(), GV.getLinkage()));
4473ca95b02SDimitry Andric     };
4483ca95b02SDimitry Andric     for (auto &GV : *MergedModule)
4493ca95b02SDimitry Andric       RecordLinkage(GV);
4503ca95b02SDimitry Andric     for (auto &GV : MergedModule->globals())
4513ca95b02SDimitry Andric       RecordLinkage(GV);
4523ca95b02SDimitry Andric     for (auto &GV : MergedModule->aliases())
4533ca95b02SDimitry Andric       RecordLinkage(GV);
454f785676fSDimitry Andric   }
455f785676fSDimitry Andric 
4563ca95b02SDimitry Andric   // Update the llvm.compiler_used globals to force preserving libcalls and
4573ca95b02SDimitry Andric   // symbols referenced from asm
4583ca95b02SDimitry Andric   updateCompilerUsed(*MergedModule, *TargetMach, AsmUndefinedRefs);
459f785676fSDimitry Andric 
4603ca95b02SDimitry Andric   internalizeModule(*MergedModule, mustPreserveGV);
461f785676fSDimitry Andric 
462f785676fSDimitry Andric   ScopeRestrictionsDone = true;
463f785676fSDimitry Andric }
464f785676fSDimitry Andric 
4653ca95b02SDimitry Andric /// Restore original linkage for symbols that may have been internalized
4663ca95b02SDimitry Andric void LTOCodeGenerator::restoreLinkageForExternals() {
4673ca95b02SDimitry Andric   if (!ShouldInternalize || !ShouldRestoreGlobalsLinkage)
4683ca95b02SDimitry Andric     return;
4693ca95b02SDimitry Andric 
4703ca95b02SDimitry Andric   assert(ScopeRestrictionsDone &&
4713ca95b02SDimitry Andric          "Cannot externalize without internalization!");
4723ca95b02SDimitry Andric 
4733ca95b02SDimitry Andric   if (ExternalSymbols.empty())
4743ca95b02SDimitry Andric     return;
4753ca95b02SDimitry Andric 
4763ca95b02SDimitry Andric   auto externalize = [this](GlobalValue &GV) {
4773ca95b02SDimitry Andric     if (!GV.hasLocalLinkage() || !GV.hasName())
4783ca95b02SDimitry Andric       return;
4793ca95b02SDimitry Andric 
4803ca95b02SDimitry Andric     auto I = ExternalSymbols.find(GV.getName());
4813ca95b02SDimitry Andric     if (I == ExternalSymbols.end())
4823ca95b02SDimitry Andric       return;
4833ca95b02SDimitry Andric 
4843ca95b02SDimitry Andric     GV.setLinkage(I->second);
4853ca95b02SDimitry Andric   };
4863ca95b02SDimitry Andric 
4873ca95b02SDimitry Andric   std::for_each(MergedModule->begin(), MergedModule->end(), externalize);
4883ca95b02SDimitry Andric   std::for_each(MergedModule->global_begin(), MergedModule->global_end(),
4893ca95b02SDimitry Andric                 externalize);
4903ca95b02SDimitry Andric   std::for_each(MergedModule->alias_begin(), MergedModule->alias_end(),
4913ca95b02SDimitry Andric                 externalize);
4923ca95b02SDimitry Andric }
4933ca95b02SDimitry Andric 
4943ca95b02SDimitry Andric void LTOCodeGenerator::verifyMergedModuleOnce() {
4953ca95b02SDimitry Andric   // Only run on the first call.
4963ca95b02SDimitry Andric   if (HasVerifiedInput)
4973ca95b02SDimitry Andric     return;
4983ca95b02SDimitry Andric   HasVerifiedInput = true;
4993ca95b02SDimitry Andric 
5003ca95b02SDimitry Andric   if (LTOStripInvalidDebugInfo) {
5013ca95b02SDimitry Andric     bool BrokenDebugInfo = false;
5023ca95b02SDimitry Andric     if (verifyModule(*MergedModule, &dbgs(), &BrokenDebugInfo))
5033ca95b02SDimitry Andric       report_fatal_error("Broken module found, compilation aborted!");
5043ca95b02SDimitry Andric     if (BrokenDebugInfo) {
5053ca95b02SDimitry Andric       emitWarning("Invalid debug info found, debug info will be stripped");
5063ca95b02SDimitry Andric       StripDebugInfo(*MergedModule);
5073ca95b02SDimitry Andric     }
5083ca95b02SDimitry Andric   }
5093ca95b02SDimitry Andric   if (verifyModule(*MergedModule, &dbgs()))
5103ca95b02SDimitry Andric     report_fatal_error("Broken module found, compilation aborted!");
5113ca95b02SDimitry Andric }
5123ca95b02SDimitry Andric 
513f785676fSDimitry Andric /// Optimize merged modules using various IPO passes
5147d523365SDimitry Andric bool LTOCodeGenerator::optimize(bool DisableVerify, bool DisableInline,
515f785676fSDimitry Andric                                 bool DisableGVNLoadPRE,
5167d523365SDimitry Andric                                 bool DisableVectorization) {
5177d523365SDimitry Andric   if (!this->determineTarget())
518f785676fSDimitry Andric     return false;
519f785676fSDimitry Andric 
5203ca95b02SDimitry Andric   // We always run the verifier once on the merged module, the `DisableVerify`
5213ca95b02SDimitry Andric   // parameter only applies to subsequent verify.
5223ca95b02SDimitry Andric   verifyMergedModuleOnce();
5233ca95b02SDimitry Andric 
524f785676fSDimitry Andric   // Mark which symbols can not be internalized
525f785676fSDimitry Andric   this->applyScopeRestrictions();
526f785676fSDimitry Andric 
527f785676fSDimitry Andric   // Instantiate the pass manager to organize the passes.
528ff0cc061SDimitry Andric   legacy::PassManager passes;
529f785676fSDimitry Andric 
530f785676fSDimitry Andric   // Add an appropriate DataLayout instance for this module...
5317d523365SDimitry Andric   MergedModule->setDataLayout(TargetMach->createDataLayout());
532ff0cc061SDimitry Andric 
533ff0cc061SDimitry Andric   passes.add(
534ff0cc061SDimitry Andric       createTargetTransformInfoWrapperPass(TargetMach->getTargetIRAnalysis()));
53591bc56edSDimitry Andric 
53639d628a0SDimitry Andric   Triple TargetTriple(TargetMach->getTargetTriple());
53739d628a0SDimitry Andric   PassManagerBuilder PMB;
53839d628a0SDimitry Andric   PMB.DisableGVNLoadPRE = DisableGVNLoadPRE;
53939d628a0SDimitry Andric   PMB.LoopVectorize = !DisableVectorization;
54039d628a0SDimitry Andric   PMB.SLPVectorize = !DisableVectorization;
54139d628a0SDimitry Andric   if (!DisableInline)
54239d628a0SDimitry Andric     PMB.Inliner = createFunctionInliningPass();
543ff0cc061SDimitry Andric   PMB.LibraryInfo = new TargetLibraryInfoImpl(TargetTriple);
544ff0cc061SDimitry Andric   PMB.OptLevel = OptLevel;
5457d523365SDimitry Andric   PMB.VerifyInput = !DisableVerify;
5467d523365SDimitry Andric   PMB.VerifyOutput = !DisableVerify;
54791bc56edSDimitry Andric 
548ff0cc061SDimitry Andric   PMB.populateLTOPassManager(passes);
549f785676fSDimitry Andric 
550ff0cc061SDimitry Andric   // Run our queue of passes all at once now, efficiently.
5517d523365SDimitry Andric   passes.run(*MergedModule);
552f785676fSDimitry Andric 
553ff0cc061SDimitry Andric   return true;
554ff0cc061SDimitry Andric }
555f785676fSDimitry Andric 
5567d523365SDimitry Andric bool LTOCodeGenerator::compileOptimized(ArrayRef<raw_pwrite_stream *> Out) {
5577d523365SDimitry Andric   if (!this->determineTarget())
558ff0cc061SDimitry Andric     return false;
559ff0cc061SDimitry Andric 
5603ca95b02SDimitry Andric   // We always run the verifier once on the merged module.  If it has already
5613ca95b02SDimitry Andric   // been called in optimize(), this call will return early.
5623ca95b02SDimitry Andric   verifyMergedModuleOnce();
5633ca95b02SDimitry Andric 
5647d523365SDimitry Andric   legacy::PassManager preCodeGenPasses;
565f785676fSDimitry Andric 
566f785676fSDimitry Andric   // If the bitcode files contain ARC code and were compiled with optimization,
567f785676fSDimitry Andric   // the ObjCARCContractPass must be run, so do it unconditionally here.
5687d523365SDimitry Andric   preCodeGenPasses.add(createObjCARCContractPass());
5697d523365SDimitry Andric   preCodeGenPasses.run(*MergedModule);
570f785676fSDimitry Andric 
5713ca95b02SDimitry Andric   // Re-externalize globals that may have been internalized to increase scope
5723ca95b02SDimitry Andric   // for splitting
5733ca95b02SDimitry Andric   restoreLinkageForExternals();
5743ca95b02SDimitry Andric 
5757d523365SDimitry Andric   // Do code generation. We need to preserve the module in case the client calls
5767d523365SDimitry Andric   // writeMergedModules() after compilation, but we only need to allow this at
5777d523365SDimitry Andric   // parallelism level 1. This is achieved by having splitCodeGen return the
5787d523365SDimitry Andric   // original module at parallelism level 1 which we then assign back to
5797d523365SDimitry Andric   // MergedModule.
5803ca95b02SDimitry Andric   MergedModule = splitCodeGen(std::move(MergedModule), Out, {},
5813ca95b02SDimitry Andric                               [&]() { return createTargetMachine(); }, FileType,
5823ca95b02SDimitry Andric                               ShouldRestoreGlobalsLinkage);
5833ca95b02SDimitry Andric 
5843ca95b02SDimitry Andric   // If statistics were requested, print them out after codegen.
5853ca95b02SDimitry Andric   if (llvm::AreStatisticsEnabled())
5863ca95b02SDimitry Andric     llvm::PrintStatistics();
587f785676fSDimitry Andric 
588f785676fSDimitry Andric   return true;
589f785676fSDimitry Andric }
590f785676fSDimitry Andric 
591f785676fSDimitry Andric /// setCodeGenDebugOptions - Set codegen debugging options to aid in debugging
592f785676fSDimitry Andric /// LTO problems.
5937d523365SDimitry Andric void LTOCodeGenerator::setCodeGenDebugOptions(const char *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 void LTOCodeGenerator::DiagnosticHandler(const DiagnosticInfo &DI,
61191bc56edSDimitry Andric                                          void *Context) {
61291bc56edSDimitry Andric   ((LTOCodeGenerator *)Context)->DiagnosticHandler2(DI);
61391bc56edSDimitry Andric }
61491bc56edSDimitry Andric 
61591bc56edSDimitry Andric void LTOCodeGenerator::DiagnosticHandler2(const DiagnosticInfo &DI) {
61691bc56edSDimitry Andric   // Map the LLVM internal diagnostic severity to the LTO diagnostic severity.
61791bc56edSDimitry Andric   lto_codegen_diagnostic_severity_t Severity;
61891bc56edSDimitry Andric   switch (DI.getSeverity()) {
61991bc56edSDimitry Andric   case DS_Error:
62091bc56edSDimitry Andric     Severity = LTO_DS_ERROR;
62191bc56edSDimitry Andric     break;
62291bc56edSDimitry Andric   case DS_Warning:
62391bc56edSDimitry Andric     Severity = LTO_DS_WARNING;
62491bc56edSDimitry Andric     break;
62591bc56edSDimitry Andric   case DS_Remark:
62691bc56edSDimitry Andric     Severity = LTO_DS_REMARK;
62791bc56edSDimitry Andric     break;
62891bc56edSDimitry Andric   case DS_Note:
62991bc56edSDimitry Andric     Severity = LTO_DS_NOTE;
63091bc56edSDimitry Andric     break;
63191bc56edSDimitry Andric   }
63291bc56edSDimitry Andric   // Create the string that will be reported to the external diagnostic handler.
63391bc56edSDimitry Andric   std::string MsgStorage;
63491bc56edSDimitry Andric   raw_string_ostream Stream(MsgStorage);
63591bc56edSDimitry Andric   DiagnosticPrinterRawOStream DP(Stream);
63691bc56edSDimitry Andric   DI.print(DP);
63791bc56edSDimitry Andric   Stream.flush();
63891bc56edSDimitry Andric 
63991bc56edSDimitry Andric   // If this method has been called it means someone has set up an external
64091bc56edSDimitry Andric   // diagnostic handler. Assert on that.
64191bc56edSDimitry Andric   assert(DiagHandler && "Invalid diagnostic handler");
64291bc56edSDimitry Andric   (*DiagHandler)(Severity, MsgStorage.c_str(), DiagContext);
64391bc56edSDimitry Andric }
64491bc56edSDimitry Andric 
64591bc56edSDimitry Andric void
64691bc56edSDimitry Andric LTOCodeGenerator::setDiagnosticHandler(lto_diagnostic_handler_t DiagHandler,
64791bc56edSDimitry Andric                                        void *Ctxt) {
64891bc56edSDimitry Andric   this->DiagHandler = DiagHandler;
64991bc56edSDimitry Andric   this->DiagContext = Ctxt;
65091bc56edSDimitry Andric   if (!DiagHandler)
65191bc56edSDimitry Andric     return Context.setDiagnosticHandler(nullptr, nullptr);
65291bc56edSDimitry Andric   // Register the LTOCodeGenerator stub in the LLVMContext to forward the
65391bc56edSDimitry Andric   // diagnostic to the external DiagHandler.
65439d628a0SDimitry Andric   Context.setDiagnosticHandler(LTOCodeGenerator::DiagnosticHandler, this,
65539d628a0SDimitry Andric                                /* RespectFilters */ true);
65691bc56edSDimitry Andric }
6577d523365SDimitry Andric 
6587d523365SDimitry Andric namespace {
6597d523365SDimitry Andric class LTODiagnosticInfo : public DiagnosticInfo {
6607d523365SDimitry Andric   const Twine &Msg;
6617d523365SDimitry Andric public:
6627d523365SDimitry Andric   LTODiagnosticInfo(const Twine &DiagMsg, DiagnosticSeverity Severity=DS_Error)
6637d523365SDimitry Andric       : DiagnosticInfo(DK_Linker, Severity), Msg(DiagMsg) {}
6647d523365SDimitry Andric   void print(DiagnosticPrinter &DP) const override { DP << Msg; }
6657d523365SDimitry Andric };
6667d523365SDimitry Andric }
6677d523365SDimitry Andric 
6687d523365SDimitry Andric void LTOCodeGenerator::emitError(const std::string &ErrMsg) {
6697d523365SDimitry Andric   if (DiagHandler)
6707d523365SDimitry Andric     (*DiagHandler)(LTO_DS_ERROR, ErrMsg.c_str(), DiagContext);
6717d523365SDimitry Andric   else
6727d523365SDimitry Andric     Context.diagnose(LTODiagnosticInfo(ErrMsg));
6737d523365SDimitry Andric }
6743ca95b02SDimitry Andric 
6753ca95b02SDimitry Andric void LTOCodeGenerator::emitWarning(const std::string &ErrMsg) {
6763ca95b02SDimitry Andric   if (DiagHandler)
6773ca95b02SDimitry Andric     (*DiagHandler)(LTO_DS_WARNING, ErrMsg.c_str(), DiagContext);
6783ca95b02SDimitry Andric   else
6793ca95b02SDimitry Andric     Context.diagnose(LTODiagnosticInfo(ErrMsg, DS_Warning));
6803ca95b02SDimitry Andric }
681