blob: daeb9648e3062a0e16c47838410b65a60ff5b5f5 [file] [log] [blame]
Nick Kledzik77595fc2008-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 Wendling76b13ed2012-03-31 10:50:14 +00007//
Nick Kledzik77595fc2008-02-26 20:26:43 +00008//===----------------------------------------------------------------------===//
9//
Bill Wendling76b13ed2012-03-31 10:50:14 +000010// This file implements the Link Time Optimization library. This library is
Nick Kledzik77595fc2008-02-26 20:26:43 +000011// intended to be used by linker to optimize code at link time.
12//
13//===----------------------------------------------------------------------===//
14
Nick Kledzikef194ed2008-02-27 22:25:36 +000015#include "LTOCodeGenerator.h"
Bill Wendlingab53bc72012-03-31 11:10:35 +000016#include "LTOModule.h"
Chandler Carruthf010c462012-12-04 10:44:52 +000017#include "llvm/ADT/StringExtras.h"
Nick Lewycky8189d402009-06-17 06:52:10 +000018#include "llvm/Analysis/Passes.h"
Rafael Espindolac684e832011-08-02 21:50:27 +000019#include "llvm/Analysis/Verifier.h"
Nick Kledzik77595fc2008-02-26 20:26:43 +000020#include "llvm/Bitcode/ReaderWriter.h"
Bill Wendlingc94c5622012-03-31 11:15:43 +000021#include "llvm/Config/config.h"
Chandler Carruth0b8c9a82013-01-02 11:36:10 +000022#include "llvm/IR/Constants.h"
23#include "llvm/IR/DataLayout.h"
24#include "llvm/IR/DerivedTypes.h"
25#include "llvm/IR/LLVMContext.h"
26#include "llvm/IR/Module.h"
Shuxin Yang8945f752013-07-22 18:40:34 +000027#include "llvm/InitializePasses.h"
Chandler Carruthf010c462012-12-04 10:44:52 +000028#include "llvm/Linker.h"
Chris Lattner5ef31a02010-03-12 18:44:54 +000029#include "llvm/MC/MCAsmInfo.h"
30#include "llvm/MC/MCContext.h"
Evan Chengab8be962011-06-29 01:14:12 +000031#include "llvm/MC/SubtargetFeature.h"
Chandler Carruthf010c462012-12-04 10:44:52 +000032#include "llvm/PassManager.h"
Nick Kledzik920ae982008-07-08 21:14:10 +000033#include "llvm/Support/CommandLine.h"
Rafael Espindola68c0efa2013-06-17 18:05:35 +000034#include "llvm/Support/FileSystem.h"
David Greene71847812009-07-14 20:18:05 +000035#include "llvm/Support/FormattedStream.h"
Michael J. Spencer3cc52ea2010-11-29 18:47:54 +000036#include "llvm/Support/Host.h"
Chandler Carruthf010c462012-12-04 10:44:52 +000037#include "llvm/Support/MemoryBuffer.h"
Michael J. Spencer3cc52ea2010-11-29 18:47:54 +000038#include "llvm/Support/Signals.h"
Evan Cheng3e74d6f2011-08-24 18:08:43 +000039#include "llvm/Support/TargetRegistry.h"
40#include "llvm/Support/TargetSelect.h"
Chandler Carruthf010c462012-12-04 10:44:52 +000041#include "llvm/Support/ToolOutputFile.h"
Michael J. Spencerf2f516f2010-12-09 18:06:07 +000042#include "llvm/Support/system_error.h"
Chandler Carruthf010c462012-12-04 10:44:52 +000043#include "llvm/Target/Mangler.h"
44#include "llvm/Target/TargetMachine.h"
45#include "llvm/Target/TargetOptions.h"
46#include "llvm/Target/TargetRegisterInfo.h"
47#include "llvm/Transforms/IPO.h"
48#include "llvm/Transforms/IPO/PassManagerBuilder.h"
Bob Wilsond6965442013-03-29 23:28:55 +000049#include "llvm/Transforms/ObjCARC.h"
Shuxin Yang67d135a2013-08-12 18:29:43 +000050using namespace llvm;
Shuxin Yang67d135a2013-08-12 18:29:43 +000051
Bill Wendling9ac0aaa2012-08-06 21:34:54 +000052static cl::opt<bool>
Bill Wendling6303b662013-02-28 14:11:10 +000053DisableOpt("disable-opt", cl::init(false),
54 cl::desc("Do not run any optimization passes"));
55
56static cl::opt<bool>
Bill Wendling9ac0aaa2012-08-06 21:34:54 +000057DisableInline("disable-inlining", cl::init(false),
Nick Kledzik920ae982008-07-08 21:14:10 +000058 cl::desc("Do not run the inliner pass"));
Nick Kledzik77595fc2008-02-26 20:26:43 +000059
Bill Wendling9ac0aaa2012-08-06 21:34:54 +000060static cl::opt<bool>
61DisableGVNLoadPRE("disable-gvn-loadpre", cl::init(false),
Bill Wendling3197b442012-04-02 22:16:50 +000062 cl::desc("Do not run the GVN load PRE pass"));
63
Bill Wendlingcaf71d42012-03-31 10:49:43 +000064const char* LTOCodeGenerator::getVersionString() {
Nick Kledzik77595fc2008-02-26 20:26:43 +000065#ifdef LLVM_VERSION_INFO
Bill Wendlingcaf71d42012-03-31 10:49:43 +000066 return PACKAGE_NAME " version " PACKAGE_VERSION ", " LLVM_VERSION_INFO;
Nick Kledzik77595fc2008-02-26 20:26:43 +000067#else
Bill Wendlingcaf71d42012-03-31 10:49:43 +000068 return PACKAGE_NAME " version " PACKAGE_VERSION;
Nick Kledzik77595fc2008-02-26 20:26:43 +000069#endif
70}
71
Bill Wendling76b13ed2012-03-31 10:50:14 +000072LTOCodeGenerator::LTOCodeGenerator()
Bill Wendlingc94c5622012-03-31 11:15:43 +000073 : _context(getGlobalContext()),
Rafael Espindola10519372013-05-04 02:43:00 +000074 _linker(new Module("ld-temp.o", _context)), _target(NULL),
Bill Wendlingc94c5622012-03-31 11:15:43 +000075 _emitDwarfDebugInfo(false), _scopeRestrictionsDone(false),
Bill Wendling50f31832012-12-10 21:33:45 +000076 _codeModel(LTO_CODEGEN_PIC_MODEL_DYNAMIC),
Shuxin Yange3427a52013-08-27 00:03:23 +000077 _nativeObjectFile(NULL), ObjBufVect(0) {
Bill Wendlingc94c5622012-03-31 11:15:43 +000078 InitializeAllTargets();
79 InitializeAllTargetMCs();
80 InitializeAllAsmPrinters();
Shuxin Yang8945f752013-07-22 18:40:34 +000081 initializeLTOPasses();
Nick Kledzik77595fc2008-02-26 20:26:43 +000082}
83
Bill Wendlingcaf71d42012-03-31 10:49:43 +000084LTOCodeGenerator::~LTOCodeGenerator() {
85 delete _target;
86 delete _nativeObjectFile;
Rafael Espindola10519372013-05-04 02:43:00 +000087 delete _linker.getModule();
Shuxin Yange3427a52013-08-27 00:03:23 +000088 delete[] ObjBufVect;
Bill Wendlingcaf71d42012-03-31 10:49:43 +000089
Bill Wendlingf2cc2ee2012-03-31 10:51:45 +000090 for (std::vector<char*>::iterator I = _codegenOptions.begin(),
Bill Wendlingcaf71d42012-03-31 10:49:43 +000091 E = _codegenOptions.end(); I != E; ++I)
92 free(*I);
Nick Kledzik77595fc2008-02-26 20:26:43 +000093}
94
Shuxin Yang8945f752013-07-22 18:40:34 +000095// Initialize LTO passes. Please keep this funciton in sync with
Shuxin Yangc679d6b2013-07-23 06:44:34 +000096// PassManagerBuilder::populateLTOPassManager(), and make sure all LTO
Shuxin Yang8945f752013-07-22 18:40:34 +000097// passes are initialized.
98//
99void LTOCodeGenerator::initializeLTOPasses() {
100 PassRegistry &R = *PassRegistry::getPassRegistry();
101
102 initializeInternalizePassPass(R);
103 initializeIPSCCPPass(R);
104 initializeGlobalOptPass(R);
105 initializeConstantMergePass(R);
106 initializeDAHPass(R);
107 initializeInstCombinerPass(R);
108 initializeSimpleInlinerPass(R);
109 initializePruneEHPass(R);
110 initializeGlobalDCEPass(R);
111 initializeArgPromotionPass(R);
112 initializeJumpThreadingPass(R);
113 initializeSROAPass(R);
114 initializeSROA_DTPass(R);
115 initializeSROA_SSAUpPass(R);
116 initializeFunctionAttrsPass(R);
117 initializeGlobalsModRefPass(R);
118 initializeLICMPass(R);
119 initializeGVNPass(R);
120 initializeMemCpyOptPass(R);
121 initializeDCEPass(R);
Tom Stellard01d72032013-08-06 02:43:45 +0000122 initializeCFGSimplifyPassPass(R);
Shuxin Yang8945f752013-07-22 18:40:34 +0000123}
124
Bill Wendlingc94c5622012-03-31 11:15:43 +0000125bool LTOCodeGenerator::addModule(LTOModule* mod, std::string& errMsg) {
Rafael Espindolafca88632013-05-04 03:06:50 +0000126 bool ret = _linker.linkInModule(mod->getLLVVMModule(), &errMsg);
Rafael Espindola38c4e532011-03-02 04:14:42 +0000127
128 const std::vector<const char*> &undefs = mod->getAsmUndefinedRefs();
129 for (int i = 0, e = undefs.size(); i != e; ++i)
130 _asmUndefinedRefs[undefs[i]] = 1;
131
Shuxin Yang235089b2013-08-07 05:19:23 +0000132 return !ret;
Nick Kledzik77595fc2008-02-26 20:26:43 +0000133}
Bill Wendling76b13ed2012-03-31 10:50:14 +0000134
Shuxin Yang235089b2013-08-07 05:19:23 +0000135void LTOCodeGenerator::setDebugInfo(lto_debug_model debug) {
Bill Wendlingc94c5622012-03-31 11:15:43 +0000136 switch (debug) {
137 case LTO_DEBUG_MODEL_NONE:
138 _emitDwarfDebugInfo = false;
Shuxin Yang235089b2013-08-07 05:19:23 +0000139 return;
Nick Kledzik77595fc2008-02-26 20:26:43 +0000140
Bill Wendlingc94c5622012-03-31 11:15:43 +0000141 case LTO_DEBUG_MODEL_DWARF:
142 _emitDwarfDebugInfo = true;
Shuxin Yang235089b2013-08-07 05:19:23 +0000143 return;
Bill Wendlingc94c5622012-03-31 11:15:43 +0000144 }
145 llvm_unreachable("Unknown debug format!");
Nick Kledzik77595fc2008-02-26 20:26:43 +0000146}
147
Shuxin Yang235089b2013-08-07 05:19:23 +0000148void LTOCodeGenerator::setCodePICModel(lto_codegen_model model) {
Bill Wendlingc94c5622012-03-31 11:15:43 +0000149 switch (model) {
150 case LTO_CODEGEN_PIC_MODEL_STATIC:
151 case LTO_CODEGEN_PIC_MODEL_DYNAMIC:
152 case LTO_CODEGEN_PIC_MODEL_DYNAMIC_NO_PIC:
153 _codeModel = model;
Shuxin Yang235089b2013-08-07 05:19:23 +0000154 return;
Bill Wendlingc94c5622012-03-31 11:15:43 +0000155 }
156 llvm_unreachable("Unknown PIC model!");
Nick Kledzik77595fc2008-02-26 20:26:43 +0000157}
158
Chris Lattnerb515d752009-08-23 07:49:08 +0000159bool LTOCodeGenerator::writeMergedModules(const char *path,
160 std::string &errMsg) {
Shuxin Yang08809392013-08-06 21:51:21 +0000161 if (!determineTarget(errMsg))
Shuxin Yang235089b2013-08-07 05:19:23 +0000162 return false;
Nick Kledzik77595fc2008-02-26 20:26:43 +0000163
Bill Wendling6ba2ed52013-08-08 23:51:04 +0000164 // mark which symbols can not be internalized
165 applyScopeRestrictions();
Nick Kledzik77595fc2008-02-26 20:26:43 +0000166
Chris Lattnerb515d752009-08-23 07:49:08 +0000167 // create output file
168 std::string ErrInfo;
Rafael Espindolac1b49b52013-07-16 19:44:17 +0000169 tool_output_file Out(path, ErrInfo, sys::fs::F_Binary);
Chris Lattnerb515d752009-08-23 07:49:08 +0000170 if (!ErrInfo.empty()) {
171 errMsg = "could not open bitcode file for writing: ";
172 errMsg += path;
Shuxin Yang235089b2013-08-07 05:19:23 +0000173 return false;
Chris Lattnerb515d752009-08-23 07:49:08 +0000174 }
Bill Wendling76b13ed2012-03-31 10:50:14 +0000175
Chris Lattnerb515d752009-08-23 07:49:08 +0000176 // write bitcode to it
Dan Gohmand4c45432010-09-01 14:20:41 +0000177 WriteBitcodeToFile(_linker.getModule(), Out.os());
178 Out.os().close();
Dan Gohman4b7416b2010-05-27 20:19:47 +0000179
Dan Gohmand4c45432010-09-01 14:20:41 +0000180 if (Out.os().has_error()) {
Chris Lattnerb515d752009-08-23 07:49:08 +0000181 errMsg = "could not write bitcode file: ";
182 errMsg += path;
Dan Gohmand4c45432010-09-01 14:20:41 +0000183 Out.os().clear_error();
Shuxin Yang235089b2013-08-07 05:19:23 +0000184 return false;
Chris Lattnerb515d752009-08-23 07:49:08 +0000185 }
Bill Wendling76b13ed2012-03-31 10:50:14 +0000186
Dan Gohmanf2914012010-08-20 16:59:15 +0000187 Out.keep();
Shuxin Yang235089b2013-08-07 05:19:23 +0000188 return true;
Nick Kledzik77595fc2008-02-26 20:26:43 +0000189}
190
Shuxin Yangcfaa6362013-08-12 21:07:31 +0000191bool LTOCodeGenerator::compile_to_file(const char** name, std::string& errMsg) {
192 // make unique temp .o file to put generated object file
193 SmallString<128> Filename;
194 int FD;
195 error_code EC = sys::fs::createTemporaryFile("lto-llvm", "o", FD, Filename);
196 if (EC) {
197 errMsg = EC.message();
Shuxin Yang235089b2013-08-07 05:19:23 +0000198 return false;
Shuxin Yangcfaa6362013-08-12 21:07:31 +0000199 }
Rafael Espindola6421a882011-03-22 20:57:13 +0000200
Shuxin Yangcfaa6362013-08-12 21:07:31 +0000201 // generate object file
202 tool_output_file objFile(Filename.c_str(), FD);
Bill Wendlingc94c5622012-03-31 11:15:43 +0000203
Shuxin Yangcfaa6362013-08-12 21:07:31 +0000204 bool genResult = generateObjectFile(objFile.os(), errMsg);
205 objFile.os().close();
206 if (objFile.os().has_error()) {
207 objFile.os().clear_error();
208 sys::fs::remove(Twine(Filename));
Shuxin Yang235089b2013-08-07 05:19:23 +0000209 return false;
Shuxin Yangcfaa6362013-08-12 21:07:31 +0000210 }
Bill Wendlingc94c5622012-03-31 11:15:43 +0000211
Shuxin Yangcfaa6362013-08-12 21:07:31 +0000212 objFile.keep();
213 if (!genResult) {
214 sys::fs::remove(Twine(Filename));
Shuxin Yang235089b2013-08-07 05:19:23 +0000215 return false;
Shuxin Yangcfaa6362013-08-12 21:07:31 +0000216 }
Rafael Espindola6421a882011-03-22 20:57:13 +0000217
Shuxin Yangcfaa6362013-08-12 21:07:31 +0000218 _nativeObjectPath = Filename.c_str();
219 *name = _nativeObjectPath.c_str();
Shuxin Yang235089b2013-08-07 05:19:23 +0000220 return true;
Rafael Espindola6421a882011-03-22 20:57:13 +0000221}
222
Bill Wendlingc94c5622012-03-31 11:15:43 +0000223const void* LTOCodeGenerator::compile(size_t* length, std::string& errMsg) {
Rafael Espindola6421a882011-03-22 20:57:13 +0000224 const char *name;
Shuxin Yang235089b2013-08-07 05:19:23 +0000225 if (!compile_to_file(&name, errMsg))
Rafael Espindola6421a882011-03-22 20:57:13 +0000226 return NULL;
Nick Kledzik77595fc2008-02-26 20:26:43 +0000227
Rafael Espindola6421a882011-03-22 20:57:13 +0000228 // remove old buffer if compile() called twice
229 delete _nativeObjectFile;
Nick Kledzikef194ed2008-02-27 22:25:36 +0000230
Rafael Espindola6421a882011-03-22 20:57:13 +0000231 // read .o file into memory buffer
232 OwningPtr<MemoryBuffer> BuffPtr;
233 if (error_code ec = MemoryBuffer::getFile(name, BuffPtr, -1, false)) {
234 errMsg = ec.message();
Shuxin Yangcfaa6362013-08-12 21:07:31 +0000235 sys::fs::remove(_nativeObjectPath);
236 return NULL;
Rafael Espindola6421a882011-03-22 20:57:13 +0000237 }
Shuxin Yangcfaa6362013-08-12 21:07:31 +0000238 _nativeObjectFile = BuffPtr.take();
Rafael Espindolae9efea12011-02-24 21:04:06 +0000239
Shuxin Yangcfaa6362013-08-12 21:07:31 +0000240 // remove temp files
241 sys::fs::remove(_nativeObjectPath);
Rafael Espindolae9efea12011-02-24 21:04:06 +0000242
Shuxin Yangcfaa6362013-08-12 21:07:31 +0000243 // return buffer, unless error
244 if (_nativeObjectFile == NULL)
245 return NULL;
246 *length = _nativeObjectFile->getBufferSize();
247 return _nativeObjectFile->getBufferStart();
Nick Kledzik77595fc2008-02-26 20:26:43 +0000248}
249
Shuxin Yange3427a52013-08-27 00:03:23 +0000250// Currently compile() and compile_parallel() have no difference.
251NativeObjectFile *LTOCodeGenerator::compile_parallel(size_t *count,
252 std::string &ErrMsg) {
253 assert(ObjBufVect == 0 && "Should be NULL");
254
255 size_t Len;
256 const void *Buf = compile(&Len, ErrMsg);
257 if (!Buf)
258 return 0;
259
260 *count = 1;
261 ObjBufVect = new NativeObjectFile[1];
262 ObjBufVect[0].content = Buf;
263 ObjBufVect[0].length = Len;
264 return ObjBufVect;
265}
266
Bill Wendling8c18a6f2013-05-23 21:21:50 +0000267bool LTOCodeGenerator::determineTarget(std::string &errMsg) {
Bill Wendling0ca36af2012-08-08 22:03:50 +0000268 if (_target != NULL)
Shuxin Yang08809392013-08-06 21:51:21 +0000269 return true;
Daniel Dunbar3c2d4bf2009-08-03 04:03:51 +0000270
Bill Wendling8c18a6f2013-05-23 21:21:50 +0000271 // if options were requested, set them
Shuxin Yangcfaa6362013-08-12 21:07:31 +0000272 if (!_codegenOptions.empty())
273 cl::ParseCommandLineOptions(_codegenOptions.size(),
274 const_cast<char **>(&_codegenOptions[0]));
Bill Wendling8c18a6f2013-05-23 21:21:50 +0000275
Bob Wilson47ed8a12012-10-12 17:39:25 +0000276 std::string TripleStr = _linker.getModule()->getTargetTriple();
277 if (TripleStr.empty())
278 TripleStr = sys::getDefaultTargetTriple();
279 llvm::Triple Triple(TripleStr);
Bill Wendling604a8182008-06-18 06:35:30 +0000280
Bill Wendlingeda3fc62012-08-06 22:52:45 +0000281 // create target machine from info for merged modules
Bob Wilson47ed8a12012-10-12 17:39:25 +0000282 const Target *march = TargetRegistry::lookupTarget(TripleStr, errMsg);
Bill Wendling0ca36af2012-08-08 22:03:50 +0000283 if (march == NULL)
Shuxin Yang08809392013-08-06 21:51:21 +0000284 return false;
Bill Wendlingc94c5622012-03-31 11:15:43 +0000285
Bill Wendlingeda3fc62012-08-06 22:52:45 +0000286 // The relocation model is actually a static member of TargetMachine and
287 // needs to be set before the TargetMachine is instantiated.
288 Reloc::Model RelocModel = Reloc::Default;
Bill Wendling0ca36af2012-08-08 22:03:50 +0000289 switch (_codeModel) {
Bill Wendlingeda3fc62012-08-06 22:52:45 +0000290 case LTO_CODEGEN_PIC_MODEL_STATIC:
291 RelocModel = Reloc::Static;
292 break;
293 case LTO_CODEGEN_PIC_MODEL_DYNAMIC:
294 RelocModel = Reloc::PIC_;
295 break;
296 case LTO_CODEGEN_PIC_MODEL_DYNAMIC_NO_PIC:
297 RelocModel = Reloc::DynamicNoPIC;
298 break;
Bill Wendlingc94c5622012-03-31 11:15:43 +0000299 }
Bill Wendlingeda3fc62012-08-06 22:52:45 +0000300
301 // construct LTOModule, hand over ownership of module and target
302 SubtargetFeatures Features;
Bob Wilson47ed8a12012-10-12 17:39:25 +0000303 Features.getDefaultSubtargetFeatures(Triple);
Bill Wendlingeda3fc62012-08-06 22:52:45 +0000304 std::string FeatureStr = Features.getString();
Bob Wilson47ed8a12012-10-12 17:39:25 +0000305 // Set a default CPU for Darwin triples.
306 if (_mCpu.empty() && Triple.isOSDarwin()) {
307 if (Triple.getArch() == llvm::Triple::x86_64)
308 _mCpu = "core2";
309 else if (Triple.getArch() == llvm::Triple::x86)
310 _mCpu = "yonah";
311 }
Bill Wendlingeda3fc62012-08-06 22:52:45 +0000312 TargetOptions Options;
313 LTOModule::getTargetOptions(Options);
Bob Wilson47ed8a12012-10-12 17:39:25 +0000314 _target = march->createTargetMachine(TripleStr, _mCpu, FeatureStr, Options,
Bill Wendlingeda3fc62012-08-06 22:52:45 +0000315 RelocModel, CodeModel::Default,
316 CodeGenOpt::Aggressive);
Shuxin Yang08809392013-08-06 21:51:21 +0000317 return true;
Nick Kledzik77595fc2008-02-26 20:26:43 +0000318}
319
Bill Wendlingc94c5622012-03-31 11:15:43 +0000320void LTOCodeGenerator::
321applyRestriction(GlobalValue &GV,
322 std::vector<const char*> &mustPreserveList,
323 SmallPtrSet<GlobalValue*, 8> &asmUsed,
324 Mangler &mangler) {
Rafael Espindola38c4e532011-03-02 04:14:42 +0000325 SmallString<64> Buffer;
326 mangler.getNameWithPrefix(Buffer, &GV, false);
327
328 if (GV.isDeclaration())
329 return;
330 if (_mustPreserveSymbols.count(Buffer))
331 mustPreserveList.push_back(GV.getName().data());
332 if (_asmUndefinedRefs.count(Buffer))
333 asmUsed.insert(&GV);
334}
335
336static void findUsedValues(GlobalVariable *LLVMUsed,
337 SmallPtrSet<GlobalValue*, 8> &UsedValues) {
338 if (LLVMUsed == 0) return;
339
Rafael Espindolad4ee3922013-04-24 17:54:35 +0000340 ConstantArray *Inits = cast<ConstantArray>(LLVMUsed->getInitializer());
Rafael Espindola38c4e532011-03-02 04:14:42 +0000341 for (unsigned i = 0, e = Inits->getNumOperands(); i != e; ++i)
Bill Wendling76b13ed2012-03-31 10:50:14 +0000342 if (GlobalValue *GV =
Bill Wendlingc94c5622012-03-31 11:15:43 +0000343 dyn_cast<GlobalValue>(Inits->getOperand(i)->stripPointerCasts()))
Rafael Espindola38c4e532011-03-02 04:14:42 +0000344 UsedValues.insert(GV);
345}
346
Chris Lattner5ef31a02010-03-12 18:44:54 +0000347void LTOCodeGenerator::applyScopeRestrictions() {
348 if (_scopeRestrictionsDone) return;
349 Module *mergedModule = _linker.getModule();
Nick Kledzik77595fc2008-02-26 20:26:43 +0000350
Chris Lattner5ef31a02010-03-12 18:44:54 +0000351 // Start off with a verification pass.
352 PassManager passes;
353 passes.add(createVerifierPass());
Nick Kledzik77595fc2008-02-26 20:26:43 +0000354
Bill Wendling76b13ed2012-03-31 10:50:14 +0000355 // mark which symbols can not be internalized
Bill Wendling99cb6222013-06-18 07:20:20 +0000356 MCContext Context(_target->getMCAsmInfo(), _target->getRegisterInfo(), NULL);
Bill Wendlingcc5a8822013-05-29 20:37:19 +0000357 Mangler mangler(Context, _target);
Rafael Espindola38c4e532011-03-02 04:14:42 +0000358 std::vector<const char*> mustPreserveList;
359 SmallPtrSet<GlobalValue*, 8> asmUsed;
360
361 for (Module::iterator f = mergedModule->begin(),
362 e = mergedModule->end(); f != e; ++f)
363 applyRestriction(*f, mustPreserveList, asmUsed, mangler);
Bill Wendling76b13ed2012-03-31 10:50:14 +0000364 for (Module::global_iterator v = mergedModule->global_begin(),
Rafael Espindola38c4e532011-03-02 04:14:42 +0000365 e = mergedModule->global_end(); v != e; ++v)
366 applyRestriction(*v, mustPreserveList, asmUsed, mangler);
367 for (Module::alias_iterator a = mergedModule->alias_begin(),
368 e = mergedModule->alias_end(); a != e; ++a)
369 applyRestriction(*a, mustPreserveList, asmUsed, mangler);
370
371 GlobalVariable *LLVMCompilerUsed =
372 mergedModule->getGlobalVariable("llvm.compiler.used");
373 findUsedValues(LLVMCompilerUsed, asmUsed);
374 if (LLVMCompilerUsed)
375 LLVMCompilerUsed->eraseFromParent();
376
Rafael Espindolad4ee3922013-04-24 17:54:35 +0000377 if (!asmUsed.empty()) {
378 llvm::Type *i8PTy = llvm::Type::getInt8PtrTy(_context);
379 std::vector<Constant*> asmUsed2;
380 for (SmallPtrSet<GlobalValue*, 16>::const_iterator i = asmUsed.begin(),
381 e = asmUsed.end(); i !=e; ++i) {
382 GlobalValue *GV = *i;
383 Constant *c = ConstantExpr::getBitCast(GV, i8PTy);
384 asmUsed2.push_back(c);
385 }
386
387 llvm::ArrayType *ATy = llvm::ArrayType::get(i8PTy, asmUsed2.size());
388 LLVMCompilerUsed =
389 new llvm::GlobalVariable(*mergedModule, ATy, false,
390 llvm::GlobalValue::AppendingLinkage,
391 llvm::ConstantArray::get(ATy, asmUsed2),
392 "llvm.compiler.used");
393
394 LLVMCompilerUsed->setSection("llvm.metadata");
Chris Lattner5ef31a02010-03-12 18:44:54 +0000395 }
Rafael Espindola38c4e532011-03-02 04:14:42 +0000396
Bill Wendling50f31832012-12-10 21:33:45 +0000397 passes.add(createInternalizePass(mustPreserveList));
Rafael Espindola38c4e532011-03-02 04:14:42 +0000398
Chris Lattner5ef31a02010-03-12 18:44:54 +0000399 // apply scope restrictions
400 passes.run(*mergedModule);
Bill Wendling76b13ed2012-03-31 10:50:14 +0000401
Chris Lattner5ef31a02010-03-12 18:44:54 +0000402 _scopeRestrictionsDone = true;
Nick Kledzik77595fc2008-02-26 20:26:43 +0000403}
404
Nick Kledzik77595fc2008-02-26 20:26:43 +0000405/// Optimize merged modules using various IPO passes
Chris Lattner817a01f2011-05-22 00:20:07 +0000406bool LTOCodeGenerator::generateObjectFile(raw_ostream &out,
407 std::string &errMsg) {
Shuxin Yang08809392013-08-06 21:51:21 +0000408 if (!this->determineTarget(errMsg))
409 return false;
Nick Kledzik77595fc2008-02-26 20:26:43 +0000410
Bill Wendlingc94c5622012-03-31 11:15:43 +0000411 Module* mergedModule = _linker.getModule();
Nick Kledzik77595fc2008-02-26 20:26:43 +0000412
Bill Wendling8c18a6f2013-05-23 21:21:50 +0000413 // Mark which symbols can not be internalized
Bill Wendling64d5b282012-04-09 22:18:01 +0000414 this->applyScopeRestrictions();
415
Bill Wendlingc94c5622012-03-31 11:15:43 +0000416 // Instantiate the pass manager to organize the passes.
417 PassManager passes;
Nick Kledzik77595fc2008-02-26 20:26:43 +0000418
Bill Wendlingc94c5622012-03-31 11:15:43 +0000419 // Start off with a verification pass.
420 passes.add(createVerifierPass());
Nick Kledzik77595fc2008-02-26 20:26:43 +0000421
Micah Villmow791cfc22012-10-08 16:39:34 +0000422 // Add an appropriate DataLayout instance for this module...
423 passes.add(new DataLayout(*_target->getDataLayout()));
Chandler Carruthaeef83c2013-01-07 01:37:14 +0000424 _target->addAnalysisPasses(passes);
Bill Wendling76b13ed2012-03-31 10:50:14 +0000425
Rafael Espindola4d2e9d92012-04-16 10:58:38 +0000426 // Enabling internalize here would use its AllButMain variant. It
427 // keeps only main if it exists and does nothing for libraries. Instead
428 // we create the pass ourselves with the symbol list provided by the linker.
Bill Wendling8c18a6f2013-05-23 21:21:50 +0000429 if (!DisableOpt)
Bill Wendling6303b662013-02-28 14:11:10 +0000430 PassManagerBuilder().populateLTOPassManager(passes,
Bill Wendling50f31832012-12-10 21:33:45 +0000431 /*Internalize=*/false,
Bill Wendling3197b442012-04-02 22:16:50 +0000432 !DisableInline,
433 DisableGVNLoadPRE);
Nick Kledzik77595fc2008-02-26 20:26:43 +0000434
Bill Wendlingc94c5622012-03-31 11:15:43 +0000435 // Make sure everything is still good.
436 passes.add(createVerifierPass());
Nick Kledzik77595fc2008-02-26 20:26:43 +0000437
Lang Hamesa991b252013-03-13 21:18:46 +0000438 PassManager codeGenPasses;
Nick Kledzik77595fc2008-02-26 20:26:43 +0000439
Lang Hamesa991b252013-03-13 21:18:46 +0000440 codeGenPasses.add(new DataLayout(*_target->getDataLayout()));
441 _target->addAnalysisPasses(codeGenPasses);
Nick Kledzik77595fc2008-02-26 20:26:43 +0000442
Bill Wendlingc94c5622012-03-31 11:15:43 +0000443 formatted_raw_ostream Out(out);
Dan Gohmand4c45432010-09-01 14:20:41 +0000444
Bob Wilsond6965442013-03-29 23:28:55 +0000445 // If the bitcode files contain ARC code and were compiled with optimization,
446 // the ObjCARCContractPass must be run, so do it unconditionally here.
447 codeGenPasses.add(createObjCARCContractPass());
448
Lang Hamesa991b252013-03-13 21:18:46 +0000449 if (_target->addPassesToEmitFile(codeGenPasses, Out,
David Blaikie4f56a302012-05-30 18:42:51 +0000450 TargetMachine::CGFT_ObjectFile)) {
Bill Wendlingc94c5622012-03-31 11:15:43 +0000451 errMsg = "target file type not supported";
Shuxin Yang08809392013-08-06 21:51:21 +0000452 return false;
Bill Wendlingc94c5622012-03-31 11:15:43 +0000453 }
Nick Kledzik77595fc2008-02-26 20:26:43 +0000454
Bill Wendlingc94c5622012-03-31 11:15:43 +0000455 // Run our queue of passes all at once now, efficiently.
456 passes.run(*mergedModule);
Nick Kledzik77595fc2008-02-26 20:26:43 +0000457
Bill Wendlingc94c5622012-03-31 11:15:43 +0000458 // Run the code generator, and write assembly file
Lang Hamesa991b252013-03-13 21:18:46 +0000459 codeGenPasses.run(*mergedModule);
Nick Lewyckyd42b58b2009-07-26 22:16:39 +0000460
Shuxin Yang08809392013-08-06 21:51:21 +0000461 return true;
Nick Kledzik77595fc2008-02-26 20:26:43 +0000462}
463
Bill Wendlingcaf71d42012-03-31 10:49:43 +0000464/// setCodeGenDebugOptions - Set codegen debugging options to aid in debugging
465/// LTO problems.
466void LTOCodeGenerator::setCodeGenDebugOptions(const char *options) {
467 for (std::pair<StringRef, StringRef> o = getToken(options);
468 !o.first.empty(); o = getToken(o.second)) {
469 // ParseCommandLineOptions() expects argv[0] to be program name. Lazily add
470 // that.
Bill Wendling0ca36af2012-08-08 22:03:50 +0000471 if (_codegenOptions.empty())
Bill Wendlingcaf71d42012-03-31 10:49:43 +0000472 _codegenOptions.push_back(strdup("libLTO"));
473 _codegenOptions.push_back(strdup(o.first.str().c_str()));
474 }
Nick Kledzik920ae982008-07-08 21:14:10 +0000475}