blob: 78c8cfe93d34f6201e408a5e398815cc7c5dc0e5 [file] [log] [blame]
Nick Kledzik77595fc2008-02-26 20:26:43 +00001//===-LTOModule.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
Nick Kledzik77595fc2008-02-26 20:26:43 +000017#include "llvm/Module.h"
Nick Kledzik77595fc2008-02-26 20:26:43 +000018#include "llvm/ModuleProvider.h"
Nick Kledzikef194ed2008-02-27 22:25:36 +000019#include "llvm/ADT/OwningPtr.h"
Nick Kledzik77595fc2008-02-26 20:26:43 +000020#include "llvm/Bitcode/ReaderWriter.h"
Nick Kledzik77595fc2008-02-26 20:26:43 +000021#include "llvm/Support/SystemUtils.h"
22#include "llvm/Support/Mangler.h"
23#include "llvm/Support/MemoryBuffer.h"
Nick Kledzikef194ed2008-02-27 22:25:36 +000024#include "llvm/Support/MathExtras.h"
Nick Kledzik77595fc2008-02-26 20:26:43 +000025#include "llvm/System/Path.h"
Nick Kledzik90dcff72008-05-09 01:09:59 +000026#include "llvm/System/Process.h"
Bill Wendling604a8182008-06-18 06:35:30 +000027#include "llvm/Target/SubtargetFeature.h"
Nick Kledzik77595fc2008-02-26 20:26:43 +000028#include "llvm/Target/TargetMachine.h"
29#include "llvm/Target/TargetMachineRegistry.h"
30#include "llvm/Target/TargetAsmInfo.h"
Nick Kledzik77595fc2008-02-26 20:26:43 +000031
Nick Kledzik77595fc2008-02-26 20:26:43 +000032#include <fstream>
33
34using namespace llvm;
35
36bool LTOModule::isBitcodeFile(const void* mem, size_t length)
37{
38 return ( llvm::sys::IdentifyFileType((char*)mem, length)
39 == llvm::sys::Bitcode_FileType );
40}
41
42bool LTOModule::isBitcodeFile(const char* path)
43{
44 return llvm::sys::Path(path).isBitcodeFile();
45}
46
Chris Lattner038112a2008-04-01 18:04:03 +000047bool LTOModule::isBitcodeFileForTarget(const void* mem, size_t length,
48 const char* triplePrefix)
Nick Kledzik77595fc2008-02-26 20:26:43 +000049{
Nick Kledzik90dcff72008-05-09 01:09:59 +000050 MemoryBuffer* buffer = makeBuffer(mem, length);
Nick Kledzikef194ed2008-02-27 22:25:36 +000051 if ( buffer == NULL )
52 return false;
53 return isTargetMatch(buffer, triplePrefix);
Nick Kledzik77595fc2008-02-26 20:26:43 +000054}
55
Nick Kledzikef194ed2008-02-27 22:25:36 +000056
Nick Kledzik77595fc2008-02-26 20:26:43 +000057bool LTOModule::isBitcodeFileForTarget(const char* path,
Chris Lattner038112a2008-04-01 18:04:03 +000058 const char* triplePrefix)
Nick Kledzik77595fc2008-02-26 20:26:43 +000059{
Chris Lattner038112a2008-04-01 18:04:03 +000060 MemoryBuffer *buffer = MemoryBuffer::getFile(path);
61 if (buffer == NULL)
Nick Kledzikef194ed2008-02-27 22:25:36 +000062 return false;
63 return isTargetMatch(buffer, triplePrefix);
64}
65
66// takes ownership of buffer
67bool LTOModule::isTargetMatch(MemoryBuffer* buffer, const char* triplePrefix)
68{
69 OwningPtr<ModuleProvider> mp(getBitcodeModuleProvider(buffer));
70 // on success, mp owns buffer and both are deleted at end of this method
71 if ( !mp ) {
72 delete buffer;
73 return false;
Nick Kledzik77595fc2008-02-26 20:26:43 +000074 }
Nick Kledzikef194ed2008-02-27 22:25:36 +000075 std::string actualTarget = mp->getModule()->getTargetTriple();
76 return ( strncmp(actualTarget.c_str(), triplePrefix,
77 strlen(triplePrefix)) == 0);
Nick Kledzik77595fc2008-02-26 20:26:43 +000078}
79
80
81LTOModule::LTOModule(Module* m, TargetMachine* t)
82 : _module(m), _target(t), _symbolsParsed(false)
83{
84}
85
Nick Kledzik77595fc2008-02-26 20:26:43 +000086LTOModule* LTOModule::makeLTOModule(const char* path, std::string& errMsg)
87{
Chris Lattner038112a2008-04-01 18:04:03 +000088 OwningPtr<MemoryBuffer> buffer(MemoryBuffer::getFile(path, &errMsg));
Nick Kledzikef194ed2008-02-27 22:25:36 +000089 if ( !buffer )
90 return NULL;
91 return makeLTOModule(buffer.get(), errMsg);
Nick Kledzik77595fc2008-02-26 20:26:43 +000092}
93
Nick Kledzik6b89d922008-05-09 18:44:41 +000094/// makeBuffer - create a MemoryBuffer from a memory range.
95/// MemoryBuffer requires the byte past end of the buffer to be a zero.
96/// We might get lucky and already be that way, otherwise make a copy.
97/// Also if next byte is on a different page, don't assume it is readable.
Nick Kledzik90dcff72008-05-09 01:09:59 +000098MemoryBuffer* LTOModule::makeBuffer(const void* mem, size_t length)
99{
Nick Kledziked185d62008-05-28 00:06:14 +0000100 const char* startPtr = (char*)mem;
101 const char* endPtr = startPtr+length;
102 if ( (((uintptr_t)endPtr & (sys::Process::GetPageSize()-1)) == 0)
103 || (*endPtr != 0) )
104 return MemoryBuffer::getMemBufferCopy(startPtr, endPtr);
105 else
106 return MemoryBuffer::getMemBuffer(startPtr, endPtr);
Nick Kledzik90dcff72008-05-09 01:09:59 +0000107}
108
109
Nick Kledzik77595fc2008-02-26 20:26:43 +0000110LTOModule* LTOModule::makeLTOModule(const void* mem, size_t length,
Nick Lewyckyb454eab2009-02-06 07:01:00 +0000111 std::string& errMsg)
Nick Kledzik77595fc2008-02-26 20:26:43 +0000112{
Nick Kledzik90dcff72008-05-09 01:09:59 +0000113 OwningPtr<MemoryBuffer> buffer(makeBuffer(mem, length));
Nick Kledzikef194ed2008-02-27 22:25:36 +0000114 if ( !buffer )
115 return NULL;
116 return makeLTOModule(buffer.get(), errMsg);
117}
118
Bill Wendlinge4242542008-06-18 21:39:02 +0000119/// getFeatureString - Return a string listing the features associated with the
120/// target triple.
121///
122/// FIXME: This is an inelegant way of specifying the features of a
123/// subtarget. It would be better if we could encode this information into the
124/// IR. See <rdar://5972456>.
125std::string getFeatureString(const char *TargetTriple) {
126 SubtargetFeatures Features;
127
128 if (strncmp(TargetTriple, "powerpc-apple-", 14) == 0) {
129 Features.AddFeature("altivec", true);
130 } else if (strncmp(TargetTriple, "powerpc64-apple-", 16) == 0) {
131 Features.AddFeature("64bit", true);
132 Features.AddFeature("altivec", true);
133 }
134
135 return Features.getString();
136}
137
Nick Kledzikef194ed2008-02-27 22:25:36 +0000138LTOModule* LTOModule::makeLTOModule(MemoryBuffer* buffer, std::string& errMsg)
139{
140 // parse bitcode buffer
141 OwningPtr<Module> m(ParseBitcodeFile(buffer, &errMsg));
142 if ( !m )
143 return NULL;
144 // find machine architecture for this module
145 const TargetMachineRegistry::entry* march =
146 TargetMachineRegistry::getClosestStaticTargetForModule(*m, errMsg);
Bill Wendling604a8182008-06-18 06:35:30 +0000147
Nick Kledzikef194ed2008-02-27 22:25:36 +0000148 if ( march == NULL )
149 return NULL;
Bill Wendling604a8182008-06-18 06:35:30 +0000150
Nick Kledzikef194ed2008-02-27 22:25:36 +0000151 // construct LTModule, hand over ownership of module and target
Bill Wendlinge4242542008-06-18 21:39:02 +0000152 std::string FeatureStr = getFeatureString(m->getTargetTriple().c_str());
153 TargetMachine* target = march->CtorFn(*m, FeatureStr);
Nick Kledzikef194ed2008-02-27 22:25:36 +0000154 return new LTOModule(m.take(), target);
Nick Kledzik77595fc2008-02-26 20:26:43 +0000155}
156
157
158const char* LTOModule::getTargetTriple()
159{
160 return _module->getTargetTriple().c_str();
161}
162
Nick Kledzikef194ed2008-02-27 22:25:36 +0000163void LTOModule::addDefinedFunctionSymbol(Function* f, Mangler &mangler)
164{
165 // add to list of defined symbols
166 addDefinedSymbol(f, mangler, true);
167
168 // add external symbols referenced by this function.
169 for (Function::iterator b = f->begin(); b != f->end(); ++b) {
170 for (BasicBlock::iterator i = b->begin(); i != b->end(); ++i) {
171 for (unsigned count = 0, total = i->getNumOperands();
172 count != total; ++count) {
173 findExternalRefs(i->getOperand(count), mangler);
174 }
175 }
176 }
177}
178
179void LTOModule::addDefinedDataSymbol(GlobalValue* v, Mangler &mangler)
180{
181 // add to list of defined symbols
182 addDefinedSymbol(v, mangler, false);
183
184 // add external symbols referenced by this data.
Nick Kledzik9178a652008-05-27 22:07:08 +0000185 for (unsigned count = 0, total = v->getNumOperands();
Nick Kledzikef194ed2008-02-27 22:25:36 +0000186 count != total; ++count) {
187 findExternalRefs(v->getOperand(count), mangler);
188 }
189}
190
191
Nick Kledzik77595fc2008-02-26 20:26:43 +0000192void LTOModule::addDefinedSymbol(GlobalValue* def, Mangler &mangler,
193 bool isFunction)
194{
Nick Kledzikef194ed2008-02-27 22:25:36 +0000195 // string is owned by _defines
Nick Kledzik77595fc2008-02-26 20:26:43 +0000196 const char* symbolName = ::strdup(mangler.getValueName(def).c_str());
197
198 // set alignment part log2() can have rounding errors
199 uint32_t align = def->getAlignment();
Nick Kledzikef194ed2008-02-27 22:25:36 +0000200 uint32_t attr = align ? CountTrailingZeros_32(def->getAlignment()) : 0;
Nick Kledzik77595fc2008-02-26 20:26:43 +0000201
202 // set permissions part
203 if ( isFunction )
204 attr |= LTO_SYMBOL_PERMISSIONS_CODE;
205 else {
206 GlobalVariable* gv = dyn_cast<GlobalVariable>(def);
207 if ( (gv != NULL) && gv->isConstant() )
208 attr |= LTO_SYMBOL_PERMISSIONS_RODATA;
209 else
210 attr |= LTO_SYMBOL_PERMISSIONS_DATA;
211 }
212
213 // set definition part
214 if ( def->hasWeakLinkage() || def->hasLinkOnceLinkage() ) {
Dale Johannesened1ec3a2008-05-23 00:15:10 +0000215 attr |= LTO_SYMBOL_DEFINITION_WEAK;
Nick Kledzik77595fc2008-02-26 20:26:43 +0000216 }
Dale Johannesen6a6f2dd2008-05-16 22:46:40 +0000217 else if ( def->hasCommonLinkage()) {
218 attr |= LTO_SYMBOL_DEFINITION_TENTATIVE;
219 }
Nick Kledzik77595fc2008-02-26 20:26:43 +0000220 else {
221 attr |= LTO_SYMBOL_DEFINITION_REGULAR;
222 }
223
224 // set scope part
225 if ( def->hasHiddenVisibility() )
226 attr |= LTO_SYMBOL_SCOPE_HIDDEN;
Nick Lewycky4fd40e82008-11-29 22:49:59 +0000227 else if ( def->hasProtectedVisibility() )
228 attr |= LTO_SYMBOL_SCOPE_PROTECTED;
Devang Patelf0d286b2008-07-15 00:00:11 +0000229 else if ( def->hasExternalLinkage() || def->hasWeakLinkage()
Nick Kledzikdb6535d2008-07-19 00:58:07 +0000230 || def->hasLinkOnceLinkage() || def->hasCommonLinkage() )
Nick Kledzik77595fc2008-02-26 20:26:43 +0000231 attr |= LTO_SYMBOL_SCOPE_DEFAULT;
232 else
233 attr |= LTO_SYMBOL_SCOPE_INTERNAL;
234
235 // add to table of symbols
236 NameAndAttributes info;
237 info.name = symbolName;
238 info.attributes = (lto_symbol_attributes)attr;
239 _symbols.push_back(info);
240 _defines[info.name] = 1;
241}
242
Devang Patelc2aec572008-07-16 18:06:52 +0000243void LTOModule::addAsmGlobalSymbol(const char *name) {
244 // string is owned by _defines
245 const char *symbolName = ::strdup(name);
246 uint32_t attr = LTO_SYMBOL_DEFINITION_REGULAR;
247 attr |= LTO_SYMBOL_SCOPE_DEFAULT;
248
249 // add to table of symbols
250 NameAndAttributes info;
251 info.name = symbolName;
252 info.attributes = (lto_symbol_attributes)attr;
253 _symbols.push_back(info);
254 _defines[info.name] = 1;
255}
Nick Kledzik77595fc2008-02-26 20:26:43 +0000256
Nick Kledzikef194ed2008-02-27 22:25:36 +0000257void LTOModule::addPotentialUndefinedSymbol(GlobalValue* decl, Mangler &mangler)
258{
259 const char* name = mangler.getValueName(decl).c_str();
Nick Kledzik77595fc2008-02-26 20:26:43 +0000260 // ignore all llvm.* symbols
Rafael Espindola7431af02009-04-24 16:55:21 +0000261 if ( strncmp(name, "llvm.", 5) == 0 )
262 return;
263
264 // we already have the symbol
265 if (_undefines.find(name) != _undefines.end())
266 return;
267
268 NameAndAttributes info;
269 // string is owned by _undefines
270 info.name = ::strdup(name);
271 if (decl->hasExternalWeakLinkage())
272 info.attributes = LTO_SYMBOL_DEFINITION_WEAKUNDEF;
273 else
274 info.attributes = LTO_SYMBOL_DEFINITION_UNDEFINED;
275 _undefines[name] = info;
Nick Kledzik77595fc2008-02-26 20:26:43 +0000276}
277
278
279
280// Find exeternal symbols referenced by VALUE. This is a recursive function.
281void LTOModule::findExternalRefs(Value* value, Mangler &mangler) {
282
283 if (GlobalValue* gv = dyn_cast<GlobalValue>(value)) {
284 if ( !gv->hasExternalLinkage() )
Nick Kledzikef194ed2008-02-27 22:25:36 +0000285 addPotentialUndefinedSymbol(gv, mangler);
Nick Kledziked185d62008-05-28 00:06:14 +0000286 // If this is a variable definition, do not recursively process
287 // initializer. It might contain a reference to this variable
288 // and cause an infinite loop. The initializer will be
289 // processed in addDefinedDataSymbol().
290 return;
Nick Kledzik77595fc2008-02-26 20:26:43 +0000291 }
Nick Kledziked185d62008-05-28 00:06:14 +0000292
Nick Kledzik77595fc2008-02-26 20:26:43 +0000293 // GlobalValue, even with InternalLinkage type, may have operands with
294 // ExternalLinkage type. Do not ignore these operands.
295 if (Constant* c = dyn_cast<Constant>(value)) {
296 // Handle ConstantExpr, ConstantStruct, ConstantArry etc..
297 for (unsigned i = 0, e = c->getNumOperands(); i != e; ++i)
298 findExternalRefs(c->getOperand(i), mangler);
299 }
300}
301
Nick Kledzikef194ed2008-02-27 22:25:36 +0000302void LTOModule::lazyParseSymbols()
Nick Kledzik77595fc2008-02-26 20:26:43 +0000303{
304 if ( !_symbolsParsed ) {
305 _symbolsParsed = true;
306
307 // Use mangler to add GlobalPrefix to names to match linker names.
308 Mangler mangler(*_module, _target->getTargetAsmInfo()->getGlobalPrefix());
309
310 // add functions
311 for (Module::iterator f = _module->begin(); f != _module->end(); ++f) {
Nick Kledzikef194ed2008-02-27 22:25:36 +0000312 if ( f->isDeclaration() )
313 addPotentialUndefinedSymbol(f, mangler);
314 else
315 addDefinedFunctionSymbol(f, mangler);
Nick Kledzik77595fc2008-02-26 20:26:43 +0000316 }
317
318 // add data
319 for (Module::global_iterator v = _module->global_begin(),
320 e = _module->global_end(); v != e; ++v) {
Nick Kledzikef194ed2008-02-27 22:25:36 +0000321 if ( v->isDeclaration() )
322 addPotentialUndefinedSymbol(v, mangler);
323 else
324 addDefinedDataSymbol(v, mangler);
Nick Kledzik77595fc2008-02-26 20:26:43 +0000325 }
326
Devang Patelc2aec572008-07-16 18:06:52 +0000327 // add asm globals
328 const std::string &inlineAsm = _module->getModuleInlineAsm();
329 const std::string glbl = ".globl";
330 std::string asmSymbolName;
331 std::string::size_type pos = inlineAsm.find(glbl, 0);
332 while (pos != std::string::npos) {
333 // eat .globl
334 pos = pos + 6;
335
336 // skip white space between .globl and symbol name
337 std::string::size_type pbegin = inlineAsm.find_first_not_of(' ', pos);
338 if (pbegin == std::string::npos)
339 break;
340
341 // find end-of-line
342 std::string::size_type pend = inlineAsm.find_first_of('\n', pbegin);
343 if (pend == std::string::npos)
344 break;
345
Devang Patel41390702008-07-16 19:49:09 +0000346 asmSymbolName.assign(inlineAsm, pbegin, pend - pbegin);
Devang Patelc2aec572008-07-16 18:06:52 +0000347 addAsmGlobalSymbol(asmSymbolName.c_str());
348
349 // search next .globl
350 pos = inlineAsm.find(glbl, pend);
351 }
352
Nick Kledzik77595fc2008-02-26 20:26:43 +0000353 // make symbols for all undefines
Rafael Espindola7431af02009-04-24 16:55:21 +0000354 for (StringMap<NameAndAttributes>::iterator it=_undefines.begin();
Nick Kledzik77595fc2008-02-26 20:26:43 +0000355 it != _undefines.end(); ++it) {
356 // if this symbol also has a definition, then don't make an undefine
357 // because it is a tentative definition
Nick Kledzikef194ed2008-02-27 22:25:36 +0000358 if ( _defines.count(it->getKeyData(), it->getKeyData()+
359 it->getKeyLength()) == 0 ) {
Rafael Espindola7431af02009-04-24 16:55:21 +0000360 NameAndAttributes info = it->getValue();
361 _symbols.push_back(info);
Nick Kledzik77595fc2008-02-26 20:26:43 +0000362 }
363 }
Nick Kledzikef194ed2008-02-27 22:25:36 +0000364 }
365}
366
367
368uint32_t LTOModule::getSymbolCount()
369{
370 lazyParseSymbols();
Nick Kledzik77595fc2008-02-26 20:26:43 +0000371 return _symbols.size();
372}
373
374
375lto_symbol_attributes LTOModule::getSymbolAttributes(uint32_t index)
376{
Nick Kledzikef194ed2008-02-27 22:25:36 +0000377 lazyParseSymbols();
Nick Kledzik77595fc2008-02-26 20:26:43 +0000378 if ( index < _symbols.size() )
379 return _symbols[index].attributes;
380 else
381 return lto_symbol_attributes(0);
382}
383
384const char* LTOModule::getSymbolName(uint32_t index)
385{
Nick Kledzikef194ed2008-02-27 22:25:36 +0000386 lazyParseSymbols();
Nick Kledzik77595fc2008-02-26 20:26:43 +0000387 if ( index < _symbols.size() )
388 return _symbols[index].name;
389 else
390 return NULL;
391}
392