blob: d9f5fa55bad0d3b2c20384fafed9ea4b17761d90 [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 }
Rafael Espindolaf19d7a72011-03-18 19:51:00 +000094 return makeLTOModule(buffer.take(), errMsg);
Daniel Dunbarb06913d2010-08-10 23:46:39 +000095}
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 }
Rafael Espindolaf19d7a72011-03-18 19:51:00 +0000114 return makeLTOModule(buffer.take(), errMsg);
Rafael Espindolab4cc0312011-02-08 22:40:47 +0000115}
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;
Rafael Espindolaf19d7a72011-03-18 19:51:00 +0000129 return makeLTOModule(buffer.take(), errMsg);
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000130}
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
Rafael Espindolaf19d7a72011-03-18 19:51:00 +0000142 OwningPtr<Module> m(getLazyBitcodeModule(buffer, getGlobalContext(),
143 &errMsg));
144 if (!m) {
145 delete buffer;
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000146 return NULL;
Rafael Espindolaf19d7a72011-03-18 19:51:00 +0000147 }
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000148
149 std::string Triple = m->getTargetTriple();
150 if (Triple.empty())
151 Triple = sys::getHostTriple();
152
153 // find machine architecture for this module
154 const Target *march = TargetRegistry::lookupTarget(Triple, errMsg);
155 if (!march)
156 return NULL;
157
Nick Lewycky333ed452011-04-21 01:54:08 +0000158 // construct LTOModule, hand over ownership of module and target
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000159 SubtargetFeatures Features;
160 Features.getDefaultSubtargetFeatures("" /* cpu */, llvm::Triple(Triple));
161 std::string FeatureStr = Features.getString();
162 TargetMachine *target = march->createTargetMachine(Triple, FeatureStr);
Rafael Espindola38c4e532011-03-02 04:14:42 +0000163 LTOModule *Ret = new LTOModule(m.take(), target);
164 bool Err = Ret->ParseSymbols();
165 if (Err) {
166 delete Ret;
167 return NULL;
168 }
169 return Ret;
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000170}
171
172
173const char *LTOModule::getTargetTriple() {
174 return _module->getTargetTriple().c_str();
175}
176
177void LTOModule::setTargetTriple(const char *triple) {
178 _module->setTargetTriple(triple);
179}
180
181void LTOModule::addDefinedFunctionSymbol(Function *f, Mangler &mangler) {
182 // add to list of defined symbols
183 addDefinedSymbol(f, mangler, true);
Nick Kledzik3eb445f2009-06-01 20:33:09 +0000184}
185
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000186// Get string that data pointer points to.
187bool LTOModule::objcClassNameFromExpression(Constant *c, std::string &name) {
188 if (ConstantExpr *ce = dyn_cast<ConstantExpr>(c)) {
189 Constant *op = ce->getOperand(0);
190 if (GlobalVariable *gvn = dyn_cast<GlobalVariable>(op)) {
191 Constant *cn = gvn->getInitializer();
192 if (ConstantArray *ca = dyn_cast<ConstantArray>(cn)) {
193 if (ca->isCString()) {
194 name = ".objc_class_name_" + ca->getAsString();
195 return true;
Nick Kledzik3eb445f2009-06-01 20:33:09 +0000196 }
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000197 }
Nick Kledzik3eb445f2009-06-01 20:33:09 +0000198 }
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000199 }
200 return false;
201}
202
203// Parse i386/ppc ObjC class data structure.
204void LTOModule::addObjCClass(GlobalVariable *clgv) {
205 if (ConstantStruct *c = dyn_cast<ConstantStruct>(clgv->getInitializer())) {
206 // second slot in __OBJC,__class is pointer to superclass name
207 std::string superclassName;
208 if (objcClassNameFromExpression(c->getOperand(1), superclassName)) {
209 NameAndAttributes info;
Rafael Espindolacd6c93e2011-02-20 16:27:25 +0000210 StringMap<NameAndAttributes>::value_type &entry =
211 _undefines.GetOrCreateValue(superclassName.c_str());
212 if (!entry.getValue().name) {
213 const char *symbolName = entry.getKey().data();
Daniel Dunbar8d0843d2010-08-11 00:11:17 +0000214 info.name = symbolName;
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000215 info.attributes = LTO_SYMBOL_DEFINITION_UNDEFINED;
Rafael Espindolacd6c93e2011-02-20 16:27:25 +0000216 entry.setValue(info);
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000217 }
218 }
219 // third slot in __OBJC,__class is pointer to class name
220 std::string className;
221 if (objcClassNameFromExpression(c->getOperand(2), className)) {
Rafael Espindolacd6c93e2011-02-20 16:27:25 +0000222 StringSet::value_type &entry =
223 _defines.GetOrCreateValue(className.c_str());
224 entry.setValue(1);
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000225 NameAndAttributes info;
Rafael Espindolacd6c93e2011-02-20 16:27:25 +0000226 info.name = entry.getKey().data();
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000227 info.attributes = (lto_symbol_attributes)
228 (LTO_SYMBOL_PERMISSIONS_DATA |
229 LTO_SYMBOL_DEFINITION_REGULAR |
230 LTO_SYMBOL_SCOPE_DEFAULT);
231 _symbols.push_back(info);
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000232 }
233 }
Nick Kledzik3eb445f2009-06-01 20:33:09 +0000234}
235
236
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000237// Parse i386/ppc ObjC category data structure.
238void LTOModule::addObjCCategory(GlobalVariable *clgv) {
239 if (ConstantStruct *c = dyn_cast<ConstantStruct>(clgv->getInitializer())) {
240 // second slot in __OBJC,__category is pointer to target class name
Nick Kledzik3eb445f2009-06-01 20:33:09 +0000241 std::string targetclassName;
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000242 if (objcClassNameFromExpression(c->getOperand(1), targetclassName)) {
243 NameAndAttributes info;
Rafael Espindolacd6c93e2011-02-20 16:27:25 +0000244
245 StringMap<NameAndAttributes>::value_type &entry =
246 _undefines.GetOrCreateValue(targetclassName.c_str());
247
248 if (entry.getValue().name)
249 return;
250
251 const char *symbolName = entry.getKey().data();
252 info.name = symbolName;
253 info.attributes = LTO_SYMBOL_DEFINITION_UNDEFINED;
254 entry.setValue(info);
Nick Kledzik3eb445f2009-06-01 20:33:09 +0000255 }
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000256 }
Nick Kledzik3eb445f2009-06-01 20:33:09 +0000257}
258
259
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000260// Parse i386/ppc ObjC class list data structure.
261void LTOModule::addObjCClassRef(GlobalVariable *clgv) {
262 std::string targetclassName;
263 if (objcClassNameFromExpression(clgv->getInitializer(), targetclassName)) {
Nick Kledzik77595fc2008-02-26 20:26:43 +0000264 NameAndAttributes info;
Rafael Espindolacd6c93e2011-02-20 16:27:25 +0000265
266 StringMap<NameAndAttributes>::value_type &entry =
267 _undefines.GetOrCreateValue(targetclassName.c_str());
268 if (entry.getValue().name)
269 return;
270
271 const char *symbolName = entry.getKey().data();
272 info.name = symbolName;
273 info.attributes = LTO_SYMBOL_DEFINITION_UNDEFINED;
274 entry.setValue(info);
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000275 }
276}
277
278
279void LTOModule::addDefinedDataSymbol(GlobalValue *v, Mangler &mangler) {
280 // Add to list of defined symbols.
281 addDefinedSymbol(v, mangler, false);
282
283 // Special case i386/ppc ObjC data structures in magic sections:
284 // The issue is that the old ObjC object format did some strange
285 // contortions to avoid real linker symbols. For instance, the
286 // ObjC class data structure is allocated statically in the executable
287 // that defines that class. That data structures contains a pointer to
288 // its superclass. But instead of just initializing that part of the
289 // struct to the address of its superclass, and letting the static and
290 // dynamic linkers do the rest, the runtime works by having that field
291 // instead point to a C-string that is the name of the superclass.
292 // At runtime the objc initialization updates that pointer and sets
293 // it to point to the actual super class. As far as the linker
294 // knows it is just a pointer to a string. But then someone wanted the
295 // linker to issue errors at build time if the superclass was not found.
296 // So they figured out a way in mach-o object format to use an absolute
297 // symbols (.objc_class_name_Foo = 0) and a floating reference
298 // (.reference .objc_class_name_Bar) to cause the linker into erroring when
299 // a class was missing.
300 // The following synthesizes the implicit .objc_* symbols for the linker
301 // from the ObjC data structures generated by the front end.
302 if (v->hasSection() /* && isTargetDarwin */) {
303 // special case if this data blob is an ObjC class definition
304 if (v->getSection().compare(0, 15, "__OBJC,__class,") == 0) {
305 if (GlobalVariable *gv = dyn_cast<GlobalVariable>(v)) {
306 addObjCClass(gv);
307 }
308 }
309
310 // special case if this data blob is an ObjC category definition
311 else if (v->getSection().compare(0, 18, "__OBJC,__category,") == 0) {
312 if (GlobalVariable *gv = dyn_cast<GlobalVariable>(v)) {
313 addObjCCategory(gv);
314 }
315 }
316
317 // special case if this data blob is the list of referenced classes
318 else if (v->getSection().compare(0, 18, "__OBJC,__cls_refs,") == 0) {
319 if (GlobalVariable *gv = dyn_cast<GlobalVariable>(v)) {
320 addObjCClassRef(gv);
321 }
322 }
323 }
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000324}
325
326
327void LTOModule::addDefinedSymbol(GlobalValue *def, Mangler &mangler,
328 bool isFunction) {
329 // ignore all llvm.* symbols
330 if (def->getName().startswith("llvm."))
331 return;
332
333 // string is owned by _defines
Rafael Espindolaef1860a2011-02-11 05:23:09 +0000334 SmallString<64> Buffer;
335 mangler.getNameWithPrefix(Buffer, def, false);
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000336
337 // set alignment part log2() can have rounding errors
338 uint32_t align = def->getAlignment();
339 uint32_t attr = align ? CountTrailingZeros_32(def->getAlignment()) : 0;
340
341 // set permissions part
342 if (isFunction)
343 attr |= LTO_SYMBOL_PERMISSIONS_CODE;
344 else {
345 GlobalVariable *gv = dyn_cast<GlobalVariable>(def);
346 if (gv && gv->isConstant())
347 attr |= LTO_SYMBOL_PERMISSIONS_RODATA;
348 else
349 attr |= LTO_SYMBOL_PERMISSIONS_DATA;
350 }
351
352 // set definition part
Bill Wendling563ef5e2010-09-27 18:05:19 +0000353 if (def->hasWeakLinkage() || def->hasLinkOnceLinkage() ||
354 def->hasLinkerPrivateWeakLinkage() ||
Bill Wendling7afea0c2010-09-27 20:17:45 +0000355 def->hasLinkerPrivateWeakDefAutoLinkage())
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000356 attr |= LTO_SYMBOL_DEFINITION_WEAK;
Bill Wendling7afea0c2010-09-27 20:17:45 +0000357 else if (def->hasCommonLinkage())
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000358 attr |= LTO_SYMBOL_DEFINITION_TENTATIVE;
Bill Wendling7afea0c2010-09-27 20:17:45 +0000359 else
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000360 attr |= LTO_SYMBOL_DEFINITION_REGULAR;
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000361
362 // set scope part
363 if (def->hasHiddenVisibility())
364 attr |= LTO_SYMBOL_SCOPE_HIDDEN;
365 else if (def->hasProtectedVisibility())
366 attr |= LTO_SYMBOL_SCOPE_PROTECTED;
Bill Wendling7afea0c2010-09-27 20:17:45 +0000367 else if (def->hasExternalLinkage() || def->hasWeakLinkage() ||
368 def->hasLinkOnceLinkage() || def->hasCommonLinkage() ||
369 def->hasLinkerPrivateWeakLinkage())
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000370 attr |= LTO_SYMBOL_SCOPE_DEFAULT;
Bill Wendling7afea0c2010-09-27 20:17:45 +0000371 else if (def->hasLinkerPrivateWeakDefAutoLinkage())
372 attr |= LTO_SYMBOL_SCOPE_DEFAULT_CAN_BE_HIDDEN;
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000373 else
374 attr |= LTO_SYMBOL_SCOPE_INTERNAL;
375
376 // add to table of symbols
377 NameAndAttributes info;
Rafael Espindolacd6c93e2011-02-20 16:27:25 +0000378 StringSet::value_type &entry = _defines.GetOrCreateValue(Buffer.c_str());
379 entry.setValue(1);
380
381 StringRef Name = entry.getKey();
382 info.name = Name.data();
383 assert(info.name[Name.size()] == '\0');
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000384 info.attributes = (lto_symbol_attributes)attr;
385 _symbols.push_back(info);
Nick Kledzik77595fc2008-02-26 20:26:43 +0000386}
387
Rafael Espindola38c4e532011-03-02 04:14:42 +0000388void LTOModule::addAsmGlobalSymbol(const char *name,
389 lto_symbol_attributes scope) {
Rafael Espindolacd6c93e2011-02-20 16:27:25 +0000390 StringSet::value_type &entry = _defines.GetOrCreateValue(name);
391
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000392 // only add new define if not already defined
Rafael Espindolacd6c93e2011-02-20 16:27:25 +0000393 if (entry.getValue())
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000394 return;
395
Rafael Espindolacd6c93e2011-02-20 16:27:25 +0000396 entry.setValue(1);
397 const char *symbolName = entry.getKey().data();
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000398 uint32_t attr = LTO_SYMBOL_DEFINITION_REGULAR;
Rafael Espindola38c4e532011-03-02 04:14:42 +0000399 attr |= scope;
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000400 NameAndAttributes info;
401 info.name = symbolName;
402 info.attributes = (lto_symbol_attributes)attr;
403 _symbols.push_back(info);
Devang Patelc2aec572008-07-16 18:06:52 +0000404}
Nick Kledzik77595fc2008-02-26 20:26:43 +0000405
Rafael Espindola38c4e532011-03-02 04:14:42 +0000406void LTOModule::addAsmGlobalSymbolUndef(const char *name) {
407 StringMap<NameAndAttributes>::value_type &entry =
408 _undefines.GetOrCreateValue(name);
409
410 _asm_undefines.push_back(entry.getKey().data());
411
412 // we already have the symbol
413 if (entry.getValue().name)
414 return;
415
416 uint32_t attr = LTO_SYMBOL_DEFINITION_UNDEFINED;;
417 attr |= LTO_SYMBOL_SCOPE_DEFAULT;
418 NameAndAttributes info;
419 info.name = entry.getKey().data();
420 info.attributes = (lto_symbol_attributes)attr;
421
422 entry.setValue(info);
423}
424
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000425void LTOModule::addPotentialUndefinedSymbol(GlobalValue *decl,
426 Mangler &mangler) {
427 // ignore all llvm.* symbols
428 if (decl->getName().startswith("llvm."))
429 return;
Nick Kledzik3eb445f2009-06-01 20:33:09 +0000430
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000431 // ignore all aliases
432 if (isa<GlobalAlias>(decl))
433 return;
Nick Lewycky485ded02009-07-09 06:03:04 +0000434
Rafael Espindolaef1860a2011-02-11 05:23:09 +0000435 SmallString<64> name;
436 mangler.getNameWithPrefix(name, decl, false);
Rafael Espindola7431af02009-04-24 16:55:21 +0000437
Rafael Espindolacd6c93e2011-02-20 16:27:25 +0000438 StringMap<NameAndAttributes>::value_type &entry =
439 _undefines.GetOrCreateValue(name.c_str());
440
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000441 // we already have the symbol
Rafael Espindolacd6c93e2011-02-20 16:27:25 +0000442 if (entry.getValue().name)
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000443 return;
Rafael Espindola7431af02009-04-24 16:55:21 +0000444
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000445 NameAndAttributes info;
Rafael Espindolacd6c93e2011-02-20 16:27:25 +0000446
447 info.name = entry.getKey().data();
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000448 if (decl->hasExternalWeakLinkage())
449 info.attributes = LTO_SYMBOL_DEFINITION_WEAKUNDEF;
450 else
451 info.attributes = LTO_SYMBOL_DEFINITION_UNDEFINED;
Rafael Espindolacd6c93e2011-02-20 16:27:25 +0000452
453 entry.setValue(info);
Nick Kledzik77595fc2008-02-26 20:26:43 +0000454}
455
456
Rafael Espindola38c4e532011-03-02 04:14:42 +0000457namespace {
458 class RecordStreamer : public MCStreamer {
459 public:
460 enum State { NeverSeen, Global, Defined, DefinedGlobal, Used};
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000461
Rafael Espindola38c4e532011-03-02 04:14:42 +0000462 private:
463 StringMap<State> Symbols;
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000464
Rafael Espindola38c4e532011-03-02 04:14:42 +0000465 void markDefined(const MCSymbol &Symbol) {
466 State &S = Symbols[Symbol.getName()];
467 switch (S) {
468 case DefinedGlobal:
469 case Global:
470 S = DefinedGlobal;
471 break;
472 case NeverSeen:
473 case Defined:
474 case Used:
475 S = Defined;
476 break;
477 }
478 }
479 void markGlobal(const MCSymbol &Symbol) {
480 State &S = Symbols[Symbol.getName()];
481 switch (S) {
482 case DefinedGlobal:
483 case Defined:
484 S = DefinedGlobal;
485 break;
486
487 case NeverSeen:
488 case Global:
489 case Used:
490 S = Global;
491 break;
492 }
493 }
494 void markUsed(const MCSymbol &Symbol) {
495 State &S = Symbols[Symbol.getName()];
496 switch (S) {
497 case DefinedGlobal:
498 case Defined:
499 case Global:
500 break;
501
502 case NeverSeen:
503 case Used:
504 S = Used;
505 break;
506 }
507 }
508
509 // FIXME: mostly copied for the obj streamer.
510 void AddValueSymbols(const MCExpr *Value) {
511 switch (Value->getKind()) {
512 case MCExpr::Target:
513 // FIXME: What should we do in here?
514 break;
515
516 case MCExpr::Constant:
517 break;
518
519 case MCExpr::Binary: {
520 const MCBinaryExpr *BE = cast<MCBinaryExpr>(Value);
521 AddValueSymbols(BE->getLHS());
522 AddValueSymbols(BE->getRHS());
523 break;
524 }
525
526 case MCExpr::SymbolRef:
527 markUsed(cast<MCSymbolRefExpr>(Value)->getSymbol());
528 break;
529
530 case MCExpr::Unary:
531 AddValueSymbols(cast<MCUnaryExpr>(Value)->getSubExpr());
532 break;
533 }
534 }
535
536 public:
537 typedef StringMap<State>::const_iterator const_iterator;
538
539 const_iterator begin() {
540 return Symbols.begin();
541 }
542
543 const_iterator end() {
544 return Symbols.end();
545 }
546
547 RecordStreamer(MCContext &Context) : MCStreamer(Context) {}
548
549 virtual void ChangeSection(const MCSection *Section) {}
550 virtual void InitSections() {}
551 virtual void EmitLabel(MCSymbol *Symbol) {
552 Symbol->setSection(*getCurrentSection());
553 markDefined(*Symbol);
554 }
555 virtual void EmitAssemblerFlag(MCAssemblerFlag Flag) {}
556 virtual void EmitThumbFunc(MCSymbol *Func) {}
557 virtual void EmitAssignment(MCSymbol *Symbol, const MCExpr *Value) {
558 // FIXME: should we handle aliases?
559 markDefined(*Symbol);
560 }
561 virtual void EmitSymbolAttribute(MCSymbol *Symbol, MCSymbolAttr Attribute) {
562 if (Attribute == MCSA_Global)
563 markGlobal(*Symbol);
564 }
565 virtual void EmitSymbolDesc(MCSymbol *Symbol, unsigned DescValue) {}
566 virtual void EmitWeakReference(MCSymbol *Alias, const MCSymbol *Symbol) {}
567 virtual void BeginCOFFSymbolDef(const MCSymbol *Symbol) {}
568 virtual void EmitCOFFSymbolStorageClass(int StorageClass) {}
569 virtual void EmitZerofill(const MCSection *Section, MCSymbol *Symbol,
570 unsigned Size , unsigned ByteAlignment) {
571 markDefined(*Symbol);
572 }
573 virtual void EmitCOFFSymbolType(int Type) {}
574 virtual void EndCOFFSymbolDef() {}
575 virtual void EmitCommonSymbol(MCSymbol *Symbol, uint64_t Size,
576 unsigned ByteAlignment) {
577 markDefined(*Symbol);
578 }
579 virtual void EmitELFSize(MCSymbol *Symbol, const MCExpr *Value) {}
580 virtual void EmitLocalCommonSymbol(MCSymbol *Symbol, uint64_t Size) {}
581 virtual void EmitTBSSSymbol(const MCSection *Section, MCSymbol *Symbol,
582 uint64_t Size, unsigned ByteAlignment) {}
583 virtual void EmitBytes(StringRef Data, unsigned AddrSpace) {}
584 virtual void EmitValueImpl(const MCExpr *Value, unsigned Size,
585 bool isPCRel, unsigned AddrSpace) {}
Rafael Espindolae8cfbd82011-04-21 23:39:26 +0000586 virtual void EmitULEB128Value(const MCExpr *Value) {}
587 virtual void EmitSLEB128Value(const MCExpr *Value) {}
Rafael Espindola38c4e532011-03-02 04:14:42 +0000588 virtual void EmitValueToAlignment(unsigned ByteAlignment, int64_t Value,
589 unsigned ValueSize,
590 unsigned MaxBytesToEmit) {}
591 virtual void EmitCodeAlignment(unsigned ByteAlignment,
592 unsigned MaxBytesToEmit) {}
593 virtual void EmitValueToOffset(const MCExpr *Offset,
594 unsigned char Value ) {}
595 virtual void EmitFileDirective(StringRef Filename) {}
596 virtual void EmitDwarfAdvanceLineAddr(int64_t LineDelta,
597 const MCSymbol *LastLabel,
598 const MCSymbol *Label) {}
599
600 virtual void EmitInstruction(const MCInst &Inst) {
601 // Scan for values.
602 for (unsigned i = Inst.getNumOperands(); i--; )
603 if (Inst.getOperand(i).isExpr())
604 AddValueSymbols(Inst.getOperand(i).getExpr());
605 }
606 virtual void Finish() {}
607 };
608}
609
610bool LTOModule::addAsmGlobalSymbols(MCContext &Context) {
611 const std::string &inlineAsm = _module->getModuleInlineAsm();
612
613 OwningPtr<RecordStreamer> Streamer(new RecordStreamer(Context));
614 MemoryBuffer *Buffer = MemoryBuffer::getMemBuffer(inlineAsm);
615 SourceMgr SrcMgr;
616 SrcMgr.AddNewSourceBuffer(Buffer, SMLoc());
617 OwningPtr<MCAsmParser> Parser(createMCAsmParser(_target->getTarget(), SrcMgr,
618 Context, *Streamer,
619 *_target->getMCAsmInfo()));
620 OwningPtr<TargetAsmParser>
621 TAP(_target->getTarget().createAsmParser(*Parser.get(), *_target.get()));
622 Parser->setTargetParser(*TAP);
623 int Res = Parser->Run(false);
624 if (Res)
625 return true;
626
627 for (RecordStreamer::const_iterator i = Streamer->begin(),
628 e = Streamer->end(); i != e; ++i) {
629 StringRef Key = i->first();
630 RecordStreamer::State Value = i->second;
631 if (Value == RecordStreamer::DefinedGlobal)
632 addAsmGlobalSymbol(Key.data(), LTO_SYMBOL_SCOPE_DEFAULT);
633 else if (Value == RecordStreamer::Defined)
634 addAsmGlobalSymbol(Key.data(), LTO_SYMBOL_SCOPE_INTERNAL);
635 else if (Value == RecordStreamer::Global ||
636 Value == RecordStreamer::Used)
637 addAsmGlobalSymbolUndef(Key.data());
638 }
639 return false;
640}
641
Rafael Espindolaf19d7a72011-03-18 19:51:00 +0000642static bool isDeclaration(const GlobalValue &V) {
643 if (V.hasAvailableExternallyLinkage())
644 return true;
645 if (V.isMaterializable())
646 return false;
647 return V.isDeclaration();
648}
649
650static bool isAliasToDeclaration(const GlobalAlias &V) {
651 return isDeclaration(*V.getAliasedGlobal());
652}
653
Rafael Espindola38c4e532011-03-02 04:14:42 +0000654bool LTOModule::ParseSymbols() {
Daniel Dunbare41d9002010-08-10 23:46:46 +0000655 // Use mangler to add GlobalPrefix to names to match linker names.
Rafael Espindola89b93722010-12-10 07:39:47 +0000656 MCContext Context(*_target->getMCAsmInfo(), NULL);
Daniel Dunbare41d9002010-08-10 23:46:46 +0000657 Mangler mangler(Context, *_target->getTargetData());
Gabor Greif4136e7b2009-09-23 02:46:12 +0000658
Daniel Dunbare41d9002010-08-10 23:46:46 +0000659 // add functions
660 for (Module::iterator f = _module->begin(); f != _module->end(); ++f) {
Rafael Espindolaf19d7a72011-03-18 19:51:00 +0000661 if (isDeclaration(*f))
Daniel Dunbare41d9002010-08-10 23:46:46 +0000662 addPotentialUndefinedSymbol(f, mangler);
663 else
664 addDefinedFunctionSymbol(f, mangler);
665 }
Nick Kledzik77595fc2008-02-26 20:26:43 +0000666
Daniel Dunbare41d9002010-08-10 23:46:46 +0000667 // add data
668 for (Module::global_iterator v = _module->global_begin(),
669 e = _module->global_end(); v != e; ++v) {
Rafael Espindolaf19d7a72011-03-18 19:51:00 +0000670 if (isDeclaration(*v))
Daniel Dunbare41d9002010-08-10 23:46:46 +0000671 addPotentialUndefinedSymbol(v, mangler);
672 else
673 addDefinedDataSymbol(v, mangler);
674 }
Nick Kledzik77595fc2008-02-26 20:26:43 +0000675
Daniel Dunbare41d9002010-08-10 23:46:46 +0000676 // add asm globals
Rafael Espindola38c4e532011-03-02 04:14:42 +0000677 if (addAsmGlobalSymbols(Context))
678 return true;
Daniel Dunbare41d9002010-08-10 23:46:46 +0000679
Rafael Espindola02003ca2010-10-20 04:57:22 +0000680 // add aliases
681 for (Module::alias_iterator i = _module->alias_begin(),
682 e = _module->alias_end(); i != e; ++i) {
Rafael Espindolaf19d7a72011-03-18 19:51:00 +0000683 if (isAliasToDeclaration(*i))
Rafael Espindola02003ca2010-10-20 04:57:22 +0000684 addPotentialUndefinedSymbol(i, mangler);
685 else
686 addDefinedDataSymbol(i, mangler);
687 }
688
Daniel Dunbare41d9002010-08-10 23:46:46 +0000689 // make symbols for all undefines
690 for (StringMap<NameAndAttributes>::iterator it=_undefines.begin();
691 it != _undefines.end(); ++it) {
692 // if this symbol also has a definition, then don't make an undefine
693 // because it is a tentative definition
694 if (_defines.count(it->getKey()) == 0) {
695 NameAndAttributes info = it->getValue();
696 _symbols.push_back(info);
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000697 }
698 }
Rafael Espindola38c4e532011-03-02 04:14:42 +0000699 return false;
Nick Kledzikef194ed2008-02-27 22:25:36 +0000700}
701
702
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000703uint32_t LTOModule::getSymbolCount() {
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000704 return _symbols.size();
Nick Kledzik77595fc2008-02-26 20:26:43 +0000705}
706
707
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000708lto_symbol_attributes LTOModule::getSymbolAttributes(uint32_t index) {
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000709 if (index < _symbols.size())
710 return _symbols[index].attributes;
711 else
712 return lto_symbol_attributes(0);
Nick Kledzik77595fc2008-02-26 20:26:43 +0000713}
714
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000715const char *LTOModule::getSymbolName(uint32_t index) {
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000716 if (index < _symbols.size())
717 return _symbols[index].name;
718 else
719 return NULL;
Nick Kledzik77595fc2008-02-26 20:26:43 +0000720}