blob: 310e647b1f114820e07b475cdf54d3c0d7ec1672 [file] [log] [blame]
Chris Lattner5ef31a02010-03-12 18:44:54 +00001//===-- LTOModule.cpp - LLVM Link Time Optimizer --------------------------===//
Nick Kledzik77595fc2008-02-26 20:26:43 +00002//
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.
Daniel Dunbarb06913d2010-08-10 23:46:39 +00007//
Nick Kledzik77595fc2008-02-26 20:26:43 +00008//===----------------------------------------------------------------------===//
9//
Daniel Dunbarb06913d2010-08-10 23:46:39 +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 "LTOModule.h"
16
Nick Kledzik3eb445f2009-06-01 20:33:09 +000017#include "llvm/Constants.h"
Owen Anderson8b477ed2009-07-01 16:58:40 +000018#include "llvm/LLVMContext.h"
Nick Kledzik77595fc2008-02-26 20:26:43 +000019#include "llvm/Module.h"
Nick Kledzikef194ed2008-02-27 22:25:36 +000020#include "llvm/ADT/OwningPtr.h"
Viktor Kutuzove823db82009-11-18 20:20:05 +000021#include "llvm/ADT/Triple.h"
Nick Kledzik77595fc2008-02-26 20:26:43 +000022#include "llvm/Bitcode/ReaderWriter.h"
Nick Kledzik77595fc2008-02-26 20:26:43 +000023#include "llvm/Support/SystemUtils.h"
Nick Kledzik77595fc2008-02-26 20:26:43 +000024#include "llvm/Support/MemoryBuffer.h"
Nick Kledzikef194ed2008-02-27 22:25:36 +000025#include "llvm/Support/MathExtras.h"
Michael J. Spencer3cc52ea2010-11-29 18:47:54 +000026#include "llvm/Support/Host.h"
27#include "llvm/Support/Path.h"
28#include "llvm/Support/Process.h"
Rafael Espindola38c4e532011-03-02 04:14:42 +000029#include "llvm/Support/SourceMgr.h"
Michael J. Spencerf2f516f2010-12-09 18:06:07 +000030#include "llvm/Support/system_error.h"
Chris Lattner45111d12010-01-16 21:57:06 +000031#include "llvm/Target/Mangler.h"
Bill Wendling604a8182008-06-18 06:35:30 +000032#include "llvm/Target/SubtargetFeature.h"
Chris Lattneraf76e592009-08-22 20:48:53 +000033#include "llvm/MC/MCAsmInfo.h"
Chris Lattner5ef31a02010-03-12 18:44:54 +000034#include "llvm/MC/MCContext.h"
Rafael Espindola38c4e532011-03-02 04:14:42 +000035#include "llvm/MC/MCExpr.h"
36#include "llvm/MC/MCInst.h"
37#include "llvm/MC/MCParser/MCAsmParser.h"
38#include "llvm/MC/MCStreamer.h"
39#include "llvm/MC/MCSymbol.h"
40#include "llvm/Target/TargetAsmParser.h"
Daniel Dunbarff9834a2009-07-16 02:41:19 +000041#include "llvm/Target/TargetMachine.h"
42#include "llvm/Target/TargetRegistry.h"
Nick Lewyckyd42b58b2009-07-26 22:16:39 +000043#include "llvm/Target/TargetSelect.h"
Nick Kledzik77595fc2008-02-26 20:26:43 +000044
Nick Kledzik77595fc2008-02-26 20:26:43 +000045using namespace llvm;
46
Daniel Dunbarb06913d2010-08-10 23:46:39 +000047bool LTOModule::isBitcodeFile(const void *mem, size_t length) {
48 return llvm::sys::IdentifyFileType((char*)mem, length)
49 == llvm::sys::Bitcode_FileType;
Nick Kledzik77595fc2008-02-26 20:26:43 +000050}
51
Daniel Dunbarb06913d2010-08-10 23:46:39 +000052bool LTOModule::isBitcodeFile(const char *path) {
53 return llvm::sys::Path(path).isBitcodeFile();
Nick Kledzik77595fc2008-02-26 20:26:43 +000054}
55
Daniel Dunbarb06913d2010-08-10 23:46:39 +000056bool LTOModule::isBitcodeFileForTarget(const void *mem, size_t length,
57 const char *triplePrefix) {
58 MemoryBuffer *buffer = makeBuffer(mem, length);
59 if (!buffer)
Nick Kledzik3eb445f2009-06-01 20:33:09 +000060 return false;
Daniel Dunbarb06913d2010-08-10 23:46:39 +000061 return isTargetMatch(buffer, triplePrefix);
Nick Kledzik3eb445f2009-06-01 20:33:09 +000062}
63
Daniel Dunbarb06913d2010-08-10 23:46:39 +000064
65bool LTOModule::isBitcodeFileForTarget(const char *path,
66 const char *triplePrefix) {
Michael J. Spencer3ff95632010-12-16 03:29:14 +000067 OwningPtr<MemoryBuffer> buffer;
68 if (MemoryBuffer::getFile(path, buffer))
Daniel Dunbarb06913d2010-08-10 23:46:39 +000069 return false;
Michael J. Spencer3ff95632010-12-16 03:29:14 +000070 return isTargetMatch(buffer.take(), triplePrefix);
Daniel Dunbarb06913d2010-08-10 23:46:39 +000071}
72
73// Takes ownership of buffer.
74bool LTOModule::isTargetMatch(MemoryBuffer *buffer, const char *triplePrefix) {
Bill Wendling34711742010-10-06 01:22:42 +000075 std::string Triple = getBitcodeTargetTriple(buffer, getGlobalContext());
76 delete buffer;
Michael J. Spencer3ff95632010-12-16 03:29:14 +000077 return (strncmp(Triple.c_str(), triplePrefix,
Bill Wendling34711742010-10-06 01:22:42 +000078 strlen(triplePrefix)) == 0);
Daniel Dunbarb06913d2010-08-10 23:46:39 +000079}
80
81
82LTOModule::LTOModule(Module *m, TargetMachine *t)
Rafael Espindola38c4e532011-03-02 04:14:42 +000083 : _module(m), _target(t)
Nick Kledzik3eb445f2009-06-01 20:33:09 +000084{
Daniel Dunbarb06913d2010-08-10 23:46:39 +000085}
86
87LTOModule *LTOModule::makeLTOModule(const char *path,
88 std::string &errMsg) {
Michael J. Spencer3ff95632010-12-16 03:29:14 +000089 OwningPtr<MemoryBuffer> buffer;
90 if (error_code ec = MemoryBuffer::getFile(path, buffer)) {
Michael J. Spencerf2f516f2010-12-09 18:06:07 +000091 errMsg = ec.message();
Daniel Dunbarb06913d2010-08-10 23:46:39 +000092 return NULL;
Michael J. Spencerf2f516f2010-12-09 18:06:07 +000093 }
Daniel Dunbarb06913d2010-08-10 23:46:39 +000094 return makeLTOModule(buffer.get(), errMsg);
95}
96
Rafael Espindolab4cc0312011-02-08 22:40:47 +000097LTOModule *LTOModule::makeLTOModule(int fd, const char *path,
Rafael Espindolaf21b1052011-03-17 00:36:11 +000098 size_t size,
99 std::string &errMsg) {
100 return makeLTOModule(fd, path, size, size, 0, errMsg);
101}
102
103LTOModule *LTOModule::makeLTOModule(int fd, const char *path,
104 size_t file_size,
105 size_t map_size,
106 off_t offset,
Rafael Espindolab4cc0312011-02-08 22:40:47 +0000107 std::string &errMsg) {
108 OwningPtr<MemoryBuffer> buffer;
Rafael Espindolaf21b1052011-03-17 00:36:11 +0000109 if (error_code ec = MemoryBuffer::getOpenFile(fd, path, buffer, file_size,
110 map_size, offset, false)) {
Rafael Espindolab4cc0312011-02-08 22:40:47 +0000111 errMsg = ec.message();
112 return NULL;
113 }
114 return makeLTOModule(buffer.get(), errMsg);
115}
116
Rafael Espindola9916d2a2011-03-17 22:18:42 +0000117/// makeBuffer - Create a MemoryBuffer from a memory range.
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000118MemoryBuffer *LTOModule::makeBuffer(const void *mem, size_t length) {
119 const char *startPtr = (char*)mem;
120 const char *endPtr = startPtr+length;
Rafael Espindola9916d2a2011-03-17 22:18:42 +0000121 return MemoryBuffer::getMemBuffer(StringRef(startPtr, length), "", false);
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000122}
123
124
125LTOModule *LTOModule::makeLTOModule(const void *mem, size_t length,
126 std::string &errMsg) {
127 OwningPtr<MemoryBuffer> buffer(makeBuffer(mem, length));
128 if (!buffer)
129 return NULL;
130 return makeLTOModule(buffer.get(), errMsg);
131}
132
133LTOModule *LTOModule::makeLTOModule(MemoryBuffer *buffer,
134 std::string &errMsg) {
Rafael Espindola38c4e532011-03-02 04:14:42 +0000135 static bool Initialized = false;
136 if (!Initialized) {
137 InitializeAllTargets();
138 InitializeAllAsmParsers();
139 Initialized = true;
140 }
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000141
142 // parse bitcode buffer
143 OwningPtr<Module> m(ParseBitcodeFile(buffer, getGlobalContext(), &errMsg));
144 if (!m)
145 return NULL;
146
147 std::string Triple = m->getTargetTriple();
148 if (Triple.empty())
149 Triple = sys::getHostTriple();
150
151 // find machine architecture for this module
152 const Target *march = TargetRegistry::lookupTarget(Triple, errMsg);
153 if (!march)
154 return NULL;
155
156 // construct LTModule, hand over ownership of module and target
157 SubtargetFeatures Features;
158 Features.getDefaultSubtargetFeatures("" /* cpu */, llvm::Triple(Triple));
159 std::string FeatureStr = Features.getString();
160 TargetMachine *target = march->createTargetMachine(Triple, FeatureStr);
Rafael Espindola38c4e532011-03-02 04:14:42 +0000161 LTOModule *Ret = new LTOModule(m.take(), target);
162 bool Err = Ret->ParseSymbols();
163 if (Err) {
164 delete Ret;
165 return NULL;
166 }
167 return Ret;
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000168}
169
170
171const char *LTOModule::getTargetTriple() {
172 return _module->getTargetTriple().c_str();
173}
174
175void LTOModule::setTargetTriple(const char *triple) {
176 _module->setTargetTriple(triple);
177}
178
179void LTOModule::addDefinedFunctionSymbol(Function *f, Mangler &mangler) {
180 // add to list of defined symbols
181 addDefinedSymbol(f, mangler, true);
182
183 // add external symbols referenced by this function.
184 for (Function::iterator b = f->begin(); b != f->end(); ++b) {
185 for (BasicBlock::iterator i = b->begin(); i != b->end(); ++i) {
186 for (unsigned count = 0, total = i->getNumOperands();
187 count != total; ++count) {
188 findExternalRefs(i->getOperand(count), mangler);
189 }
Nick Kledzik3eb445f2009-06-01 20:33:09 +0000190 }
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000191 }
Nick Kledzik3eb445f2009-06-01 20:33:09 +0000192}
193
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000194// Get string that data pointer points to.
195bool LTOModule::objcClassNameFromExpression(Constant *c, std::string &name) {
196 if (ConstantExpr *ce = dyn_cast<ConstantExpr>(c)) {
197 Constant *op = ce->getOperand(0);
198 if (GlobalVariable *gvn = dyn_cast<GlobalVariable>(op)) {
199 Constant *cn = gvn->getInitializer();
200 if (ConstantArray *ca = dyn_cast<ConstantArray>(cn)) {
201 if (ca->isCString()) {
202 name = ".objc_class_name_" + ca->getAsString();
203 return true;
Nick Kledzik3eb445f2009-06-01 20:33:09 +0000204 }
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000205 }
Nick Kledzik3eb445f2009-06-01 20:33:09 +0000206 }
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000207 }
208 return false;
209}
210
211// Parse i386/ppc ObjC class data structure.
212void LTOModule::addObjCClass(GlobalVariable *clgv) {
213 if (ConstantStruct *c = dyn_cast<ConstantStruct>(clgv->getInitializer())) {
214 // second slot in __OBJC,__class is pointer to superclass name
215 std::string superclassName;
216 if (objcClassNameFromExpression(c->getOperand(1), superclassName)) {
217 NameAndAttributes info;
Rafael Espindolacd6c93e2011-02-20 16:27:25 +0000218 StringMap<NameAndAttributes>::value_type &entry =
219 _undefines.GetOrCreateValue(superclassName.c_str());
220 if (!entry.getValue().name) {
221 const char *symbolName = entry.getKey().data();
Daniel Dunbar8d0843d2010-08-11 00:11:17 +0000222 info.name = symbolName;
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000223 info.attributes = LTO_SYMBOL_DEFINITION_UNDEFINED;
Rafael Espindolacd6c93e2011-02-20 16:27:25 +0000224 entry.setValue(info);
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000225 }
226 }
227 // third slot in __OBJC,__class is pointer to class name
228 std::string className;
229 if (objcClassNameFromExpression(c->getOperand(2), className)) {
Rafael Espindolacd6c93e2011-02-20 16:27:25 +0000230 StringSet::value_type &entry =
231 _defines.GetOrCreateValue(className.c_str());
232 entry.setValue(1);
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000233 NameAndAttributes info;
Rafael Espindolacd6c93e2011-02-20 16:27:25 +0000234 info.name = entry.getKey().data();
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000235 info.attributes = (lto_symbol_attributes)
236 (LTO_SYMBOL_PERMISSIONS_DATA |
237 LTO_SYMBOL_DEFINITION_REGULAR |
238 LTO_SYMBOL_SCOPE_DEFAULT);
239 _symbols.push_back(info);
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000240 }
241 }
Nick Kledzik3eb445f2009-06-01 20:33:09 +0000242}
243
244
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000245// Parse i386/ppc ObjC category data structure.
246void LTOModule::addObjCCategory(GlobalVariable *clgv) {
247 if (ConstantStruct *c = dyn_cast<ConstantStruct>(clgv->getInitializer())) {
248 // second slot in __OBJC,__category is pointer to target class name
Nick Kledzik3eb445f2009-06-01 20:33:09 +0000249 std::string targetclassName;
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000250 if (objcClassNameFromExpression(c->getOperand(1), targetclassName)) {
251 NameAndAttributes info;
Rafael Espindolacd6c93e2011-02-20 16:27:25 +0000252
253 StringMap<NameAndAttributes>::value_type &entry =
254 _undefines.GetOrCreateValue(targetclassName.c_str());
255
256 if (entry.getValue().name)
257 return;
258
259 const char *symbolName = entry.getKey().data();
260 info.name = symbolName;
261 info.attributes = LTO_SYMBOL_DEFINITION_UNDEFINED;
262 entry.setValue(info);
Nick Kledzik3eb445f2009-06-01 20:33:09 +0000263 }
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000264 }
Nick Kledzik3eb445f2009-06-01 20:33:09 +0000265}
266
267
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000268// Parse i386/ppc ObjC class list data structure.
269void LTOModule::addObjCClassRef(GlobalVariable *clgv) {
270 std::string targetclassName;
271 if (objcClassNameFromExpression(clgv->getInitializer(), targetclassName)) {
Nick Kledzik77595fc2008-02-26 20:26:43 +0000272 NameAndAttributes info;
Rafael Espindolacd6c93e2011-02-20 16:27:25 +0000273
274 StringMap<NameAndAttributes>::value_type &entry =
275 _undefines.GetOrCreateValue(targetclassName.c_str());
276 if (entry.getValue().name)
277 return;
278
279 const char *symbolName = entry.getKey().data();
280 info.name = symbolName;
281 info.attributes = LTO_SYMBOL_DEFINITION_UNDEFINED;
282 entry.setValue(info);
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000283 }
284}
285
286
287void LTOModule::addDefinedDataSymbol(GlobalValue *v, Mangler &mangler) {
288 // Add to list of defined symbols.
289 addDefinedSymbol(v, mangler, false);
290
291 // Special case i386/ppc ObjC data structures in magic sections:
292 // The issue is that the old ObjC object format did some strange
293 // contortions to avoid real linker symbols. For instance, the
294 // ObjC class data structure is allocated statically in the executable
295 // that defines that class. That data structures contains a pointer to
296 // its superclass. But instead of just initializing that part of the
297 // struct to the address of its superclass, and letting the static and
298 // dynamic linkers do the rest, the runtime works by having that field
299 // instead point to a C-string that is the name of the superclass.
300 // At runtime the objc initialization updates that pointer and sets
301 // it to point to the actual super class. As far as the linker
302 // knows it is just a pointer to a string. But then someone wanted the
303 // linker to issue errors at build time if the superclass was not found.
304 // So they figured out a way in mach-o object format to use an absolute
305 // symbols (.objc_class_name_Foo = 0) and a floating reference
306 // (.reference .objc_class_name_Bar) to cause the linker into erroring when
307 // a class was missing.
308 // The following synthesizes the implicit .objc_* symbols for the linker
309 // from the ObjC data structures generated by the front end.
310 if (v->hasSection() /* && isTargetDarwin */) {
311 // special case if this data blob is an ObjC class definition
312 if (v->getSection().compare(0, 15, "__OBJC,__class,") == 0) {
313 if (GlobalVariable *gv = dyn_cast<GlobalVariable>(v)) {
314 addObjCClass(gv);
315 }
316 }
317
318 // special case if this data blob is an ObjC category definition
319 else if (v->getSection().compare(0, 18, "__OBJC,__category,") == 0) {
320 if (GlobalVariable *gv = dyn_cast<GlobalVariable>(v)) {
321 addObjCCategory(gv);
322 }
323 }
324
325 // special case if this data blob is the list of referenced classes
326 else if (v->getSection().compare(0, 18, "__OBJC,__cls_refs,") == 0) {
327 if (GlobalVariable *gv = dyn_cast<GlobalVariable>(v)) {
328 addObjCClassRef(gv);
329 }
330 }
331 }
332
333 // add external symbols referenced by this data.
334 for (unsigned count = 0, total = v->getNumOperands();
335 count != total; ++count) {
336 findExternalRefs(v->getOperand(count), mangler);
337 }
338}
339
340
341void LTOModule::addDefinedSymbol(GlobalValue *def, Mangler &mangler,
342 bool isFunction) {
343 // ignore all llvm.* symbols
344 if (def->getName().startswith("llvm."))
345 return;
346
Rafael Espindola4cb310b2011-02-01 00:41:51 +0000347 // ignore available_externally
348 if (def->hasAvailableExternallyLinkage())
349 return;
350
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000351 // string is owned by _defines
Rafael Espindolaef1860a2011-02-11 05:23:09 +0000352 SmallString<64> Buffer;
353 mangler.getNameWithPrefix(Buffer, def, false);
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000354
355 // set alignment part log2() can have rounding errors
356 uint32_t align = def->getAlignment();
357 uint32_t attr = align ? CountTrailingZeros_32(def->getAlignment()) : 0;
358
359 // set permissions part
360 if (isFunction)
361 attr |= LTO_SYMBOL_PERMISSIONS_CODE;
362 else {
363 GlobalVariable *gv = dyn_cast<GlobalVariable>(def);
364 if (gv && gv->isConstant())
365 attr |= LTO_SYMBOL_PERMISSIONS_RODATA;
366 else
367 attr |= LTO_SYMBOL_PERMISSIONS_DATA;
368 }
369
370 // set definition part
Bill Wendling563ef5e2010-09-27 18:05:19 +0000371 if (def->hasWeakLinkage() || def->hasLinkOnceLinkage() ||
372 def->hasLinkerPrivateWeakLinkage() ||
Bill Wendling7afea0c2010-09-27 20:17:45 +0000373 def->hasLinkerPrivateWeakDefAutoLinkage())
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000374 attr |= LTO_SYMBOL_DEFINITION_WEAK;
Bill Wendling7afea0c2010-09-27 20:17:45 +0000375 else if (def->hasCommonLinkage())
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000376 attr |= LTO_SYMBOL_DEFINITION_TENTATIVE;
Bill Wendling7afea0c2010-09-27 20:17:45 +0000377 else
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000378 attr |= LTO_SYMBOL_DEFINITION_REGULAR;
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000379
380 // set scope part
381 if (def->hasHiddenVisibility())
382 attr |= LTO_SYMBOL_SCOPE_HIDDEN;
383 else if (def->hasProtectedVisibility())
384 attr |= LTO_SYMBOL_SCOPE_PROTECTED;
Bill Wendling7afea0c2010-09-27 20:17:45 +0000385 else if (def->hasExternalLinkage() || def->hasWeakLinkage() ||
386 def->hasLinkOnceLinkage() || def->hasCommonLinkage() ||
387 def->hasLinkerPrivateWeakLinkage())
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000388 attr |= LTO_SYMBOL_SCOPE_DEFAULT;
Bill Wendling7afea0c2010-09-27 20:17:45 +0000389 else if (def->hasLinkerPrivateWeakDefAutoLinkage())
390 attr |= LTO_SYMBOL_SCOPE_DEFAULT_CAN_BE_HIDDEN;
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000391 else
392 attr |= LTO_SYMBOL_SCOPE_INTERNAL;
393
394 // add to table of symbols
395 NameAndAttributes info;
Rafael Espindolacd6c93e2011-02-20 16:27:25 +0000396 StringSet::value_type &entry = _defines.GetOrCreateValue(Buffer.c_str());
397 entry.setValue(1);
398
399 StringRef Name = entry.getKey();
400 info.name = Name.data();
401 assert(info.name[Name.size()] == '\0');
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000402 info.attributes = (lto_symbol_attributes)attr;
403 _symbols.push_back(info);
Nick Kledzik77595fc2008-02-26 20:26:43 +0000404}
405
Rafael Espindola38c4e532011-03-02 04:14:42 +0000406void LTOModule::addAsmGlobalSymbol(const char *name,
407 lto_symbol_attributes scope) {
Rafael Espindolacd6c93e2011-02-20 16:27:25 +0000408 StringSet::value_type &entry = _defines.GetOrCreateValue(name);
409
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000410 // only add new define if not already defined
Rafael Espindolacd6c93e2011-02-20 16:27:25 +0000411 if (entry.getValue())
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000412 return;
413
Rafael Espindolacd6c93e2011-02-20 16:27:25 +0000414 entry.setValue(1);
415 const char *symbolName = entry.getKey().data();
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000416 uint32_t attr = LTO_SYMBOL_DEFINITION_REGULAR;
Rafael Espindola38c4e532011-03-02 04:14:42 +0000417 attr |= scope;
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000418 NameAndAttributes info;
419 info.name = symbolName;
420 info.attributes = (lto_symbol_attributes)attr;
421 _symbols.push_back(info);
Devang Patelc2aec572008-07-16 18:06:52 +0000422}
Nick Kledzik77595fc2008-02-26 20:26:43 +0000423
Rafael Espindola38c4e532011-03-02 04:14:42 +0000424void LTOModule::addAsmGlobalSymbolUndef(const char *name) {
425 StringMap<NameAndAttributes>::value_type &entry =
426 _undefines.GetOrCreateValue(name);
427
428 _asm_undefines.push_back(entry.getKey().data());
429
430 // we already have the symbol
431 if (entry.getValue().name)
432 return;
433
434 uint32_t attr = LTO_SYMBOL_DEFINITION_UNDEFINED;;
435 attr |= LTO_SYMBOL_SCOPE_DEFAULT;
436 NameAndAttributes info;
437 info.name = entry.getKey().data();
438 info.attributes = (lto_symbol_attributes)attr;
439
440 entry.setValue(info);
441}
442
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000443void LTOModule::addPotentialUndefinedSymbol(GlobalValue *decl,
444 Mangler &mangler) {
445 // ignore all llvm.* symbols
446 if (decl->getName().startswith("llvm."))
447 return;
Nick Kledzik3eb445f2009-06-01 20:33:09 +0000448
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000449 // ignore all aliases
450 if (isa<GlobalAlias>(decl))
451 return;
Nick Lewycky485ded02009-07-09 06:03:04 +0000452
Rafael Espindolaef1860a2011-02-11 05:23:09 +0000453 SmallString<64> name;
454 mangler.getNameWithPrefix(name, decl, false);
Rafael Espindola7431af02009-04-24 16:55:21 +0000455
Rafael Espindolacd6c93e2011-02-20 16:27:25 +0000456 StringMap<NameAndAttributes>::value_type &entry =
457 _undefines.GetOrCreateValue(name.c_str());
458
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000459 // we already have the symbol
Rafael Espindolacd6c93e2011-02-20 16:27:25 +0000460 if (entry.getValue().name)
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000461 return;
Rafael Espindola7431af02009-04-24 16:55:21 +0000462
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000463 NameAndAttributes info;
Rafael Espindolacd6c93e2011-02-20 16:27:25 +0000464
465 info.name = entry.getKey().data();
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000466 if (decl->hasExternalWeakLinkage())
467 info.attributes = LTO_SYMBOL_DEFINITION_WEAKUNDEF;
468 else
469 info.attributes = LTO_SYMBOL_DEFINITION_UNDEFINED;
Rafael Espindolacd6c93e2011-02-20 16:27:25 +0000470
471 entry.setValue(info);
Nick Kledzik77595fc2008-02-26 20:26:43 +0000472}
473
474
475
Nick Lewyckyd42b58b2009-07-26 22:16:39 +0000476// Find external symbols referenced by VALUE. This is a recursive function.
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000477void LTOModule::findExternalRefs(Value *value, Mangler &mangler) {
478 if (GlobalValue *gv = dyn_cast<GlobalValue>(value)) {
479 if (!gv->hasExternalLinkage())
480 addPotentialUndefinedSymbol(gv, mangler);
481 // If this is a variable definition, do not recursively process
482 // initializer. It might contain a reference to this variable
483 // and cause an infinite loop. The initializer will be
484 // processed in addDefinedDataSymbol().
485 return;
486 }
Nick Kledzik77595fc2008-02-26 20:26:43 +0000487
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000488 // GlobalValue, even with InternalLinkage type, may have operands with
489 // ExternalLinkage type. Do not ignore these operands.
490 if (Constant *c = dyn_cast<Constant>(value)) {
491 // Handle ConstantExpr, ConstantStruct, ConstantArry etc.
492 for (unsigned i = 0, e = c->getNumOperands(); i != e; ++i)
493 findExternalRefs(c->getOperand(i), mangler);
494 }
495}
496
Rafael Espindola38c4e532011-03-02 04:14:42 +0000497namespace {
498 class RecordStreamer : public MCStreamer {
499 public:
500 enum State { NeverSeen, Global, Defined, DefinedGlobal, Used};
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000501
Rafael Espindola38c4e532011-03-02 04:14:42 +0000502 private:
503 StringMap<State> Symbols;
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000504
Rafael Espindola38c4e532011-03-02 04:14:42 +0000505 void markDefined(const MCSymbol &Symbol) {
506 State &S = Symbols[Symbol.getName()];
507 switch (S) {
508 case DefinedGlobal:
509 case Global:
510 S = DefinedGlobal;
511 break;
512 case NeverSeen:
513 case Defined:
514 case Used:
515 S = Defined;
516 break;
517 }
518 }
519 void markGlobal(const MCSymbol &Symbol) {
520 State &S = Symbols[Symbol.getName()];
521 switch (S) {
522 case DefinedGlobal:
523 case Defined:
524 S = DefinedGlobal;
525 break;
526
527 case NeverSeen:
528 case Global:
529 case Used:
530 S = Global;
531 break;
532 }
533 }
534 void markUsed(const MCSymbol &Symbol) {
535 State &S = Symbols[Symbol.getName()];
536 switch (S) {
537 case DefinedGlobal:
538 case Defined:
539 case Global:
540 break;
541
542 case NeverSeen:
543 case Used:
544 S = Used;
545 break;
546 }
547 }
548
549 // FIXME: mostly copied for the obj streamer.
550 void AddValueSymbols(const MCExpr *Value) {
551 switch (Value->getKind()) {
552 case MCExpr::Target:
553 // FIXME: What should we do in here?
554 break;
555
556 case MCExpr::Constant:
557 break;
558
559 case MCExpr::Binary: {
560 const MCBinaryExpr *BE = cast<MCBinaryExpr>(Value);
561 AddValueSymbols(BE->getLHS());
562 AddValueSymbols(BE->getRHS());
563 break;
564 }
565
566 case MCExpr::SymbolRef:
567 markUsed(cast<MCSymbolRefExpr>(Value)->getSymbol());
568 break;
569
570 case MCExpr::Unary:
571 AddValueSymbols(cast<MCUnaryExpr>(Value)->getSubExpr());
572 break;
573 }
574 }
575
576 public:
577 typedef StringMap<State>::const_iterator const_iterator;
578
579 const_iterator begin() {
580 return Symbols.begin();
581 }
582
583 const_iterator end() {
584 return Symbols.end();
585 }
586
587 RecordStreamer(MCContext &Context) : MCStreamer(Context) {}
588
589 virtual void ChangeSection(const MCSection *Section) {}
590 virtual void InitSections() {}
591 virtual void EmitLabel(MCSymbol *Symbol) {
592 Symbol->setSection(*getCurrentSection());
593 markDefined(*Symbol);
594 }
595 virtual void EmitAssemblerFlag(MCAssemblerFlag Flag) {}
596 virtual void EmitThumbFunc(MCSymbol *Func) {}
597 virtual void EmitAssignment(MCSymbol *Symbol, const MCExpr *Value) {
598 // FIXME: should we handle aliases?
599 markDefined(*Symbol);
600 }
601 virtual void EmitSymbolAttribute(MCSymbol *Symbol, MCSymbolAttr Attribute) {
602 if (Attribute == MCSA_Global)
603 markGlobal(*Symbol);
604 }
605 virtual void EmitSymbolDesc(MCSymbol *Symbol, unsigned DescValue) {}
606 virtual void EmitWeakReference(MCSymbol *Alias, const MCSymbol *Symbol) {}
607 virtual void BeginCOFFSymbolDef(const MCSymbol *Symbol) {}
608 virtual void EmitCOFFSymbolStorageClass(int StorageClass) {}
609 virtual void EmitZerofill(const MCSection *Section, MCSymbol *Symbol,
610 unsigned Size , unsigned ByteAlignment) {
611 markDefined(*Symbol);
612 }
613 virtual void EmitCOFFSymbolType(int Type) {}
614 virtual void EndCOFFSymbolDef() {}
615 virtual void EmitCommonSymbol(MCSymbol *Symbol, uint64_t Size,
616 unsigned ByteAlignment) {
617 markDefined(*Symbol);
618 }
619 virtual void EmitELFSize(MCSymbol *Symbol, const MCExpr *Value) {}
620 virtual void EmitLocalCommonSymbol(MCSymbol *Symbol, uint64_t Size) {}
621 virtual void EmitTBSSSymbol(const MCSection *Section, MCSymbol *Symbol,
622 uint64_t Size, unsigned ByteAlignment) {}
623 virtual void EmitBytes(StringRef Data, unsigned AddrSpace) {}
624 virtual void EmitValueImpl(const MCExpr *Value, unsigned Size,
625 bool isPCRel, unsigned AddrSpace) {}
626 virtual void EmitULEB128Value(const MCExpr *Value,
627 unsigned AddrSpace = 0) {}
628 virtual void EmitSLEB128Value(const MCExpr *Value,
629 unsigned AddrSpace = 0) {}
630 virtual void EmitValueToAlignment(unsigned ByteAlignment, int64_t Value,
631 unsigned ValueSize,
632 unsigned MaxBytesToEmit) {}
633 virtual void EmitCodeAlignment(unsigned ByteAlignment,
634 unsigned MaxBytesToEmit) {}
635 virtual void EmitValueToOffset(const MCExpr *Offset,
636 unsigned char Value ) {}
637 virtual void EmitFileDirective(StringRef Filename) {}
638 virtual void EmitDwarfAdvanceLineAddr(int64_t LineDelta,
639 const MCSymbol *LastLabel,
640 const MCSymbol *Label) {}
641
642 virtual void EmitInstruction(const MCInst &Inst) {
643 // Scan for values.
644 for (unsigned i = Inst.getNumOperands(); i--; )
645 if (Inst.getOperand(i).isExpr())
646 AddValueSymbols(Inst.getOperand(i).getExpr());
647 }
648 virtual void Finish() {}
649 };
650}
651
652bool LTOModule::addAsmGlobalSymbols(MCContext &Context) {
653 const std::string &inlineAsm = _module->getModuleInlineAsm();
654
655 OwningPtr<RecordStreamer> Streamer(new RecordStreamer(Context));
656 MemoryBuffer *Buffer = MemoryBuffer::getMemBuffer(inlineAsm);
657 SourceMgr SrcMgr;
658 SrcMgr.AddNewSourceBuffer(Buffer, SMLoc());
659 OwningPtr<MCAsmParser> Parser(createMCAsmParser(_target->getTarget(), SrcMgr,
660 Context, *Streamer,
661 *_target->getMCAsmInfo()));
662 OwningPtr<TargetAsmParser>
663 TAP(_target->getTarget().createAsmParser(*Parser.get(), *_target.get()));
664 Parser->setTargetParser(*TAP);
665 int Res = Parser->Run(false);
666 if (Res)
667 return true;
668
669 for (RecordStreamer::const_iterator i = Streamer->begin(),
670 e = Streamer->end(); i != e; ++i) {
671 StringRef Key = i->first();
672 RecordStreamer::State Value = i->second;
673 if (Value == RecordStreamer::DefinedGlobal)
674 addAsmGlobalSymbol(Key.data(), LTO_SYMBOL_SCOPE_DEFAULT);
675 else if (Value == RecordStreamer::Defined)
676 addAsmGlobalSymbol(Key.data(), LTO_SYMBOL_SCOPE_INTERNAL);
677 else if (Value == RecordStreamer::Global ||
678 Value == RecordStreamer::Used)
679 addAsmGlobalSymbolUndef(Key.data());
680 }
681 return false;
682}
683
684bool LTOModule::ParseSymbols() {
Daniel Dunbare41d9002010-08-10 23:46:46 +0000685 // Use mangler to add GlobalPrefix to names to match linker names.
Rafael Espindola89b93722010-12-10 07:39:47 +0000686 MCContext Context(*_target->getMCAsmInfo(), NULL);
Daniel Dunbare41d9002010-08-10 23:46:46 +0000687 Mangler mangler(Context, *_target->getTargetData());
Gabor Greif4136e7b2009-09-23 02:46:12 +0000688
Daniel Dunbare41d9002010-08-10 23:46:46 +0000689 // add functions
690 for (Module::iterator f = _module->begin(); f != _module->end(); ++f) {
691 if (f->isDeclaration())
692 addPotentialUndefinedSymbol(f, mangler);
693 else
694 addDefinedFunctionSymbol(f, mangler);
695 }
Nick Kledzik77595fc2008-02-26 20:26:43 +0000696
Daniel Dunbare41d9002010-08-10 23:46:46 +0000697 // add data
698 for (Module::global_iterator v = _module->global_begin(),
699 e = _module->global_end(); v != e; ++v) {
700 if (v->isDeclaration())
701 addPotentialUndefinedSymbol(v, mangler);
702 else
703 addDefinedDataSymbol(v, mangler);
704 }
Nick Kledzik77595fc2008-02-26 20:26:43 +0000705
Daniel Dunbare41d9002010-08-10 23:46:46 +0000706 // add asm globals
Rafael Espindola38c4e532011-03-02 04:14:42 +0000707 if (addAsmGlobalSymbols(Context))
708 return true;
Daniel Dunbare41d9002010-08-10 23:46:46 +0000709
Rafael Espindola02003ca2010-10-20 04:57:22 +0000710 // add aliases
711 for (Module::alias_iterator i = _module->alias_begin(),
712 e = _module->alias_end(); i != e; ++i) {
713 if (i->isDeclaration())
714 addPotentialUndefinedSymbol(i, mangler);
715 else
716 addDefinedDataSymbol(i, mangler);
717 }
718
Daniel Dunbare41d9002010-08-10 23:46:46 +0000719 // make symbols for all undefines
720 for (StringMap<NameAndAttributes>::iterator it=_undefines.begin();
721 it != _undefines.end(); ++it) {
722 // if this symbol also has a definition, then don't make an undefine
723 // because it is a tentative definition
724 if (_defines.count(it->getKey()) == 0) {
725 NameAndAttributes info = it->getValue();
726 _symbols.push_back(info);
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000727 }
728 }
Rafael Espindola38c4e532011-03-02 04:14:42 +0000729 return false;
Nick Kledzikef194ed2008-02-27 22:25:36 +0000730}
731
732
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000733uint32_t LTOModule::getSymbolCount() {
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000734 return _symbols.size();
Nick Kledzik77595fc2008-02-26 20:26:43 +0000735}
736
737
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000738lto_symbol_attributes LTOModule::getSymbolAttributes(uint32_t index) {
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000739 if (index < _symbols.size())
740 return _symbols[index].attributes;
741 else
742 return lto_symbol_attributes(0);
Nick Kledzik77595fc2008-02-26 20:26:43 +0000743}
744
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000745const char *LTOModule::getSymbolName(uint32_t index) {
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000746 if (index < _symbols.size())
747 return _symbols[index].name;
748 else
749 return NULL;
Nick Kledzik77595fc2008-02-26 20:26:43 +0000750}