blob: 7d5d82a93cc199400e41ef2f4cc93bf8c20a35b7 [file] [log] [blame]
Nick Kledzik07b4a622008-02-26 20:26:43 +00001//===-LTOCodeGenerator.cpp - LLVM Link Time Optimizer ---------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Bill Wendling39d942b2012-03-31 10:50:14 +00007//
Nick Kledzik07b4a622008-02-26 20:26:43 +00008//===----------------------------------------------------------------------===//
9//
Bill Wendling39d942b2012-03-31 10:50:14 +000010// This file implements the Link Time Optimization library. This library is
Nick Kledzik07b4a622008-02-26 20:26:43 +000011// intended to be used by linker to optimize code at link time.
12//
13//===----------------------------------------------------------------------===//
14
Peter Collingbourne4ccf0f12013-09-24 23:52:22 +000015#include "llvm/LTO/LTOCodeGenerator.h"
16#include "llvm/LTO/LTOModule.h"
Chandler Carruth4d88a1c2012-12-04 10:44:52 +000017#include "llvm/ADT/StringExtras.h"
Nick Lewycky510dae32009-06-17 06:52:10 +000018#include "llvm/Analysis/Passes.h"
Rafael Espindola3ea478b2011-08-02 21:50:27 +000019#include "llvm/Analysis/Verifier.h"
Nick Kledzik07b4a622008-02-26 20:26:43 +000020#include "llvm/Bitcode/ReaderWriter.h"
Justin Bognerb10a5202013-11-12 21:44:01 +000021#include "llvm/CodeGen/RuntimeLibcalls.h"
Bill Wendling0e1824c2012-03-31 11:15:43 +000022#include "llvm/Config/config.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000023#include "llvm/IR/Constants.h"
24#include "llvm/IR/DataLayout.h"
25#include "llvm/IR/DerivedTypes.h"
26#include "llvm/IR/LLVMContext.h"
27#include "llvm/IR/Module.h"
Shuxin Yang1e6d80e2013-07-22 18:40:34 +000028#include "llvm/InitializePasses.h"
Chandler Carruth4d88a1c2012-12-04 10:44:52 +000029#include "llvm/Linker.h"
Chris Lattner2eff5052010-03-12 18:44:54 +000030#include "llvm/MC/MCAsmInfo.h"
31#include "llvm/MC/MCContext.h"
Evan Cheng8264e272011-06-29 01:14:12 +000032#include "llvm/MC/SubtargetFeature.h"
Chandler Carruth4d88a1c2012-12-04 10:44:52 +000033#include "llvm/PassManager.h"
Nick Kledzikc2323472008-07-08 21:14:10 +000034#include "llvm/Support/CommandLine.h"
Rafael Espindola40c908b2013-06-17 18:05:35 +000035#include "llvm/Support/FileSystem.h"
David Greenea31f96c2009-07-14 20:18:05 +000036#include "llvm/Support/FormattedStream.h"
Michael J. Spencerab425d82010-11-29 18:47:54 +000037#include "llvm/Support/Host.h"
Chandler Carruth4d88a1c2012-12-04 10:44:52 +000038#include "llvm/Support/MemoryBuffer.h"
Michael J. Spencerab425d82010-11-29 18:47:54 +000039#include "llvm/Support/Signals.h"
Evan Cheng2bb40352011-08-24 18:08:43 +000040#include "llvm/Support/TargetRegistry.h"
41#include "llvm/Support/TargetSelect.h"
Chandler Carruth4d88a1c2012-12-04 10:44:52 +000042#include "llvm/Support/ToolOutputFile.h"
Michael J. Spencerd4227232010-12-09 18:06:07 +000043#include "llvm/Support/system_error.h"
Justin Bognerb10a5202013-11-12 21:44:01 +000044#include "llvm/Target/TargetLibraryInfo.h"
45#include "llvm/Target/TargetLowering.h"
Rafael Espindola0b385c72013-09-30 16:39:19 +000046#include "llvm/Target/TargetOptions.h"
Chandler Carruth4d88a1c2012-12-04 10:44:52 +000047#include "llvm/Target/TargetRegisterInfo.h"
Peter Collingbourne4ccf0f12013-09-24 23:52:22 +000048#include "llvm/Target/Mangler.h"
Chandler Carruth4d88a1c2012-12-04 10:44:52 +000049#include "llvm/Transforms/IPO.h"
50#include "llvm/Transforms/IPO/PassManagerBuilder.h"
Bob Wilsonf36f15f2013-03-29 23:28:55 +000051#include "llvm/Transforms/ObjCARC.h"
Shuxin Yang76d082b2013-08-12 18:29:43 +000052using namespace llvm;
Shuxin Yang76d082b2013-08-12 18:29:43 +000053
Bill Wendling534a6582012-03-31 10:49:43 +000054const char* LTOCodeGenerator::getVersionString() {
Nick Kledzik07b4a622008-02-26 20:26:43 +000055#ifdef LLVM_VERSION_INFO
Bill Wendling534a6582012-03-31 10:49:43 +000056 return PACKAGE_NAME " version " PACKAGE_VERSION ", " LLVM_VERSION_INFO;
Nick Kledzik07b4a622008-02-26 20:26:43 +000057#else
Bill Wendling534a6582012-03-31 10:49:43 +000058 return PACKAGE_NAME " version " PACKAGE_VERSION;
Nick Kledzik07b4a622008-02-26 20:26:43 +000059#endif
60}
61
Bill Wendling39d942b2012-03-31 10:50:14 +000062LTOCodeGenerator::LTOCodeGenerator()
Rafael Espindolac80c9692013-09-04 17:44:24 +000063 : Context(getGlobalContext()), Linker(new Module("ld-temp.o", Context)),
64 TargetMach(NULL), EmitDwarfDebugInfo(false), ScopeRestrictionsDone(false),
65 CodeModel(LTO_CODEGEN_PIC_MODEL_DYNAMIC), NativeObjectFile(NULL) {
Shuxin Yang1e6d80e2013-07-22 18:40:34 +000066 initializeLTOPasses();
Nick Kledzik07b4a622008-02-26 20:26:43 +000067}
68
Bill Wendling534a6582012-03-31 10:49:43 +000069LTOCodeGenerator::~LTOCodeGenerator() {
Rafael Espindolac80c9692013-09-04 17:44:24 +000070 delete TargetMach;
71 delete NativeObjectFile;
Bill Wendling91e6f6e2013-10-16 08:59:57 +000072 TargetMach = NULL;
73 NativeObjectFile = NULL;
74
75 Linker.deleteModule();
Bill Wendling534a6582012-03-31 10:49:43 +000076
Rafael Espindolac80c9692013-09-04 17:44:24 +000077 for (std::vector<char *>::iterator I = CodegenOptions.begin(),
78 E = CodegenOptions.end();
79 I != E; ++I)
Bill Wendling534a6582012-03-31 10:49:43 +000080 free(*I);
Nick Kledzik07b4a622008-02-26 20:26:43 +000081}
82
Shuxin Yang1e6d80e2013-07-22 18:40:34 +000083// Initialize LTO passes. Please keep this funciton in sync with
Shuxin Yangca760852013-07-23 06:44:34 +000084// PassManagerBuilder::populateLTOPassManager(), and make sure all LTO
Shuxin Yang1e6d80e2013-07-22 18:40:34 +000085// passes are initialized.
86//
87void LTOCodeGenerator::initializeLTOPasses() {
88 PassRegistry &R = *PassRegistry::getPassRegistry();
89
90 initializeInternalizePassPass(R);
91 initializeIPSCCPPass(R);
92 initializeGlobalOptPass(R);
93 initializeConstantMergePass(R);
94 initializeDAHPass(R);
95 initializeInstCombinerPass(R);
96 initializeSimpleInlinerPass(R);
97 initializePruneEHPass(R);
98 initializeGlobalDCEPass(R);
99 initializeArgPromotionPass(R);
100 initializeJumpThreadingPass(R);
101 initializeSROAPass(R);
102 initializeSROA_DTPass(R);
103 initializeSROA_SSAUpPass(R);
104 initializeFunctionAttrsPass(R);
105 initializeGlobalsModRefPass(R);
106 initializeLICMPass(R);
107 initializeGVNPass(R);
108 initializeMemCpyOptPass(R);
109 initializeDCEPass(R);
Tom Stellardaa664d92013-08-06 02:43:45 +0000110 initializeCFGSimplifyPassPass(R);
Shuxin Yang1e6d80e2013-07-22 18:40:34 +0000111}
112
Bill Wendling0e1824c2012-03-31 11:15:43 +0000113bool LTOCodeGenerator::addModule(LTOModule* mod, std::string& errMsg) {
Rafael Espindolac80c9692013-09-04 17:44:24 +0000114 bool ret = Linker.linkInModule(mod->getLLVVMModule(), &errMsg);
Rafael Espindola1e49a6d2011-03-02 04:14:42 +0000115
116 const std::vector<const char*> &undefs = mod->getAsmUndefinedRefs();
117 for (int i = 0, e = undefs.size(); i != e; ++i)
Rafael Espindolac80c9692013-09-04 17:44:24 +0000118 AsmUndefinedRefs[undefs[i]] = 1;
Rafael Espindola1e49a6d2011-03-02 04:14:42 +0000119
Shuxin Yangb6696a92013-08-07 05:19:23 +0000120 return !ret;
Nick Kledzik07b4a622008-02-26 20:26:43 +0000121}
Bill Wendling39d942b2012-03-31 10:50:14 +0000122
Rafael Espindola0b385c72013-09-30 16:39:19 +0000123void LTOCodeGenerator::setTargetOptions(TargetOptions options) {
124 Options.LessPreciseFPMADOption = options.LessPreciseFPMADOption;
125 Options.NoFramePointerElim = options.NoFramePointerElim;
126 Options.AllowFPOpFusion = options.AllowFPOpFusion;
127 Options.UnsafeFPMath = options.UnsafeFPMath;
128 Options.NoInfsFPMath = options.NoInfsFPMath;
129 Options.NoNaNsFPMath = options.NoNaNsFPMath;
130 Options.HonorSignDependentRoundingFPMathOption =
131 options.HonorSignDependentRoundingFPMathOption;
132 Options.UseSoftFloat = options.UseSoftFloat;
133 Options.FloatABIType = options.FloatABIType;
134 Options.NoZerosInBSS = options.NoZerosInBSS;
135 Options.GuaranteedTailCallOpt = options.GuaranteedTailCallOpt;
136 Options.DisableTailCalls = options.DisableTailCalls;
137 Options.StackAlignmentOverride = options.StackAlignmentOverride;
138 Options.TrapFuncName = options.TrapFuncName;
139 Options.PositionIndependentExecutable = options.PositionIndependentExecutable;
140 Options.EnableSegmentedStacks = options.EnableSegmentedStacks;
141 Options.UseInitArray = options.UseInitArray;
142}
143
Shuxin Yangb6696a92013-08-07 05:19:23 +0000144void LTOCodeGenerator::setDebugInfo(lto_debug_model debug) {
Bill Wendling0e1824c2012-03-31 11:15:43 +0000145 switch (debug) {
146 case LTO_DEBUG_MODEL_NONE:
Rafael Espindolac80c9692013-09-04 17:44:24 +0000147 EmitDwarfDebugInfo = false;
Shuxin Yangb6696a92013-08-07 05:19:23 +0000148 return;
Nick Kledzik07b4a622008-02-26 20:26:43 +0000149
Bill Wendling0e1824c2012-03-31 11:15:43 +0000150 case LTO_DEBUG_MODEL_DWARF:
Rafael Espindolac80c9692013-09-04 17:44:24 +0000151 EmitDwarfDebugInfo = true;
Shuxin Yangb6696a92013-08-07 05:19:23 +0000152 return;
Bill Wendling0e1824c2012-03-31 11:15:43 +0000153 }
154 llvm_unreachable("Unknown debug format!");
Nick Kledzik07b4a622008-02-26 20:26:43 +0000155}
156
Shuxin Yangb6696a92013-08-07 05:19:23 +0000157void LTOCodeGenerator::setCodePICModel(lto_codegen_model model) {
Bill Wendling0e1824c2012-03-31 11:15:43 +0000158 switch (model) {
159 case LTO_CODEGEN_PIC_MODEL_STATIC:
160 case LTO_CODEGEN_PIC_MODEL_DYNAMIC:
161 case LTO_CODEGEN_PIC_MODEL_DYNAMIC_NO_PIC:
Rafael Espindolac80c9692013-09-04 17:44:24 +0000162 CodeModel = model;
Shuxin Yangb6696a92013-08-07 05:19:23 +0000163 return;
Bill Wendling0e1824c2012-03-31 11:15:43 +0000164 }
165 llvm_unreachable("Unknown PIC model!");
Nick Kledzik07b4a622008-02-26 20:26:43 +0000166}
167
Chris Lattner69733952009-08-23 07:49:08 +0000168bool LTOCodeGenerator::writeMergedModules(const char *path,
169 std::string &errMsg) {
Shuxin Yang95866fa2013-08-06 21:51:21 +0000170 if (!determineTarget(errMsg))
Shuxin Yangb6696a92013-08-07 05:19:23 +0000171 return false;
Nick Kledzik07b4a622008-02-26 20:26:43 +0000172
Bill Wendling2bbbfef2013-08-08 23:51:04 +0000173 // mark which symbols can not be internalized
174 applyScopeRestrictions();
Nick Kledzik07b4a622008-02-26 20:26:43 +0000175
Chris Lattner69733952009-08-23 07:49:08 +0000176 // create output file
177 std::string ErrInfo;
Rafael Espindola6d354812013-07-16 19:44:17 +0000178 tool_output_file Out(path, ErrInfo, sys::fs::F_Binary);
Chris Lattner69733952009-08-23 07:49:08 +0000179 if (!ErrInfo.empty()) {
180 errMsg = "could not open bitcode file for writing: ";
181 errMsg += path;
Shuxin Yangb6696a92013-08-07 05:19:23 +0000182 return false;
Chris Lattner69733952009-08-23 07:49:08 +0000183 }
Bill Wendling39d942b2012-03-31 10:50:14 +0000184
Chris Lattner69733952009-08-23 07:49:08 +0000185 // write bitcode to it
Rafael Espindolac80c9692013-09-04 17:44:24 +0000186 WriteBitcodeToFile(Linker.getModule(), Out.os());
Dan Gohmana2233f22010-09-01 14:20:41 +0000187 Out.os().close();
Dan Gohmanab366f02010-05-27 20:19:47 +0000188
Dan Gohmana2233f22010-09-01 14:20:41 +0000189 if (Out.os().has_error()) {
Chris Lattner69733952009-08-23 07:49:08 +0000190 errMsg = "could not write bitcode file: ";
191 errMsg += path;
Dan Gohmana2233f22010-09-01 14:20:41 +0000192 Out.os().clear_error();
Shuxin Yangb6696a92013-08-07 05:19:23 +0000193 return false;
Chris Lattner69733952009-08-23 07:49:08 +0000194 }
Bill Wendling39d942b2012-03-31 10:50:14 +0000195
Dan Gohman8525fe72010-08-20 16:59:15 +0000196 Out.keep();
Shuxin Yangb6696a92013-08-07 05:19:23 +0000197 return true;
Nick Kledzik07b4a622008-02-26 20:26:43 +0000198}
199
Rafael Espindola0b385c72013-09-30 16:39:19 +0000200bool LTOCodeGenerator::compile_to_file(const char** name,
201 bool disableOpt,
202 bool disableInline,
203 bool disableGVNLoadPRE,
204 std::string& errMsg) {
Shuxin Yang1826ae22013-08-12 21:07:31 +0000205 // make unique temp .o file to put generated object file
206 SmallString<128> Filename;
207 int FD;
208 error_code EC = sys::fs::createTemporaryFile("lto-llvm", "o", FD, Filename);
209 if (EC) {
210 errMsg = EC.message();
Shuxin Yangb6696a92013-08-07 05:19:23 +0000211 return false;
Shuxin Yang1826ae22013-08-12 21:07:31 +0000212 }
Rafael Espindola26b57ff2011-03-22 20:57:13 +0000213
Shuxin Yang1826ae22013-08-12 21:07:31 +0000214 // generate object file
215 tool_output_file objFile(Filename.c_str(), FD);
Bill Wendling0e1824c2012-03-31 11:15:43 +0000216
Rafael Espindola0b385c72013-09-30 16:39:19 +0000217 bool genResult = generateObjectFile(objFile.os(), disableOpt, disableInline,
218 disableGVNLoadPRE, errMsg);
Shuxin Yang1826ae22013-08-12 21:07:31 +0000219 objFile.os().close();
220 if (objFile.os().has_error()) {
221 objFile.os().clear_error();
222 sys::fs::remove(Twine(Filename));
Shuxin Yangb6696a92013-08-07 05:19:23 +0000223 return false;
Shuxin Yang1826ae22013-08-12 21:07:31 +0000224 }
Bill Wendling0e1824c2012-03-31 11:15:43 +0000225
Shuxin Yang1826ae22013-08-12 21:07:31 +0000226 objFile.keep();
227 if (!genResult) {
228 sys::fs::remove(Twine(Filename));
Shuxin Yangb6696a92013-08-07 05:19:23 +0000229 return false;
Shuxin Yang1826ae22013-08-12 21:07:31 +0000230 }
Rafael Espindola26b57ff2011-03-22 20:57:13 +0000231
Rafael Espindolac80c9692013-09-04 17:44:24 +0000232 NativeObjectPath = Filename.c_str();
233 *name = NativeObjectPath.c_str();
Shuxin Yangb6696a92013-08-07 05:19:23 +0000234 return true;
Rafael Espindola26b57ff2011-03-22 20:57:13 +0000235}
236
Rafael Espindola0b385c72013-09-30 16:39:19 +0000237const void* LTOCodeGenerator::compile(size_t* length,
238 bool disableOpt,
239 bool disableInline,
240 bool disableGVNLoadPRE,
241 std::string& errMsg) {
Rafael Espindola26b57ff2011-03-22 20:57:13 +0000242 const char *name;
Rafael Espindola0b385c72013-09-30 16:39:19 +0000243 if (!compile_to_file(&name, disableOpt, disableInline, disableGVNLoadPRE,
244 errMsg))
Rafael Espindola26b57ff2011-03-22 20:57:13 +0000245 return NULL;
Nick Kledzik07b4a622008-02-26 20:26:43 +0000246
Rafael Espindola26b57ff2011-03-22 20:57:13 +0000247 // remove old buffer if compile() called twice
Rafael Espindolac80c9692013-09-04 17:44:24 +0000248 delete NativeObjectFile;
Nick Kledzik91a6dcf2008-02-27 22:25:36 +0000249
Rafael Espindola26b57ff2011-03-22 20:57:13 +0000250 // read .o file into memory buffer
251 OwningPtr<MemoryBuffer> BuffPtr;
252 if (error_code ec = MemoryBuffer::getFile(name, BuffPtr, -1, false)) {
253 errMsg = ec.message();
Rafael Espindolac80c9692013-09-04 17:44:24 +0000254 sys::fs::remove(NativeObjectPath);
Shuxin Yang1826ae22013-08-12 21:07:31 +0000255 return NULL;
Rafael Espindola26b57ff2011-03-22 20:57:13 +0000256 }
Rafael Espindolac80c9692013-09-04 17:44:24 +0000257 NativeObjectFile = BuffPtr.take();
Rafael Espindolafac373c2011-02-24 21:04:06 +0000258
Shuxin Yang1826ae22013-08-12 21:07:31 +0000259 // remove temp files
Rafael Espindolac80c9692013-09-04 17:44:24 +0000260 sys::fs::remove(NativeObjectPath);
Rafael Espindolafac373c2011-02-24 21:04:06 +0000261
Shuxin Yang1826ae22013-08-12 21:07:31 +0000262 // return buffer, unless error
Rafael Espindolac80c9692013-09-04 17:44:24 +0000263 if (NativeObjectFile == NULL)
Shuxin Yang1826ae22013-08-12 21:07:31 +0000264 return NULL;
Rafael Espindolac80c9692013-09-04 17:44:24 +0000265 *length = NativeObjectFile->getBufferSize();
266 return NativeObjectFile->getBufferStart();
Nick Kledzik07b4a622008-02-26 20:26:43 +0000267}
268
Bill Wendlingf44b2a22013-05-23 21:21:50 +0000269bool LTOCodeGenerator::determineTarget(std::string &errMsg) {
Rafael Espindolac80c9692013-09-04 17:44:24 +0000270 if (TargetMach != NULL)
Shuxin Yang95866fa2013-08-06 21:51:21 +0000271 return true;
Daniel Dunbar0f16ea52009-08-03 04:03:51 +0000272
Rafael Espindolac80c9692013-09-04 17:44:24 +0000273 std::string TripleStr = Linker.getModule()->getTargetTriple();
Bob Wilson3f7e7c02012-10-12 17:39:25 +0000274 if (TripleStr.empty())
275 TripleStr = sys::getDefaultTargetTriple();
276 llvm::Triple Triple(TripleStr);
Bill Wendling9b2c5732008-06-18 06:35:30 +0000277
Bill Wendling45f74e32012-08-06 22:52:45 +0000278 // create target machine from info for merged modules
Bob Wilson3f7e7c02012-10-12 17:39:25 +0000279 const Target *march = TargetRegistry::lookupTarget(TripleStr, errMsg);
Bill Wendling6a0abed2012-08-08 22:03:50 +0000280 if (march == NULL)
Shuxin Yang95866fa2013-08-06 21:51:21 +0000281 return false;
Bill Wendling0e1824c2012-03-31 11:15:43 +0000282
Bill Wendling45f74e32012-08-06 22:52:45 +0000283 // The relocation model is actually a static member of TargetMachine and
284 // needs to be set before the TargetMachine is instantiated.
285 Reloc::Model RelocModel = Reloc::Default;
Rafael Espindolac80c9692013-09-04 17:44:24 +0000286 switch (CodeModel) {
Bill Wendling45f74e32012-08-06 22:52:45 +0000287 case LTO_CODEGEN_PIC_MODEL_STATIC:
288 RelocModel = Reloc::Static;
289 break;
290 case LTO_CODEGEN_PIC_MODEL_DYNAMIC:
291 RelocModel = Reloc::PIC_;
292 break;
293 case LTO_CODEGEN_PIC_MODEL_DYNAMIC_NO_PIC:
294 RelocModel = Reloc::DynamicNoPIC;
295 break;
Bill Wendling0e1824c2012-03-31 11:15:43 +0000296 }
Bill Wendling45f74e32012-08-06 22:52:45 +0000297
298 // construct LTOModule, hand over ownership of module and target
299 SubtargetFeatures Features;
Bob Wilson3f7e7c02012-10-12 17:39:25 +0000300 Features.getDefaultSubtargetFeatures(Triple);
Bill Wendling45f74e32012-08-06 22:52:45 +0000301 std::string FeatureStr = Features.getString();
Bob Wilson3f7e7c02012-10-12 17:39:25 +0000302 // Set a default CPU for Darwin triples.
Rafael Espindolac80c9692013-09-04 17:44:24 +0000303 if (MCpu.empty() && Triple.isOSDarwin()) {
Bob Wilson3f7e7c02012-10-12 17:39:25 +0000304 if (Triple.getArch() == llvm::Triple::x86_64)
Rafael Espindolac80c9692013-09-04 17:44:24 +0000305 MCpu = "core2";
Bob Wilson3f7e7c02012-10-12 17:39:25 +0000306 else if (Triple.getArch() == llvm::Triple::x86)
Rafael Espindolac80c9692013-09-04 17:44:24 +0000307 MCpu = "yonah";
Bob Wilson3f7e7c02012-10-12 17:39:25 +0000308 }
Rafael Espindola0b385c72013-09-30 16:39:19 +0000309
Rafael Espindolac80c9692013-09-04 17:44:24 +0000310 TargetMach = march->createTargetMachine(TripleStr, MCpu, FeatureStr, Options,
311 RelocModel, CodeModel::Default,
312 CodeGenOpt::Aggressive);
Shuxin Yang95866fa2013-08-06 21:51:21 +0000313 return true;
Nick Kledzik07b4a622008-02-26 20:26:43 +0000314}
315
Bill Wendling0e1824c2012-03-31 11:15:43 +0000316void LTOCodeGenerator::
317applyRestriction(GlobalValue &GV,
Justin Bognerb10a5202013-11-12 21:44:01 +0000318 const ArrayRef<StringRef> &Libcalls,
Rafael Espindolab7c0b4a2013-09-04 20:08:46 +0000319 std::vector<const char*> &MustPreserveList,
320 SmallPtrSet<GlobalValue*, 8> &AsmUsed,
321 Mangler &Mangler) {
Rafael Espindola1e49a6d2011-03-02 04:14:42 +0000322 SmallString<64> Buffer;
Rafael Espindola117b20c2013-12-05 05:53:12 +0000323 Mangler.getNameWithPrefix(Buffer, &GV);
Rafael Espindola1e49a6d2011-03-02 04:14:42 +0000324
325 if (GV.isDeclaration())
326 return;
Rafael Espindolac80c9692013-09-04 17:44:24 +0000327 if (MustPreserveSymbols.count(Buffer))
Rafael Espindolab7c0b4a2013-09-04 20:08:46 +0000328 MustPreserveList.push_back(GV.getName().data());
Rafael Espindolac80c9692013-09-04 17:44:24 +0000329 if (AsmUndefinedRefs.count(Buffer))
Rafael Espindolab7c0b4a2013-09-04 20:08:46 +0000330 AsmUsed.insert(&GV);
Justin Bognerb10a5202013-11-12 21:44:01 +0000331
332 // Conservatively append user-supplied runtime library functions to
333 // llvm.compiler.used. These could be internalized and deleted by
334 // optimizations like -globalopt, causing problems when later optimizations
335 // add new library calls (e.g., llvm.memset => memset and printf => puts).
336 // Leave it to the linker to remove any dead code (e.g. with -dead_strip).
337 if (isa<Function>(GV) &&
338 std::binary_search(Libcalls.begin(), Libcalls.end(), GV.getName()))
339 AsmUsed.insert(&GV);
Rafael Espindola1e49a6d2011-03-02 04:14:42 +0000340}
341
342static void findUsedValues(GlobalVariable *LLVMUsed,
343 SmallPtrSet<GlobalValue*, 8> &UsedValues) {
344 if (LLVMUsed == 0) return;
345
Rafael Espindolacc111b22013-04-24 17:54:35 +0000346 ConstantArray *Inits = cast<ConstantArray>(LLVMUsed->getInitializer());
Rafael Espindola1e49a6d2011-03-02 04:14:42 +0000347 for (unsigned i = 0, e = Inits->getNumOperands(); i != e; ++i)
Bill Wendling39d942b2012-03-31 10:50:14 +0000348 if (GlobalValue *GV =
Bill Wendling0e1824c2012-03-31 11:15:43 +0000349 dyn_cast<GlobalValue>(Inits->getOperand(i)->stripPointerCasts()))
Rafael Espindola1e49a6d2011-03-02 04:14:42 +0000350 UsedValues.insert(GV);
351}
352
Justin Bognerb10a5202013-11-12 21:44:01 +0000353static void accumulateAndSortLibcalls(std::vector<StringRef> &Libcalls,
354 const TargetLibraryInfo& TLI,
355 const TargetLowering *Lowering)
356{
357 // TargetLibraryInfo has info on C runtime library calls on the current
358 // target.
359 for (unsigned I = 0, E = static_cast<unsigned>(LibFunc::NumLibFuncs);
360 I != E; ++I) {
361 LibFunc::Func F = static_cast<LibFunc::Func>(I);
362 if (TLI.has(F))
363 Libcalls.push_back(TLI.getName(F));
364 }
365
366 // TargetLowering has info on library calls that CodeGen expects to be
367 // available, both from the C runtime and compiler-rt.
368 if (Lowering)
369 for (unsigned I = 0, E = static_cast<unsigned>(RTLIB::UNKNOWN_LIBCALL);
370 I != E; ++I)
371 if (const char *Name
372 = Lowering->getLibcallName(static_cast<RTLIB::Libcall>(I)))
373 Libcalls.push_back(Name);
374
Duncan P. N. Exon Smith0c8d6042013-11-16 16:15:56 +0000375 array_pod_sort(Libcalls.begin(), Libcalls.end());
Justin Bognerb10a5202013-11-12 21:44:01 +0000376 Libcalls.erase(std::unique(Libcalls.begin(), Libcalls.end()),
377 Libcalls.end());
378}
379
Chris Lattner2eff5052010-03-12 18:44:54 +0000380void LTOCodeGenerator::applyScopeRestrictions() {
Rafael Espindolac80c9692013-09-04 17:44:24 +0000381 if (ScopeRestrictionsDone)
382 return;
383 Module *mergedModule = Linker.getModule();
Nick Kledzik07b4a622008-02-26 20:26:43 +0000384
Chris Lattner2eff5052010-03-12 18:44:54 +0000385 // Start off with a verification pass.
386 PassManager passes;
387 passes.add(createVerifierPass());
Nick Kledzik07b4a622008-02-26 20:26:43 +0000388
Bill Wendling39d942b2012-03-31 10:50:14 +0000389 // mark which symbols can not be internalized
Rafael Espindolae133ed82013-10-29 17:28:26 +0000390 Mangler Mangler(TargetMach);
Rafael Espindolab7c0b4a2013-09-04 20:08:46 +0000391 std::vector<const char*> MustPreserveList;
392 SmallPtrSet<GlobalValue*, 8> AsmUsed;
Justin Bognerb10a5202013-11-12 21:44:01 +0000393 std::vector<StringRef> Libcalls;
394 TargetLibraryInfo TLI(Triple(TargetMach->getTargetTriple()));
395 accumulateAndSortLibcalls(Libcalls, TLI, TargetMach->getTargetLowering());
Rafael Espindola1e49a6d2011-03-02 04:14:42 +0000396
397 for (Module::iterator f = mergedModule->begin(),
398 e = mergedModule->end(); f != e; ++f)
Justin Bognerb10a5202013-11-12 21:44:01 +0000399 applyRestriction(*f, Libcalls, MustPreserveList, AsmUsed, Mangler);
Bill Wendling39d942b2012-03-31 10:50:14 +0000400 for (Module::global_iterator v = mergedModule->global_begin(),
Rafael Espindola1e49a6d2011-03-02 04:14:42 +0000401 e = mergedModule->global_end(); v != e; ++v)
Justin Bognerb10a5202013-11-12 21:44:01 +0000402 applyRestriction(*v, Libcalls, MustPreserveList, AsmUsed, Mangler);
Rafael Espindola1e49a6d2011-03-02 04:14:42 +0000403 for (Module::alias_iterator a = mergedModule->alias_begin(),
404 e = mergedModule->alias_end(); a != e; ++a)
Justin Bognerb10a5202013-11-12 21:44:01 +0000405 applyRestriction(*a, Libcalls, MustPreserveList, AsmUsed, Mangler);
Rafael Espindola1e49a6d2011-03-02 04:14:42 +0000406
407 GlobalVariable *LLVMCompilerUsed =
408 mergedModule->getGlobalVariable("llvm.compiler.used");
Rafael Espindolab7c0b4a2013-09-04 20:08:46 +0000409 findUsedValues(LLVMCompilerUsed, AsmUsed);
Rafael Espindola1e49a6d2011-03-02 04:14:42 +0000410 if (LLVMCompilerUsed)
411 LLVMCompilerUsed->eraseFromParent();
412
Rafael Espindolab7c0b4a2013-09-04 20:08:46 +0000413 if (!AsmUsed.empty()) {
Rafael Espindolac80c9692013-09-04 17:44:24 +0000414 llvm::Type *i8PTy = llvm::Type::getInt8PtrTy(Context);
Rafael Espindolacc111b22013-04-24 17:54:35 +0000415 std::vector<Constant*> asmUsed2;
Rafael Espindolab7c0b4a2013-09-04 20:08:46 +0000416 for (SmallPtrSet<GlobalValue*, 16>::const_iterator i = AsmUsed.begin(),
417 e = AsmUsed.end(); i !=e; ++i) {
Rafael Espindolacc111b22013-04-24 17:54:35 +0000418 GlobalValue *GV = *i;
419 Constant *c = ConstantExpr::getBitCast(GV, i8PTy);
420 asmUsed2.push_back(c);
421 }
422
423 llvm::ArrayType *ATy = llvm::ArrayType::get(i8PTy, asmUsed2.size());
424 LLVMCompilerUsed =
425 new llvm::GlobalVariable(*mergedModule, ATy, false,
426 llvm::GlobalValue::AppendingLinkage,
427 llvm::ConstantArray::get(ATy, asmUsed2),
428 "llvm.compiler.used");
429
430 LLVMCompilerUsed->setSection("llvm.metadata");
Chris Lattner2eff5052010-03-12 18:44:54 +0000431 }
Rafael Espindola1e49a6d2011-03-02 04:14:42 +0000432
Rafael Espindola282a4702013-10-31 20:51:58 +0000433 passes.add(createInternalizePass(MustPreserveList));
Rafael Espindola1e49a6d2011-03-02 04:14:42 +0000434
Chris Lattner2eff5052010-03-12 18:44:54 +0000435 // apply scope restrictions
436 passes.run(*mergedModule);
Bill Wendling39d942b2012-03-31 10:50:14 +0000437
Rafael Espindolac80c9692013-09-04 17:44:24 +0000438 ScopeRestrictionsDone = true;
Nick Kledzik07b4a622008-02-26 20:26:43 +0000439}
440
Nick Kledzik07b4a622008-02-26 20:26:43 +0000441/// Optimize merged modules using various IPO passes
Chris Lattnerf200a0a2011-05-22 00:20:07 +0000442bool LTOCodeGenerator::generateObjectFile(raw_ostream &out,
Rafael Espindola0b385c72013-09-30 16:39:19 +0000443 bool DisableOpt,
444 bool DisableInline,
445 bool DisableGVNLoadPRE,
Chris Lattnerf200a0a2011-05-22 00:20:07 +0000446 std::string &errMsg) {
Shuxin Yang95866fa2013-08-06 21:51:21 +0000447 if (!this->determineTarget(errMsg))
448 return false;
Nick Kledzik07b4a622008-02-26 20:26:43 +0000449
Rafael Espindolac80c9692013-09-04 17:44:24 +0000450 Module *mergedModule = Linker.getModule();
Nick Kledzik07b4a622008-02-26 20:26:43 +0000451
Bill Wendlingf44b2a22013-05-23 21:21:50 +0000452 // Mark which symbols can not be internalized
Bill Wendling383fda22012-04-09 22:18:01 +0000453 this->applyScopeRestrictions();
454
Bill Wendling0e1824c2012-03-31 11:15:43 +0000455 // Instantiate the pass manager to organize the passes.
456 PassManager passes;
Nick Kledzik07b4a622008-02-26 20:26:43 +0000457
Bill Wendling0e1824c2012-03-31 11:15:43 +0000458 // Start off with a verification pass.
459 passes.add(createVerifierPass());
Nick Kledzik07b4a622008-02-26 20:26:43 +0000460
Micah Villmow9cfc13d2012-10-08 16:39:34 +0000461 // Add an appropriate DataLayout instance for this module...
Rafael Espindolac80c9692013-09-04 17:44:24 +0000462 passes.add(new DataLayout(*TargetMach->getDataLayout()));
Yi Jiang53823be2013-12-12 01:37:39 +0000463
464 // Add appropriate TargetLibraryInfo for this module.
465 passes.add(new TargetLibraryInfo(Triple(TargetMach->getTargetTriple())));
466
Rafael Espindolac80c9692013-09-04 17:44:24 +0000467 TargetMach->addAnalysisPasses(passes);
Bill Wendling39d942b2012-03-31 10:50:14 +0000468
Rafael Espindola0ecb8fa2012-04-16 10:58:38 +0000469 // Enabling internalize here would use its AllButMain variant. It
470 // keeps only main if it exists and does nothing for libraries. Instead
471 // we create the pass ourselves with the symbol list provided by the linker.
Bill Wendlingf44b2a22013-05-23 21:21:50 +0000472 if (!DisableOpt)
Bill Wendlingc7e0a042013-02-28 14:11:10 +0000473 PassManagerBuilder().populateLTOPassManager(passes,
Bill Wendling4a8fc8f2012-12-10 21:33:45 +0000474 /*Internalize=*/false,
Bill Wendling932b9922012-04-02 22:16:50 +0000475 !DisableInline,
476 DisableGVNLoadPRE);
Nick Kledzik07b4a622008-02-26 20:26:43 +0000477
Bill Wendling0e1824c2012-03-31 11:15:43 +0000478 // Make sure everything is still good.
479 passes.add(createVerifierPass());
Nick Kledzik07b4a622008-02-26 20:26:43 +0000480
Lang Hamesdfa3f8f2013-03-13 21:18:46 +0000481 PassManager codeGenPasses;
Nick Kledzik07b4a622008-02-26 20:26:43 +0000482
Rafael Espindolac80c9692013-09-04 17:44:24 +0000483 codeGenPasses.add(new DataLayout(*TargetMach->getDataLayout()));
484 TargetMach->addAnalysisPasses(codeGenPasses);
Nick Kledzik07b4a622008-02-26 20:26:43 +0000485
Bill Wendling0e1824c2012-03-31 11:15:43 +0000486 formatted_raw_ostream Out(out);
Dan Gohmana2233f22010-09-01 14:20:41 +0000487
Bob Wilsonf36f15f2013-03-29 23:28:55 +0000488 // If the bitcode files contain ARC code and were compiled with optimization,
489 // the ObjCARCContractPass must be run, so do it unconditionally here.
490 codeGenPasses.add(createObjCARCContractPass());
491
Rafael Espindolac80c9692013-09-04 17:44:24 +0000492 if (TargetMach->addPassesToEmitFile(codeGenPasses, Out,
493 TargetMachine::CGFT_ObjectFile)) {
Bill Wendling0e1824c2012-03-31 11:15:43 +0000494 errMsg = "target file type not supported";
Shuxin Yang95866fa2013-08-06 21:51:21 +0000495 return false;
Bill Wendling0e1824c2012-03-31 11:15:43 +0000496 }
Nick Kledzik07b4a622008-02-26 20:26:43 +0000497
Bill Wendling0e1824c2012-03-31 11:15:43 +0000498 // Run our queue of passes all at once now, efficiently.
499 passes.run(*mergedModule);
Nick Kledzik07b4a622008-02-26 20:26:43 +0000500
Bill Wendling0e1824c2012-03-31 11:15:43 +0000501 // Run the code generator, and write assembly file
Lang Hamesdfa3f8f2013-03-13 21:18:46 +0000502 codeGenPasses.run(*mergedModule);
Nick Lewyckyfd6a2492009-07-26 22:16:39 +0000503
Shuxin Yang95866fa2013-08-06 21:51:21 +0000504 return true;
Nick Kledzik07b4a622008-02-26 20:26:43 +0000505}
506
Bill Wendling534a6582012-03-31 10:49:43 +0000507/// setCodeGenDebugOptions - Set codegen debugging options to aid in debugging
508/// LTO problems.
509void LTOCodeGenerator::setCodeGenDebugOptions(const char *options) {
510 for (std::pair<StringRef, StringRef> o = getToken(options);
511 !o.first.empty(); o = getToken(o.second)) {
512 // ParseCommandLineOptions() expects argv[0] to be program name. Lazily add
513 // that.
Rafael Espindolac80c9692013-09-04 17:44:24 +0000514 if (CodegenOptions.empty())
Peter Collingbourne4ccf0f12013-09-24 23:52:22 +0000515 CodegenOptions.push_back(strdup("libLLVMLTO"));
Rafael Espindolac80c9692013-09-04 17:44:24 +0000516 CodegenOptions.push_back(strdup(o.first.str().c_str()));
Bill Wendling534a6582012-03-31 10:49:43 +0000517 }
Nick Kledzikc2323472008-07-08 21:14:10 +0000518}
Rafael Espindolaefa02d52013-10-02 14:36:23 +0000519
520void LTOCodeGenerator::parseCodeGenDebugOptions() {
521 // if options were requested, set them
522 if (!CodegenOptions.empty())
523 cl::ParseCommandLineOptions(CodegenOptions.size(),
524 const_cast<char **>(&CodegenOptions[0]));
525}