blob: 4cfe9ad166e14ac78e125ad821b10cdb656c8ed0 [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;
Rafael Espindola9916d2a2011-03-17 22:18:42 +0000120 return MemoryBuffer::getMemBuffer(StringRef(startPtr, length), "", false);
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000121}
122
123
124LTOModule *LTOModule::makeLTOModule(const void *mem, size_t length,
125 std::string &errMsg) {
126 OwningPtr<MemoryBuffer> buffer(makeBuffer(mem, length));
127 if (!buffer)
128 return NULL;
129 return makeLTOModule(buffer.get(), errMsg);
130}
131
132LTOModule *LTOModule::makeLTOModule(MemoryBuffer *buffer,
133 std::string &errMsg) {
Rafael Espindola38c4e532011-03-02 04:14:42 +0000134 static bool Initialized = false;
135 if (!Initialized) {
136 InitializeAllTargets();
137 InitializeAllAsmParsers();
138 Initialized = true;
139 }
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000140
141 // parse bitcode buffer
142 OwningPtr<Module> m(ParseBitcodeFile(buffer, getGlobalContext(), &errMsg));
143 if (!m)
144 return NULL;
145
146 std::string Triple = m->getTargetTriple();
147 if (Triple.empty())
148 Triple = sys::getHostTriple();
149
150 // find machine architecture for this module
151 const Target *march = TargetRegistry::lookupTarget(Triple, errMsg);
152 if (!march)
153 return NULL;
154
155 // construct LTModule, hand over ownership of module and target
156 SubtargetFeatures Features;
157 Features.getDefaultSubtargetFeatures("" /* cpu */, llvm::Triple(Triple));
158 std::string FeatureStr = Features.getString();
159 TargetMachine *target = march->createTargetMachine(Triple, FeatureStr);
Rafael Espindola38c4e532011-03-02 04:14:42 +0000160 LTOModule *Ret = new LTOModule(m.take(), target);
161 bool Err = Ret->ParseSymbols();
162 if (Err) {
163 delete Ret;
164 return NULL;
165 }
166 return Ret;
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000167}
168
169
170const char *LTOModule::getTargetTriple() {
171 return _module->getTargetTriple().c_str();
172}
173
174void LTOModule::setTargetTriple(const char *triple) {
175 _module->setTargetTriple(triple);
176}
177
178void LTOModule::addDefinedFunctionSymbol(Function *f, Mangler &mangler) {
179 // add to list of defined symbols
180 addDefinedSymbol(f, mangler, true);
Nick Kledzik3eb445f2009-06-01 20:33:09 +0000181}
182
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000183// Get string that data pointer points to.
184bool LTOModule::objcClassNameFromExpression(Constant *c, std::string &name) {
185 if (ConstantExpr *ce = dyn_cast<ConstantExpr>(c)) {
186 Constant *op = ce->getOperand(0);
187 if (GlobalVariable *gvn = dyn_cast<GlobalVariable>(op)) {
188 Constant *cn = gvn->getInitializer();
189 if (ConstantArray *ca = dyn_cast<ConstantArray>(cn)) {
190 if (ca->isCString()) {
191 name = ".objc_class_name_" + ca->getAsString();
192 return true;
Nick Kledzik3eb445f2009-06-01 20:33:09 +0000193 }
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000194 }
Nick Kledzik3eb445f2009-06-01 20:33:09 +0000195 }
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000196 }
197 return false;
198}
199
200// Parse i386/ppc ObjC class data structure.
201void LTOModule::addObjCClass(GlobalVariable *clgv) {
202 if (ConstantStruct *c = dyn_cast<ConstantStruct>(clgv->getInitializer())) {
203 // second slot in __OBJC,__class is pointer to superclass name
204 std::string superclassName;
205 if (objcClassNameFromExpression(c->getOperand(1), superclassName)) {
206 NameAndAttributes info;
Rafael Espindolacd6c93e2011-02-20 16:27:25 +0000207 StringMap<NameAndAttributes>::value_type &entry =
208 _undefines.GetOrCreateValue(superclassName.c_str());
209 if (!entry.getValue().name) {
210 const char *symbolName = entry.getKey().data();
Daniel Dunbar8d0843d2010-08-11 00:11:17 +0000211 info.name = symbolName;
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000212 info.attributes = LTO_SYMBOL_DEFINITION_UNDEFINED;
Rafael Espindolacd6c93e2011-02-20 16:27:25 +0000213 entry.setValue(info);
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000214 }
215 }
216 // third slot in __OBJC,__class is pointer to class name
217 std::string className;
218 if (objcClassNameFromExpression(c->getOperand(2), className)) {
Rafael Espindolacd6c93e2011-02-20 16:27:25 +0000219 StringSet::value_type &entry =
220 _defines.GetOrCreateValue(className.c_str());
221 entry.setValue(1);
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000222 NameAndAttributes info;
Rafael Espindolacd6c93e2011-02-20 16:27:25 +0000223 info.name = entry.getKey().data();
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000224 info.attributes = (lto_symbol_attributes)
225 (LTO_SYMBOL_PERMISSIONS_DATA |
226 LTO_SYMBOL_DEFINITION_REGULAR |
227 LTO_SYMBOL_SCOPE_DEFAULT);
228 _symbols.push_back(info);
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000229 }
230 }
Nick Kledzik3eb445f2009-06-01 20:33:09 +0000231}
232
233
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000234// Parse i386/ppc ObjC category data structure.
235void LTOModule::addObjCCategory(GlobalVariable *clgv) {
236 if (ConstantStruct *c = dyn_cast<ConstantStruct>(clgv->getInitializer())) {
237 // second slot in __OBJC,__category is pointer to target class name
Nick Kledzik3eb445f2009-06-01 20:33:09 +0000238 std::string targetclassName;
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000239 if (objcClassNameFromExpression(c->getOperand(1), targetclassName)) {
240 NameAndAttributes info;
Rafael Espindolacd6c93e2011-02-20 16:27:25 +0000241
242 StringMap<NameAndAttributes>::value_type &entry =
243 _undefines.GetOrCreateValue(targetclassName.c_str());
244
245 if (entry.getValue().name)
246 return;
247
248 const char *symbolName = entry.getKey().data();
249 info.name = symbolName;
250 info.attributes = LTO_SYMBOL_DEFINITION_UNDEFINED;
251 entry.setValue(info);
Nick Kledzik3eb445f2009-06-01 20:33:09 +0000252 }
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000253 }
Nick Kledzik3eb445f2009-06-01 20:33:09 +0000254}
255
256
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000257// Parse i386/ppc ObjC class list data structure.
258void LTOModule::addObjCClassRef(GlobalVariable *clgv) {
259 std::string targetclassName;
260 if (objcClassNameFromExpression(clgv->getInitializer(), targetclassName)) {
Nick Kledzik77595fc2008-02-26 20:26:43 +0000261 NameAndAttributes info;
Rafael Espindolacd6c93e2011-02-20 16:27:25 +0000262
263 StringMap<NameAndAttributes>::value_type &entry =
264 _undefines.GetOrCreateValue(targetclassName.c_str());
265 if (entry.getValue().name)
266 return;
267
268 const char *symbolName = entry.getKey().data();
269 info.name = symbolName;
270 info.attributes = LTO_SYMBOL_DEFINITION_UNDEFINED;
271 entry.setValue(info);
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000272 }
273}
274
275
276void LTOModule::addDefinedDataSymbol(GlobalValue *v, Mangler &mangler) {
277 // Add to list of defined symbols.
278 addDefinedSymbol(v, mangler, false);
279
280 // Special case i386/ppc ObjC data structures in magic sections:
281 // The issue is that the old ObjC object format did some strange
282 // contortions to avoid real linker symbols. For instance, the
283 // ObjC class data structure is allocated statically in the executable
284 // that defines that class. That data structures contains a pointer to
285 // its superclass. But instead of just initializing that part of the
286 // struct to the address of its superclass, and letting the static and
287 // dynamic linkers do the rest, the runtime works by having that field
288 // instead point to a C-string that is the name of the superclass.
289 // At runtime the objc initialization updates that pointer and sets
290 // it to point to the actual super class. As far as the linker
291 // knows it is just a pointer to a string. But then someone wanted the
292 // linker to issue errors at build time if the superclass was not found.
293 // So they figured out a way in mach-o object format to use an absolute
294 // symbols (.objc_class_name_Foo = 0) and a floating reference
295 // (.reference .objc_class_name_Bar) to cause the linker into erroring when
296 // a class was missing.
297 // The following synthesizes the implicit .objc_* symbols for the linker
298 // from the ObjC data structures generated by the front end.
299 if (v->hasSection() /* && isTargetDarwin */) {
300 // special case if this data blob is an ObjC class definition
301 if (v->getSection().compare(0, 15, "__OBJC,__class,") == 0) {
302 if (GlobalVariable *gv = dyn_cast<GlobalVariable>(v)) {
303 addObjCClass(gv);
304 }
305 }
306
307 // special case if this data blob is an ObjC category definition
308 else if (v->getSection().compare(0, 18, "__OBJC,__category,") == 0) {
309 if (GlobalVariable *gv = dyn_cast<GlobalVariable>(v)) {
310 addObjCCategory(gv);
311 }
312 }
313
314 // special case if this data blob is the list of referenced classes
315 else if (v->getSection().compare(0, 18, "__OBJC,__cls_refs,") == 0) {
316 if (GlobalVariable *gv = dyn_cast<GlobalVariable>(v)) {
317 addObjCClassRef(gv);
318 }
319 }
320 }
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000321}
322
323
324void LTOModule::addDefinedSymbol(GlobalValue *def, Mangler &mangler,
325 bool isFunction) {
326 // ignore all llvm.* symbols
327 if (def->getName().startswith("llvm."))
328 return;
329
330 // string is owned by _defines
Rafael Espindolaef1860a2011-02-11 05:23:09 +0000331 SmallString<64> Buffer;
332 mangler.getNameWithPrefix(Buffer, def, false);
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000333
334 // set alignment part log2() can have rounding errors
335 uint32_t align = def->getAlignment();
336 uint32_t attr = align ? CountTrailingZeros_32(def->getAlignment()) : 0;
337
338 // set permissions part
339 if (isFunction)
340 attr |= LTO_SYMBOL_PERMISSIONS_CODE;
341 else {
342 GlobalVariable *gv = dyn_cast<GlobalVariable>(def);
343 if (gv && gv->isConstant())
344 attr |= LTO_SYMBOL_PERMISSIONS_RODATA;
345 else
346 attr |= LTO_SYMBOL_PERMISSIONS_DATA;
347 }
348
349 // set definition part
Bill Wendling563ef5e2010-09-27 18:05:19 +0000350 if (def->hasWeakLinkage() || def->hasLinkOnceLinkage() ||
351 def->hasLinkerPrivateWeakLinkage() ||
Bill Wendling7afea0c2010-09-27 20:17:45 +0000352 def->hasLinkerPrivateWeakDefAutoLinkage())
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000353 attr |= LTO_SYMBOL_DEFINITION_WEAK;
Bill Wendling7afea0c2010-09-27 20:17:45 +0000354 else if (def->hasCommonLinkage())
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000355 attr |= LTO_SYMBOL_DEFINITION_TENTATIVE;
Bill Wendling7afea0c2010-09-27 20:17:45 +0000356 else
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000357 attr |= LTO_SYMBOL_DEFINITION_REGULAR;
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000358
359 // set scope part
360 if (def->hasHiddenVisibility())
361 attr |= LTO_SYMBOL_SCOPE_HIDDEN;
362 else if (def->hasProtectedVisibility())
363 attr |= LTO_SYMBOL_SCOPE_PROTECTED;
Bill Wendling7afea0c2010-09-27 20:17:45 +0000364 else if (def->hasExternalLinkage() || def->hasWeakLinkage() ||
365 def->hasLinkOnceLinkage() || def->hasCommonLinkage() ||
366 def->hasLinkerPrivateWeakLinkage())
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000367 attr |= LTO_SYMBOL_SCOPE_DEFAULT;
Bill Wendling7afea0c2010-09-27 20:17:45 +0000368 else if (def->hasLinkerPrivateWeakDefAutoLinkage())
369 attr |= LTO_SYMBOL_SCOPE_DEFAULT_CAN_BE_HIDDEN;
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000370 else
371 attr |= LTO_SYMBOL_SCOPE_INTERNAL;
372
373 // add to table of symbols
374 NameAndAttributes info;
Rafael Espindolacd6c93e2011-02-20 16:27:25 +0000375 StringSet::value_type &entry = _defines.GetOrCreateValue(Buffer.c_str());
376 entry.setValue(1);
377
378 StringRef Name = entry.getKey();
379 info.name = Name.data();
380 assert(info.name[Name.size()] == '\0');
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000381 info.attributes = (lto_symbol_attributes)attr;
382 _symbols.push_back(info);
Nick Kledzik77595fc2008-02-26 20:26:43 +0000383}
384
Rafael Espindola38c4e532011-03-02 04:14:42 +0000385void LTOModule::addAsmGlobalSymbol(const char *name,
386 lto_symbol_attributes scope) {
Rafael Espindolacd6c93e2011-02-20 16:27:25 +0000387 StringSet::value_type &entry = _defines.GetOrCreateValue(name);
388
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000389 // only add new define if not already defined
Rafael Espindolacd6c93e2011-02-20 16:27:25 +0000390 if (entry.getValue())
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000391 return;
392
Rafael Espindolacd6c93e2011-02-20 16:27:25 +0000393 entry.setValue(1);
394 const char *symbolName = entry.getKey().data();
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000395 uint32_t attr = LTO_SYMBOL_DEFINITION_REGULAR;
Rafael Espindola38c4e532011-03-02 04:14:42 +0000396 attr |= scope;
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000397 NameAndAttributes info;
398 info.name = symbolName;
399 info.attributes = (lto_symbol_attributes)attr;
400 _symbols.push_back(info);
Devang Patelc2aec572008-07-16 18:06:52 +0000401}
Nick Kledzik77595fc2008-02-26 20:26:43 +0000402
Rafael Espindola38c4e532011-03-02 04:14:42 +0000403void LTOModule::addAsmGlobalSymbolUndef(const char *name) {
404 StringMap<NameAndAttributes>::value_type &entry =
405 _undefines.GetOrCreateValue(name);
406
407 _asm_undefines.push_back(entry.getKey().data());
408
409 // we already have the symbol
410 if (entry.getValue().name)
411 return;
412
413 uint32_t attr = LTO_SYMBOL_DEFINITION_UNDEFINED;;
414 attr |= LTO_SYMBOL_SCOPE_DEFAULT;
415 NameAndAttributes info;
416 info.name = entry.getKey().data();
417 info.attributes = (lto_symbol_attributes)attr;
418
419 entry.setValue(info);
420}
421
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000422void LTOModule::addPotentialUndefinedSymbol(GlobalValue *decl,
423 Mangler &mangler) {
424 // ignore all llvm.* symbols
425 if (decl->getName().startswith("llvm."))
426 return;
Nick Kledzik3eb445f2009-06-01 20:33:09 +0000427
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000428 // ignore all aliases
429 if (isa<GlobalAlias>(decl))
430 return;
Nick Lewycky485ded02009-07-09 06:03:04 +0000431
Rafael Espindolaef1860a2011-02-11 05:23:09 +0000432 SmallString<64> name;
433 mangler.getNameWithPrefix(name, decl, false);
Rafael Espindola7431af02009-04-24 16:55:21 +0000434
Rafael Espindolacd6c93e2011-02-20 16:27:25 +0000435 StringMap<NameAndAttributes>::value_type &entry =
436 _undefines.GetOrCreateValue(name.c_str());
437
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000438 // we already have the symbol
Rafael Espindolacd6c93e2011-02-20 16:27:25 +0000439 if (entry.getValue().name)
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000440 return;
Rafael Espindola7431af02009-04-24 16:55:21 +0000441
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000442 NameAndAttributes info;
Rafael Espindolacd6c93e2011-02-20 16:27:25 +0000443
444 info.name = entry.getKey().data();
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000445 if (decl->hasExternalWeakLinkage())
446 info.attributes = LTO_SYMBOL_DEFINITION_WEAKUNDEF;
447 else
448 info.attributes = LTO_SYMBOL_DEFINITION_UNDEFINED;
Rafael Espindolacd6c93e2011-02-20 16:27:25 +0000449
450 entry.setValue(info);
Nick Kledzik77595fc2008-02-26 20:26:43 +0000451}
452
453
Rafael Espindola38c4e532011-03-02 04:14:42 +0000454namespace {
455 class RecordStreamer : public MCStreamer {
456 public:
457 enum State { NeverSeen, Global, Defined, DefinedGlobal, Used};
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000458
Rafael Espindola38c4e532011-03-02 04:14:42 +0000459 private:
460 StringMap<State> Symbols;
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000461
Rafael Espindola38c4e532011-03-02 04:14:42 +0000462 void markDefined(const MCSymbol &Symbol) {
463 State &S = Symbols[Symbol.getName()];
464 switch (S) {
465 case DefinedGlobal:
466 case Global:
467 S = DefinedGlobal;
468 break;
469 case NeverSeen:
470 case Defined:
471 case Used:
472 S = Defined;
473 break;
474 }
475 }
476 void markGlobal(const MCSymbol &Symbol) {
477 State &S = Symbols[Symbol.getName()];
478 switch (S) {
479 case DefinedGlobal:
480 case Defined:
481 S = DefinedGlobal;
482 break;
483
484 case NeverSeen:
485 case Global:
486 case Used:
487 S = Global;
488 break;
489 }
490 }
491 void markUsed(const MCSymbol &Symbol) {
492 State &S = Symbols[Symbol.getName()];
493 switch (S) {
494 case DefinedGlobal:
495 case Defined:
496 case Global:
497 break;
498
499 case NeverSeen:
500 case Used:
501 S = Used;
502 break;
503 }
504 }
505
506 // FIXME: mostly copied for the obj streamer.
507 void AddValueSymbols(const MCExpr *Value) {
508 switch (Value->getKind()) {
509 case MCExpr::Target:
510 // FIXME: What should we do in here?
511 break;
512
513 case MCExpr::Constant:
514 break;
515
516 case MCExpr::Binary: {
517 const MCBinaryExpr *BE = cast<MCBinaryExpr>(Value);
518 AddValueSymbols(BE->getLHS());
519 AddValueSymbols(BE->getRHS());
520 break;
521 }
522
523 case MCExpr::SymbolRef:
524 markUsed(cast<MCSymbolRefExpr>(Value)->getSymbol());
525 break;
526
527 case MCExpr::Unary:
528 AddValueSymbols(cast<MCUnaryExpr>(Value)->getSubExpr());
529 break;
530 }
531 }
532
533 public:
534 typedef StringMap<State>::const_iterator const_iterator;
535
536 const_iterator begin() {
537 return Symbols.begin();
538 }
539
540 const_iterator end() {
541 return Symbols.end();
542 }
543
544 RecordStreamer(MCContext &Context) : MCStreamer(Context) {}
545
546 virtual void ChangeSection(const MCSection *Section) {}
547 virtual void InitSections() {}
548 virtual void EmitLabel(MCSymbol *Symbol) {
549 Symbol->setSection(*getCurrentSection());
550 markDefined(*Symbol);
551 }
552 virtual void EmitAssemblerFlag(MCAssemblerFlag Flag) {}
553 virtual void EmitThumbFunc(MCSymbol *Func) {}
554 virtual void EmitAssignment(MCSymbol *Symbol, const MCExpr *Value) {
555 // FIXME: should we handle aliases?
556 markDefined(*Symbol);
557 }
558 virtual void EmitSymbolAttribute(MCSymbol *Symbol, MCSymbolAttr Attribute) {
559 if (Attribute == MCSA_Global)
560 markGlobal(*Symbol);
561 }
562 virtual void EmitSymbolDesc(MCSymbol *Symbol, unsigned DescValue) {}
563 virtual void EmitWeakReference(MCSymbol *Alias, const MCSymbol *Symbol) {}
564 virtual void BeginCOFFSymbolDef(const MCSymbol *Symbol) {}
565 virtual void EmitCOFFSymbolStorageClass(int StorageClass) {}
566 virtual void EmitZerofill(const MCSection *Section, MCSymbol *Symbol,
567 unsigned Size , unsigned ByteAlignment) {
568 markDefined(*Symbol);
569 }
570 virtual void EmitCOFFSymbolType(int Type) {}
571 virtual void EndCOFFSymbolDef() {}
572 virtual void EmitCommonSymbol(MCSymbol *Symbol, uint64_t Size,
573 unsigned ByteAlignment) {
574 markDefined(*Symbol);
575 }
576 virtual void EmitELFSize(MCSymbol *Symbol, const MCExpr *Value) {}
577 virtual void EmitLocalCommonSymbol(MCSymbol *Symbol, uint64_t Size) {}
578 virtual void EmitTBSSSymbol(const MCSection *Section, MCSymbol *Symbol,
579 uint64_t Size, unsigned ByteAlignment) {}
580 virtual void EmitBytes(StringRef Data, unsigned AddrSpace) {}
581 virtual void EmitValueImpl(const MCExpr *Value, unsigned Size,
582 bool isPCRel, unsigned AddrSpace) {}
583 virtual void EmitULEB128Value(const MCExpr *Value,
584 unsigned AddrSpace = 0) {}
585 virtual void EmitSLEB128Value(const MCExpr *Value,
586 unsigned AddrSpace = 0) {}
587 virtual void EmitValueToAlignment(unsigned ByteAlignment, int64_t Value,
588 unsigned ValueSize,
589 unsigned MaxBytesToEmit) {}
590 virtual void EmitCodeAlignment(unsigned ByteAlignment,
591 unsigned MaxBytesToEmit) {}
592 virtual void EmitValueToOffset(const MCExpr *Offset,
593 unsigned char Value ) {}
594 virtual void EmitFileDirective(StringRef Filename) {}
595 virtual void EmitDwarfAdvanceLineAddr(int64_t LineDelta,
596 const MCSymbol *LastLabel,
597 const MCSymbol *Label) {}
598
599 virtual void EmitInstruction(const MCInst &Inst) {
600 // Scan for values.
601 for (unsigned i = Inst.getNumOperands(); i--; )
602 if (Inst.getOperand(i).isExpr())
603 AddValueSymbols(Inst.getOperand(i).getExpr());
604 }
605 virtual void Finish() {}
606 };
607}
608
609bool LTOModule::addAsmGlobalSymbols(MCContext &Context) {
610 const std::string &inlineAsm = _module->getModuleInlineAsm();
611
612 OwningPtr<RecordStreamer> Streamer(new RecordStreamer(Context));
613 MemoryBuffer *Buffer = MemoryBuffer::getMemBuffer(inlineAsm);
614 SourceMgr SrcMgr;
615 SrcMgr.AddNewSourceBuffer(Buffer, SMLoc());
616 OwningPtr<MCAsmParser> Parser(createMCAsmParser(_target->getTarget(), SrcMgr,
617 Context, *Streamer,
618 *_target->getMCAsmInfo()));
619 OwningPtr<TargetAsmParser>
620 TAP(_target->getTarget().createAsmParser(*Parser.get(), *_target.get()));
621 Parser->setTargetParser(*TAP);
622 int Res = Parser->Run(false);
623 if (Res)
624 return true;
625
626 for (RecordStreamer::const_iterator i = Streamer->begin(),
627 e = Streamer->end(); i != e; ++i) {
628 StringRef Key = i->first();
629 RecordStreamer::State Value = i->second;
630 if (Value == RecordStreamer::DefinedGlobal)
631 addAsmGlobalSymbol(Key.data(), LTO_SYMBOL_SCOPE_DEFAULT);
632 else if (Value == RecordStreamer::Defined)
633 addAsmGlobalSymbol(Key.data(), LTO_SYMBOL_SCOPE_INTERNAL);
634 else if (Value == RecordStreamer::Global ||
635 Value == RecordStreamer::Used)
636 addAsmGlobalSymbolUndef(Key.data());
637 }
638 return false;
639}
640
641bool LTOModule::ParseSymbols() {
Daniel Dunbare41d9002010-08-10 23:46:46 +0000642 // Use mangler to add GlobalPrefix to names to match linker names.
Rafael Espindola89b93722010-12-10 07:39:47 +0000643 MCContext Context(*_target->getMCAsmInfo(), NULL);
Daniel Dunbare41d9002010-08-10 23:46:46 +0000644 Mangler mangler(Context, *_target->getTargetData());
Gabor Greif4136e7b2009-09-23 02:46:12 +0000645
Daniel Dunbare41d9002010-08-10 23:46:46 +0000646 // add functions
647 for (Module::iterator f = _module->begin(); f != _module->end(); ++f) {
Rafael Espindola9a4584b2011-03-18 05:12:38 +0000648 if (f->isDeclaration() || f->hasAvailableExternallyLinkage())
Daniel Dunbare41d9002010-08-10 23:46:46 +0000649 addPotentialUndefinedSymbol(f, mangler);
650 else
651 addDefinedFunctionSymbol(f, mangler);
652 }
Nick Kledzik77595fc2008-02-26 20:26:43 +0000653
Daniel Dunbare41d9002010-08-10 23:46:46 +0000654 // add data
655 for (Module::global_iterator v = _module->global_begin(),
656 e = _module->global_end(); v != e; ++v) {
Rafael Espindola9a4584b2011-03-18 05:12:38 +0000657 if (v->isDeclaration() || v->hasAvailableExternallyLinkage())
Daniel Dunbare41d9002010-08-10 23:46:46 +0000658 addPotentialUndefinedSymbol(v, mangler);
659 else
660 addDefinedDataSymbol(v, mangler);
661 }
Nick Kledzik77595fc2008-02-26 20:26:43 +0000662
Daniel Dunbare41d9002010-08-10 23:46:46 +0000663 // add asm globals
Rafael Espindola38c4e532011-03-02 04:14:42 +0000664 if (addAsmGlobalSymbols(Context))
665 return true;
Daniel Dunbare41d9002010-08-10 23:46:46 +0000666
Rafael Espindola02003ca2010-10-20 04:57:22 +0000667 // add aliases
668 for (Module::alias_iterator i = _module->alias_begin(),
669 e = _module->alias_end(); i != e; ++i) {
670 if (i->isDeclaration())
671 addPotentialUndefinedSymbol(i, mangler);
672 else
673 addDefinedDataSymbol(i, mangler);
674 }
675
Daniel Dunbare41d9002010-08-10 23:46:46 +0000676 // make symbols for all undefines
677 for (StringMap<NameAndAttributes>::iterator it=_undefines.begin();
678 it != _undefines.end(); ++it) {
679 // if this symbol also has a definition, then don't make an undefine
680 // because it is a tentative definition
681 if (_defines.count(it->getKey()) == 0) {
682 NameAndAttributes info = it->getValue();
683 _symbols.push_back(info);
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000684 }
685 }
Rafael Espindola38c4e532011-03-02 04:14:42 +0000686 return false;
Nick Kledzikef194ed2008-02-27 22:25:36 +0000687}
688
689
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000690uint32_t LTOModule::getSymbolCount() {
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000691 return _symbols.size();
Nick Kledzik77595fc2008-02-26 20:26:43 +0000692}
693
694
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000695lto_symbol_attributes LTOModule::getSymbolAttributes(uint32_t index) {
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000696 if (index < _symbols.size())
697 return _symbols[index].attributes;
698 else
699 return lto_symbol_attributes(0);
Nick Kledzik77595fc2008-02-26 20:26:43 +0000700}
701
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000702const char *LTOModule::getSymbolName(uint32_t index) {
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000703 if (index < _symbols.size())
704 return _symbols[index].name;
705 else
706 return NULL;
Nick Kledzik77595fc2008-02-26 20:26:43 +0000707}