blob: 6739e067674a76b3da795de364b318cf6a7d552f [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.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the Link Time Optimization library. This library is
11// intended to be used by linker to optimize code at link time.
12//
13//===----------------------------------------------------------------------===//
14
Nick Kledzikef194ed2008-02-27 22:25:36 +000015#include "LTOModule.h"
16#include "LTOCodeGenerator.h"
17
Nick Kledzik77595fc2008-02-26 20:26:43 +000018#include "llvm/Constants.h"
19#include "llvm/DerivedTypes.h"
Nick Lewycky8189d402009-06-17 06:52:10 +000020#include "llvm/Linker.h"
Owen Anderson0e7a5462009-07-02 00:31:14 +000021#include "llvm/LLVMContext.h"
Nick Lewycky8189d402009-06-17 06:52:10 +000022#include "llvm/Module.h"
Nick Lewycky8189d402009-06-17 06:52:10 +000023#include "llvm/PassManager.h"
24#include "llvm/ADT/StringExtras.h"
Viktor Kutuzov51cdac02009-11-17 18:48:27 +000025#include "llvm/ADT/Triple.h"
Nick Lewycky8189d402009-06-17 06:52:10 +000026#include "llvm/Analysis/Passes.h"
Nick Kledzik77595fc2008-02-26 20:26:43 +000027#include "llvm/Bitcode/ReaderWriter.h"
Chris Lattner5ef31a02010-03-12 18:44:54 +000028#include "llvm/MC/MCAsmInfo.h"
29#include "llvm/MC/MCContext.h"
30#include "llvm/Target/Mangler.h"
31#include "llvm/Target/SubtargetFeature.h"
32#include "llvm/Target/TargetOptions.h"
33#include "llvm/Target/TargetData.h"
34#include "llvm/Target/TargetMachine.h"
35#include "llvm/Target/TargetRegistry.h"
36#include "llvm/Target/TargetSelect.h"
Nick Kledzik920ae982008-07-08 21:14:10 +000037#include "llvm/Support/CommandLine.h"
David Greene71847812009-07-14 20:18:05 +000038#include "llvm/Support/FormattedStream.h"
Nick Kledzik77595fc2008-02-26 20:26:43 +000039#include "llvm/Support/MemoryBuffer.h"
Daniel Dunbar006a0342009-06-03 21:06:14 +000040#include "llvm/Support/StandardPasses.h"
41#include "llvm/Support/SystemUtils.h"
Dan Gohman9f36c4e2010-10-07 20:48:46 +000042#include "llvm/Support/ToolOutputFile.h"
Michael J. Spencer3cc52ea2010-11-29 18:47:54 +000043#include "llvm/Support/Host.h"
44#include "llvm/Support/Program.h"
45#include "llvm/Support/Signals.h"
Michael J. Spencerf2f516f2010-12-09 18:06:07 +000046#include "llvm/Support/system_error.h"
Nick Kledzik77595fc2008-02-26 20:26:43 +000047#include "llvm/Config/config.h"
Nick Lewycky8189d402009-06-17 06:52:10 +000048#include <cstdlib>
Nick Kledzik77595fc2008-02-26 20:26:43 +000049#include <unistd.h>
Nick Kledzik77595fc2008-02-26 20:26:43 +000050#include <fcntl.h>
51
52
53using namespace llvm;
54
Nick Kledzik920ae982008-07-08 21:14:10 +000055static cl::opt<bool> DisableInline("disable-inlining",
56 cl::desc("Do not run the inliner pass"));
Nick Kledzik77595fc2008-02-26 20:26:43 +000057
58
59const char* LTOCodeGenerator::getVersionString()
60{
61#ifdef LLVM_VERSION_INFO
62 return PACKAGE_NAME " version " PACKAGE_VERSION ", " LLVM_VERSION_INFO;
63#else
64 return PACKAGE_NAME " version " PACKAGE_VERSION;
65#endif
66}
67
68
Owen Anderson0e7a5462009-07-02 00:31:14 +000069LTOCodeGenerator::LTOCodeGenerator()
70 : _context(getGlobalContext()),
Owen Anderson8b477ed2009-07-01 16:58:40 +000071 _linker("LinkTimeOptimizer", "ld-temp.o", _context), _target(NULL),
Nick Kledzik77595fc2008-02-26 20:26:43 +000072 _emitDwarfDebugInfo(false), _scopeRestrictionsDone(false),
Nick Kledzikef194ed2008-02-27 22:25:36 +000073 _codeModel(LTO_CODEGEN_PIC_MODEL_DYNAMIC),
Rafael Espindolae9efea12011-02-24 21:04:06 +000074 _nativeObjectFile(NULL)
Nick Kledzik77595fc2008-02-26 20:26:43 +000075{
Nick Lewyckyd42b58b2009-07-26 22:16:39 +000076 InitializeAllTargets();
77 InitializeAllAsmPrinters();
Nick Kledzik77595fc2008-02-26 20:26:43 +000078}
79
80LTOCodeGenerator::~LTOCodeGenerator()
81{
Nick Kledzikef194ed2008-02-27 22:25:36 +000082 delete _target;
83 delete _nativeObjectFile;
Nick Kledzik77595fc2008-02-26 20:26:43 +000084}
85
86
87
88bool LTOCodeGenerator::addModule(LTOModule* mod, std::string& errMsg)
89{
Rafael Espindola38c4e532011-03-02 04:14:42 +000090 bool ret = _linker.LinkInModule(mod->getLLVVMModule(), &errMsg);
91
92 const std::vector<const char*> &undefs = mod->getAsmUndefinedRefs();
93 for (int i = 0, e = undefs.size(); i != e; ++i)
94 _asmUndefinedRefs[undefs[i]] = 1;
95
96 return ret;
Nick Kledzik77595fc2008-02-26 20:26:43 +000097}
98
99
100bool LTOCodeGenerator::setDebugInfo(lto_debug_model debug, std::string& errMsg)
101{
102 switch (debug) {
103 case LTO_DEBUG_MODEL_NONE:
104 _emitDwarfDebugInfo = false;
105 return false;
106
107 case LTO_DEBUG_MODEL_DWARF:
108 _emitDwarfDebugInfo = true;
109 return false;
110 }
111 errMsg = "unknown debug format";
112 return true;
113}
114
115
116bool LTOCodeGenerator::setCodePICModel(lto_codegen_model model,
Evan Cheng855a1682009-06-26 06:57:16 +0000117 std::string& errMsg)
Nick Kledzik77595fc2008-02-26 20:26:43 +0000118{
119 switch (model) {
120 case LTO_CODEGEN_PIC_MODEL_STATIC:
121 case LTO_CODEGEN_PIC_MODEL_DYNAMIC:
122 case LTO_CODEGEN_PIC_MODEL_DYNAMIC_NO_PIC:
123 _codeModel = model;
124 return false;
125 }
126 errMsg = "unknown pic model";
127 return true;
128}
129
Rafael Espindola2d643ef2010-08-11 00:15:13 +0000130void LTOCodeGenerator::setCpu(const char* mCpu)
131{
132 _mCpu = mCpu;
133}
134
Nick Kledzik77595fc2008-02-26 20:26:43 +0000135void LTOCodeGenerator::addMustPreserveSymbol(const char* sym)
136{
137 _mustPreserveSymbols[sym] = 1;
138}
139
140
Chris Lattnerb515d752009-08-23 07:49:08 +0000141bool LTOCodeGenerator::writeMergedModules(const char *path,
142 std::string &errMsg) {
143 if (determineTarget(errMsg))
144 return true;
Nick Kledzik77595fc2008-02-26 20:26:43 +0000145
Chris Lattnerb515d752009-08-23 07:49:08 +0000146 // mark which symbols can not be internalized
147 applyScopeRestrictions();
Nick Kledzik77595fc2008-02-26 20:26:43 +0000148
Chris Lattnerb515d752009-08-23 07:49:08 +0000149 // create output file
150 std::string ErrInfo;
Dan Gohmanf2914012010-08-20 16:59:15 +0000151 tool_output_file Out(path, ErrInfo,
152 raw_fd_ostream::F_Binary);
Chris Lattnerb515d752009-08-23 07:49:08 +0000153 if (!ErrInfo.empty()) {
154 errMsg = "could not open bitcode file for writing: ";
155 errMsg += path;
156 return true;
157 }
Nick Kledzik77595fc2008-02-26 20:26:43 +0000158
Chris Lattnerb515d752009-08-23 07:49:08 +0000159 // write bitcode to it
Dan Gohmand4c45432010-09-01 14:20:41 +0000160 WriteBitcodeToFile(_linker.getModule(), Out.os());
161 Out.os().close();
Dan Gohman4b7416b2010-05-27 20:19:47 +0000162
Dan Gohmand4c45432010-09-01 14:20:41 +0000163 if (Out.os().has_error()) {
Chris Lattnerb515d752009-08-23 07:49:08 +0000164 errMsg = "could not write bitcode file: ";
165 errMsg += path;
Dan Gohmand4c45432010-09-01 14:20:41 +0000166 Out.os().clear_error();
Chris Lattnerb515d752009-08-23 07:49:08 +0000167 return true;
168 }
169
Dan Gohmanf2914012010-08-20 16:59:15 +0000170 Out.keep();
Chris Lattnerb515d752009-08-23 07:49:08 +0000171 return false;
Nick Kledzik77595fc2008-02-26 20:26:43 +0000172}
173
174
Nick Kledzikef194ed2008-02-27 22:25:36 +0000175const void* LTOCodeGenerator::compile(size_t* length, std::string& errMsg)
Nick Kledzik77595fc2008-02-26 20:26:43 +0000176{
Nick Kledzikef194ed2008-02-27 22:25:36 +0000177 // make unique temp .o file to put generated object file
Nick Kledzik77595fc2008-02-26 20:26:43 +0000178 sys::PathWithStatus uniqueObjPath("lto-llvm.o");
Devang Patelb7bbd462010-12-03 23:58:31 +0000179 if ( uniqueObjPath.createTemporaryFileOnDisk(false, &errMsg) ) {
Rafael Espindolae9efea12011-02-24 21:04:06 +0000180 uniqueObjPath.eraseFromDisk();
Nick Kledzik77595fc2008-02-26 20:26:43 +0000181 return NULL;
182 }
183 sys::RemoveFileOnSignal(uniqueObjPath);
184
Rafael Espindolae9efea12011-02-24 21:04:06 +0000185 // generate object file
186 bool genResult = false;
187 tool_output_file objFile(uniqueObjPath.c_str(), errMsg);
188 if (!errMsg.empty())
189 return NULL;
190 genResult = this->generateObjectFile(objFile.os(), errMsg);
191 objFile.os().close();
192 if (objFile.os().has_error()) {
193 objFile.os().clear_error();
194 return NULL;
195 }
196 objFile.keep();
197 if ( genResult ) {
198 uniqueObjPath.eraseFromDisk();
199 return NULL;
Nick Kledzik77595fc2008-02-26 20:26:43 +0000200 }
Nick Kledzikef194ed2008-02-27 22:25:36 +0000201
Rafael Espindolae9efea12011-02-24 21:04:06 +0000202 const std::string& uniqueObjStr = uniqueObjPath.str();
203 // remove old buffer if compile() called twice
204 delete _nativeObjectFile;
205
206 // read .o file into memory buffer
207 OwningPtr<MemoryBuffer> BuffPtr;
208 if (error_code ec = MemoryBuffer::getFile(uniqueObjStr.c_str(),BuffPtr))
209 errMsg = ec.message();
210 _nativeObjectFile = BuffPtr.take();
211
Nick Kledzikef194ed2008-02-27 22:25:36 +0000212 // remove temp files
Nick Kledzik77595fc2008-02-26 20:26:43 +0000213 uniqueObjPath.eraseFromDisk();
Nick Kledzikef194ed2008-02-27 22:25:36 +0000214
215 // return buffer, unless error
216 if ( _nativeObjectFile == NULL )
217 return NULL;
218 *length = _nativeObjectFile->getBufferSize();
219 return _nativeObjectFile->getBufferStart();
Nick Kledzik77595fc2008-02-26 20:26:43 +0000220}
221
Nick Kledzik77595fc2008-02-26 20:26:43 +0000222bool LTOCodeGenerator::determineTarget(std::string& errMsg)
223{
224 if ( _target == NULL ) {
Daniel Dunbar3c2d4bf2009-08-03 04:03:51 +0000225 std::string Triple = _linker.getModule()->getTargetTriple();
226 if (Triple.empty())
227 Triple = sys::getHostTriple();
228
Nick Kledzik77595fc2008-02-26 20:26:43 +0000229 // create target machine from info for merged modules
Daniel Dunbar4bd03ab2009-08-03 04:20:57 +0000230 const Target *march = TargetRegistry::lookupTarget(Triple, errMsg);
Nick Kledzik77595fc2008-02-26 20:26:43 +0000231 if ( march == NULL )
232 return true;
Bill Wendling604a8182008-06-18 06:35:30 +0000233
Nick Kledzikf5a1c35f12009-06-03 22:52:12 +0000234 // The relocation model is actually a static member of TargetMachine
235 // and needs to be set before the TargetMachine is instantiated.
236 switch( _codeModel ) {
237 case LTO_CODEGEN_PIC_MODEL_STATIC:
238 TargetMachine::setRelocationModel(Reloc::Static);
239 break;
240 case LTO_CODEGEN_PIC_MODEL_DYNAMIC:
241 TargetMachine::setRelocationModel(Reloc::PIC_);
242 break;
243 case LTO_CODEGEN_PIC_MODEL_DYNAMIC_NO_PIC:
244 TargetMachine::setRelocationModel(Reloc::DynamicNoPIC);
245 break;
246 }
247
Bill Wendling604a8182008-06-18 06:35:30 +0000248 // construct LTModule, hand over ownership of module and target
Bill Wendling81043ee2010-05-11 00:30:02 +0000249 SubtargetFeatures Features;
Rafael Espindola2d643ef2010-08-11 00:15:13 +0000250 Features.getDefaultSubtargetFeatures(_mCpu, llvm::Triple(Triple));
Bill Wendling81043ee2010-05-11 00:30:02 +0000251 std::string FeatureStr = Features.getString();
Viktor Kutuzov308f6632009-11-25 22:44:18 +0000252 _target = march->createTargetMachine(Triple, FeatureStr);
Nick Kledzik77595fc2008-02-26 20:26:43 +0000253 }
254 return false;
255}
256
Rafael Espindola38c4e532011-03-02 04:14:42 +0000257void LTOCodeGenerator::applyRestriction(GlobalValue &GV,
258 std::vector<const char*> &mustPreserveList,
259 SmallPtrSet<GlobalValue*, 8> &asmUsed,
260 Mangler &mangler) {
261 SmallString<64> Buffer;
262 mangler.getNameWithPrefix(Buffer, &GV, false);
263
264 if (GV.isDeclaration())
265 return;
266 if (_mustPreserveSymbols.count(Buffer))
267 mustPreserveList.push_back(GV.getName().data());
268 if (_asmUndefinedRefs.count(Buffer))
269 asmUsed.insert(&GV);
270}
271
272static void findUsedValues(GlobalVariable *LLVMUsed,
273 SmallPtrSet<GlobalValue*, 8> &UsedValues) {
274 if (LLVMUsed == 0) return;
275
276 ConstantArray *Inits = dyn_cast<ConstantArray>(LLVMUsed->getInitializer());
277 if (Inits == 0) return;
278
279 for (unsigned i = 0, e = Inits->getNumOperands(); i != e; ++i)
280 if (GlobalValue *GV =
281 dyn_cast<GlobalValue>(Inits->getOperand(i)->stripPointerCasts()))
282 UsedValues.insert(GV);
283}
284
Chris Lattner5ef31a02010-03-12 18:44:54 +0000285void LTOCodeGenerator::applyScopeRestrictions() {
286 if (_scopeRestrictionsDone) return;
287 Module *mergedModule = _linker.getModule();
Nick Kledzik77595fc2008-02-26 20:26:43 +0000288
Chris Lattner5ef31a02010-03-12 18:44:54 +0000289 // Start off with a verification pass.
290 PassManager passes;
291 passes.add(createVerifierPass());
Nick Kledzik77595fc2008-02-26 20:26:43 +0000292
Chris Lattner5ef31a02010-03-12 18:44:54 +0000293 // mark which symbols can not be internalized
Rafael Espindola38c4e532011-03-02 04:14:42 +0000294 MCContext Context(*_target->getMCAsmInfo(), NULL);
295 Mangler mangler(Context, *_target->getTargetData());
296 std::vector<const char*> mustPreserveList;
297 SmallPtrSet<GlobalValue*, 8> asmUsed;
298
299 for (Module::iterator f = mergedModule->begin(),
300 e = mergedModule->end(); f != e; ++f)
301 applyRestriction(*f, mustPreserveList, asmUsed, mangler);
302 for (Module::global_iterator v = mergedModule->global_begin(),
303 e = mergedModule->global_end(); v != e; ++v)
304 applyRestriction(*v, mustPreserveList, asmUsed, mangler);
305 for (Module::alias_iterator a = mergedModule->alias_begin(),
306 e = mergedModule->alias_end(); a != e; ++a)
307 applyRestriction(*a, mustPreserveList, asmUsed, mangler);
308
309 GlobalVariable *LLVMCompilerUsed =
310 mergedModule->getGlobalVariable("llvm.compiler.used");
311 findUsedValues(LLVMCompilerUsed, asmUsed);
312 if (LLVMCompilerUsed)
313 LLVMCompilerUsed->eraseFromParent();
314
315 const llvm::Type *i8PTy = llvm::Type::getInt8PtrTy(_context);
316 std::vector<Constant*> asmUsed2;
317 for (SmallPtrSet<GlobalValue*, 16>::const_iterator i = asmUsed.begin(),
318 e = asmUsed.end(); i !=e; ++i) {
319 GlobalValue *GV = *i;
320 Constant *c = ConstantExpr::getBitCast(GV, i8PTy);
321 asmUsed2.push_back(c);
Chris Lattner5ef31a02010-03-12 18:44:54 +0000322 }
Rafael Espindola38c4e532011-03-02 04:14:42 +0000323
324 llvm::ArrayType *ATy = llvm::ArrayType::get(i8PTy, asmUsed2.size());
325 LLVMCompilerUsed =
326 new llvm::GlobalVariable(*mergedModule, ATy, false,
327 llvm::GlobalValue::AppendingLinkage,
328 llvm::ConstantArray::get(ATy, asmUsed2),
329 "llvm.compiler.used");
330
331 LLVMCompilerUsed->setSection("llvm.metadata");
332
333 passes.add(createInternalizePass(mustPreserveList));
334
Chris Lattner5ef31a02010-03-12 18:44:54 +0000335 // apply scope restrictions
336 passes.run(*mergedModule);
337
338 _scopeRestrictionsDone = true;
Nick Kledzik77595fc2008-02-26 20:26:43 +0000339}
340
Nick Kledzik77595fc2008-02-26 20:26:43 +0000341/// Optimize merged modules using various IPO passes
Rafael Espindolae9efea12011-02-24 21:04:06 +0000342bool LTOCodeGenerator::generateObjectFile(raw_ostream& out,
343 std::string& errMsg)
Nick Kledzik77595fc2008-02-26 20:26:43 +0000344{
Nick Lewyckyd42b58b2009-07-26 22:16:39 +0000345 if ( this->determineTarget(errMsg) )
Nick Kledzik77595fc2008-02-26 20:26:43 +0000346 return true;
347
348 // mark which symbols can not be internalized
349 this->applyScopeRestrictions();
350
351 Module* mergedModule = _linker.getModule();
352
Nick Kledzik920ae982008-07-08 21:14:10 +0000353 // if options were requested, set them
354 if ( !_codegenOptions.empty() )
355 cl::ParseCommandLineOptions(_codegenOptions.size(),
Dan Gohman43bc70e2010-04-17 17:44:03 +0000356 const_cast<char **>(&_codegenOptions[0]));
Devang Patela93ae712008-07-03 22:53:14 +0000357
Nick Kledzik77595fc2008-02-26 20:26:43 +0000358 // Instantiate the pass manager to organize the passes.
359 PassManager passes;
360
361 // Start off with a verification pass.
362 passes.add(createVerifierPass());
363
364 // Add an appropriate TargetData instance for this module...
365 passes.add(new TargetData(*_target->getTargetData()));
366
Daniel Dunbar006a0342009-06-03 21:06:14 +0000367 createStandardLTOPasses(&passes, /*Internalize=*/ false, !DisableInline,
Daniel Dunbar006a0342009-06-03 21:06:14 +0000368 /*VerifyEach=*/ false);
Nick Kledzik77595fc2008-02-26 20:26:43 +0000369
370 // Make sure everything is still good.
371 passes.add(createVerifierPass());
372
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +0000373 FunctionPassManager* codeGenPasses = new FunctionPassManager(mergedModule);
Nick Kledzik77595fc2008-02-26 20:26:43 +0000374
375 codeGenPasses->add(new TargetData(*_target->getTargetData()));
376
Dan Gohmand4c45432010-09-01 14:20:41 +0000377 formatted_raw_ostream Out(out);
378
379 if (_target->addPassesToEmitFile(*codeGenPasses, Out,
Rafael Espindolae9efea12011-02-24 21:04:06 +0000380 TargetMachine::CGFT_ObjectFile,
Chris Lattner5669e302010-02-03 05:55:08 +0000381 CodeGenOpt::Aggressive)) {
382 errMsg = "target file type not supported";
383 return true;
Nick Kledzik77595fc2008-02-26 20:26:43 +0000384 }
385
Nick Kledzik77595fc2008-02-26 20:26:43 +0000386 // Run our queue of passes all at once now, efficiently.
387 passes.run(*mergedModule);
388
389 // Run the code generator, and write assembly file
390 codeGenPasses->doInitialization();
Nick Kledzik77595fc2008-02-26 20:26:43 +0000391
Bill Wendling604a8182008-06-18 06:35:30 +0000392 for (Module::iterator
393 it = mergedModule->begin(), e = mergedModule->end(); it != e; ++it)
394 if (!it->isDeclaration())
395 codeGenPasses->run(*it);
396
397 codeGenPasses->doFinalization();
Rafael Espindolacd6c93e2011-02-20 16:27:25 +0000398 delete codeGenPasses;
Nick Lewyckyd42b58b2009-07-26 22:16:39 +0000399
Nick Kledzik77595fc2008-02-26 20:26:43 +0000400 return false; // success
401}
402
403
Nick Kledzik920ae982008-07-08 21:14:10 +0000404/// Optimize merged modules using various IPO passes
405void LTOCodeGenerator::setCodeGenDebugOptions(const char* options)
406{
Benjamin Kramerd4f19592010-01-11 18:03:24 +0000407 for (std::pair<StringRef, StringRef> o = getToken(options);
408 !o.first.empty(); o = getToken(o.second)) {
Nick Kledzik920ae982008-07-08 21:14:10 +0000409 // ParseCommandLineOptions() expects argv[0] to be program name.
410 // Lazily add that.
411 if ( _codegenOptions.empty() )
412 _codegenOptions.push_back("libLTO");
Benjamin Kramerd4f19592010-01-11 18:03:24 +0000413 _codegenOptions.push_back(strdup(o.first.str().c_str()));
Nick Kledzik920ae982008-07-08 21:14:10 +0000414 }
415}