blob: bdea0c31a67440b6354593a3eb79bc9729dd9f54 [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,
98 off_t size,
99 std::string &errMsg) {
100 OwningPtr<MemoryBuffer> buffer;
101 if (error_code ec = MemoryBuffer::getOpenFile(fd, path, buffer, size)) {
102 errMsg = ec.message();
103 return NULL;
104 }
105 return makeLTOModule(buffer.get(), errMsg);
106}
107
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000108/// makeBuffer - Create a MemoryBuffer from a memory range. MemoryBuffer
109/// requires the byte past end of the buffer to be a zero. We might get lucky
110/// and already be that way, otherwise make a copy. Also if next byte is on a
111/// different page, don't assume it is readable.
112MemoryBuffer *LTOModule::makeBuffer(const void *mem, size_t length) {
113 const char *startPtr = (char*)mem;
114 const char *endPtr = startPtr+length;
115 if (((uintptr_t)endPtr & (sys::Process::GetPageSize()-1)) == 0 ||
116 *endPtr != 0)
117 return MemoryBuffer::getMemBufferCopy(StringRef(startPtr, length));
118
119 return MemoryBuffer::getMemBuffer(StringRef(startPtr, length));
120}
121
122
123LTOModule *LTOModule::makeLTOModule(const void *mem, size_t length,
124 std::string &errMsg) {
125 OwningPtr<MemoryBuffer> buffer(makeBuffer(mem, length));
126 if (!buffer)
127 return NULL;
128 return makeLTOModule(buffer.get(), errMsg);
129}
130
131LTOModule *LTOModule::makeLTOModule(MemoryBuffer *buffer,
132 std::string &errMsg) {
Rafael Espindola38c4e532011-03-02 04:14:42 +0000133 static bool Initialized = false;
134 if (!Initialized) {
135 InitializeAllTargets();
136 InitializeAllAsmParsers();
137 Initialized = true;
138 }
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000139
140 // parse bitcode buffer
141 OwningPtr<Module> m(ParseBitcodeFile(buffer, getGlobalContext(), &errMsg));
142 if (!m)
143 return NULL;
144
145 std::string Triple = m->getTargetTriple();
146 if (Triple.empty())
147 Triple = sys::getHostTriple();
148
149 // find machine architecture for this module
150 const Target *march = TargetRegistry::lookupTarget(Triple, errMsg);
151 if (!march)
152 return NULL;
153
154 // construct LTModule, hand over ownership of module and target
155 SubtargetFeatures Features;
156 Features.getDefaultSubtargetFeatures("" /* cpu */, llvm::Triple(Triple));
157 std::string FeatureStr = Features.getString();
158 TargetMachine *target = march->createTargetMachine(Triple, FeatureStr);
Rafael Espindola38c4e532011-03-02 04:14:42 +0000159 LTOModule *Ret = new LTOModule(m.take(), target);
160 bool Err = Ret->ParseSymbols();
161 if (Err) {
162 delete Ret;
163 return NULL;
164 }
165 return Ret;
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000166}
167
168
169const char *LTOModule::getTargetTriple() {
170 return _module->getTargetTriple().c_str();
171}
172
173void LTOModule::setTargetTriple(const char *triple) {
174 _module->setTargetTriple(triple);
175}
176
177void LTOModule::addDefinedFunctionSymbol(Function *f, Mangler &mangler) {
178 // add to list of defined symbols
179 addDefinedSymbol(f, mangler, true);
180
181 // add external symbols referenced by this function.
182 for (Function::iterator b = f->begin(); b != f->end(); ++b) {
183 for (BasicBlock::iterator i = b->begin(); i != b->end(); ++i) {
184 for (unsigned count = 0, total = i->getNumOperands();
185 count != total; ++count) {
186 findExternalRefs(i->getOperand(count), mangler);
187 }
Nick Kledzik3eb445f2009-06-01 20:33:09 +0000188 }
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000189 }
Nick Kledzik3eb445f2009-06-01 20:33:09 +0000190}
191
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000192// Get string that data pointer points to.
193bool LTOModule::objcClassNameFromExpression(Constant *c, std::string &name) {
194 if (ConstantExpr *ce = dyn_cast<ConstantExpr>(c)) {
195 Constant *op = ce->getOperand(0);
196 if (GlobalVariable *gvn = dyn_cast<GlobalVariable>(op)) {
197 Constant *cn = gvn->getInitializer();
198 if (ConstantArray *ca = dyn_cast<ConstantArray>(cn)) {
199 if (ca->isCString()) {
200 name = ".objc_class_name_" + ca->getAsString();
201 return true;
Nick Kledzik3eb445f2009-06-01 20:33:09 +0000202 }
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000203 }
Nick Kledzik3eb445f2009-06-01 20:33:09 +0000204 }
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000205 }
206 return false;
207}
208
209// Parse i386/ppc ObjC class data structure.
210void LTOModule::addObjCClass(GlobalVariable *clgv) {
211 if (ConstantStruct *c = dyn_cast<ConstantStruct>(clgv->getInitializer())) {
212 // second slot in __OBJC,__class is pointer to superclass name
213 std::string superclassName;
214 if (objcClassNameFromExpression(c->getOperand(1), superclassName)) {
215 NameAndAttributes info;
Rafael Espindolacd6c93e2011-02-20 16:27:25 +0000216 StringMap<NameAndAttributes>::value_type &entry =
217 _undefines.GetOrCreateValue(superclassName.c_str());
218 if (!entry.getValue().name) {
219 const char *symbolName = entry.getKey().data();
Daniel Dunbar8d0843d2010-08-11 00:11:17 +0000220 info.name = symbolName;
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000221 info.attributes = LTO_SYMBOL_DEFINITION_UNDEFINED;
Rafael Espindolacd6c93e2011-02-20 16:27:25 +0000222 entry.setValue(info);
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000223 }
224 }
225 // third slot in __OBJC,__class is pointer to class name
226 std::string className;
227 if (objcClassNameFromExpression(c->getOperand(2), className)) {
Rafael Espindolacd6c93e2011-02-20 16:27:25 +0000228 StringSet::value_type &entry =
229 _defines.GetOrCreateValue(className.c_str());
230 entry.setValue(1);
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000231 NameAndAttributes info;
Rafael Espindolacd6c93e2011-02-20 16:27:25 +0000232 info.name = entry.getKey().data();
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000233 info.attributes = (lto_symbol_attributes)
234 (LTO_SYMBOL_PERMISSIONS_DATA |
235 LTO_SYMBOL_DEFINITION_REGULAR |
236 LTO_SYMBOL_SCOPE_DEFAULT);
237 _symbols.push_back(info);
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000238 }
239 }
Nick Kledzik3eb445f2009-06-01 20:33:09 +0000240}
241
242
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000243// Parse i386/ppc ObjC category data structure.
244void LTOModule::addObjCCategory(GlobalVariable *clgv) {
245 if (ConstantStruct *c = dyn_cast<ConstantStruct>(clgv->getInitializer())) {
246 // second slot in __OBJC,__category is pointer to target class name
Nick Kledzik3eb445f2009-06-01 20:33:09 +0000247 std::string targetclassName;
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000248 if (objcClassNameFromExpression(c->getOperand(1), targetclassName)) {
249 NameAndAttributes info;
Rafael Espindolacd6c93e2011-02-20 16:27:25 +0000250
251 StringMap<NameAndAttributes>::value_type &entry =
252 _undefines.GetOrCreateValue(targetclassName.c_str());
253
254 if (entry.getValue().name)
255 return;
256
257 const char *symbolName = entry.getKey().data();
258 info.name = symbolName;
259 info.attributes = LTO_SYMBOL_DEFINITION_UNDEFINED;
260 entry.setValue(info);
Nick Kledzik3eb445f2009-06-01 20:33:09 +0000261 }
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000262 }
Nick Kledzik3eb445f2009-06-01 20:33:09 +0000263}
264
265
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000266// Parse i386/ppc ObjC class list data structure.
267void LTOModule::addObjCClassRef(GlobalVariable *clgv) {
268 std::string targetclassName;
269 if (objcClassNameFromExpression(clgv->getInitializer(), targetclassName)) {
Nick Kledzik77595fc2008-02-26 20:26:43 +0000270 NameAndAttributes info;
Rafael Espindolacd6c93e2011-02-20 16:27:25 +0000271
272 StringMap<NameAndAttributes>::value_type &entry =
273 _undefines.GetOrCreateValue(targetclassName.c_str());
274 if (entry.getValue().name)
275 return;
276
277 const char *symbolName = entry.getKey().data();
278 info.name = symbolName;
279 info.attributes = LTO_SYMBOL_DEFINITION_UNDEFINED;
280 entry.setValue(info);
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000281 }
282}
283
284
285void LTOModule::addDefinedDataSymbol(GlobalValue *v, Mangler &mangler) {
286 // Add to list of defined symbols.
287 addDefinedSymbol(v, mangler, false);
288
289 // Special case i386/ppc ObjC data structures in magic sections:
290 // The issue is that the old ObjC object format did some strange
291 // contortions to avoid real linker symbols. For instance, the
292 // ObjC class data structure is allocated statically in the executable
293 // that defines that class. That data structures contains a pointer to
294 // its superclass. But instead of just initializing that part of the
295 // struct to the address of its superclass, and letting the static and
296 // dynamic linkers do the rest, the runtime works by having that field
297 // instead point to a C-string that is the name of the superclass.
298 // At runtime the objc initialization updates that pointer and sets
299 // it to point to the actual super class. As far as the linker
300 // knows it is just a pointer to a string. But then someone wanted the
301 // linker to issue errors at build time if the superclass was not found.
302 // So they figured out a way in mach-o object format to use an absolute
303 // symbols (.objc_class_name_Foo = 0) and a floating reference
304 // (.reference .objc_class_name_Bar) to cause the linker into erroring when
305 // a class was missing.
306 // The following synthesizes the implicit .objc_* symbols for the linker
307 // from the ObjC data structures generated by the front end.
308 if (v->hasSection() /* && isTargetDarwin */) {
309 // special case if this data blob is an ObjC class definition
310 if (v->getSection().compare(0, 15, "__OBJC,__class,") == 0) {
311 if (GlobalVariable *gv = dyn_cast<GlobalVariable>(v)) {
312 addObjCClass(gv);
313 }
314 }
315
316 // special case if this data blob is an ObjC category definition
317 else if (v->getSection().compare(0, 18, "__OBJC,__category,") == 0) {
318 if (GlobalVariable *gv = dyn_cast<GlobalVariable>(v)) {
319 addObjCCategory(gv);
320 }
321 }
322
323 // special case if this data blob is the list of referenced classes
324 else if (v->getSection().compare(0, 18, "__OBJC,__cls_refs,") == 0) {
325 if (GlobalVariable *gv = dyn_cast<GlobalVariable>(v)) {
326 addObjCClassRef(gv);
327 }
328 }
329 }
330
331 // add external symbols referenced by this data.
332 for (unsigned count = 0, total = v->getNumOperands();
333 count != total; ++count) {
334 findExternalRefs(v->getOperand(count), mangler);
335 }
336}
337
338
339void LTOModule::addDefinedSymbol(GlobalValue *def, Mangler &mangler,
340 bool isFunction) {
341 // ignore all llvm.* symbols
342 if (def->getName().startswith("llvm."))
343 return;
344
Rafael Espindola4cb310b2011-02-01 00:41:51 +0000345 // ignore available_externally
346 if (def->hasAvailableExternallyLinkage())
347 return;
348
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000349 // string is owned by _defines
Rafael Espindolaef1860a2011-02-11 05:23:09 +0000350 SmallString<64> Buffer;
351 mangler.getNameWithPrefix(Buffer, def, false);
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000352
353 // set alignment part log2() can have rounding errors
354 uint32_t align = def->getAlignment();
355 uint32_t attr = align ? CountTrailingZeros_32(def->getAlignment()) : 0;
356
357 // set permissions part
358 if (isFunction)
359 attr |= LTO_SYMBOL_PERMISSIONS_CODE;
360 else {
361 GlobalVariable *gv = dyn_cast<GlobalVariable>(def);
362 if (gv && gv->isConstant())
363 attr |= LTO_SYMBOL_PERMISSIONS_RODATA;
364 else
365 attr |= LTO_SYMBOL_PERMISSIONS_DATA;
366 }
367
368 // set definition part
Bill Wendling563ef5e2010-09-27 18:05:19 +0000369 if (def->hasWeakLinkage() || def->hasLinkOnceLinkage() ||
370 def->hasLinkerPrivateWeakLinkage() ||
Bill Wendling7afea0c2010-09-27 20:17:45 +0000371 def->hasLinkerPrivateWeakDefAutoLinkage())
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000372 attr |= LTO_SYMBOL_DEFINITION_WEAK;
Bill Wendling7afea0c2010-09-27 20:17:45 +0000373 else if (def->hasCommonLinkage())
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000374 attr |= LTO_SYMBOL_DEFINITION_TENTATIVE;
Bill Wendling7afea0c2010-09-27 20:17:45 +0000375 else
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000376 attr |= LTO_SYMBOL_DEFINITION_REGULAR;
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000377
378 // set scope part
379 if (def->hasHiddenVisibility())
380 attr |= LTO_SYMBOL_SCOPE_HIDDEN;
381 else if (def->hasProtectedVisibility())
382 attr |= LTO_SYMBOL_SCOPE_PROTECTED;
Bill Wendling7afea0c2010-09-27 20:17:45 +0000383 else if (def->hasExternalLinkage() || def->hasWeakLinkage() ||
384 def->hasLinkOnceLinkage() || def->hasCommonLinkage() ||
385 def->hasLinkerPrivateWeakLinkage())
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000386 attr |= LTO_SYMBOL_SCOPE_DEFAULT;
Bill Wendling7afea0c2010-09-27 20:17:45 +0000387 else if (def->hasLinkerPrivateWeakDefAutoLinkage())
388 attr |= LTO_SYMBOL_SCOPE_DEFAULT_CAN_BE_HIDDEN;
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000389 else
390 attr |= LTO_SYMBOL_SCOPE_INTERNAL;
391
392 // add to table of symbols
393 NameAndAttributes info;
Rafael Espindolacd6c93e2011-02-20 16:27:25 +0000394 StringSet::value_type &entry = _defines.GetOrCreateValue(Buffer.c_str());
395 entry.setValue(1);
396
397 StringRef Name = entry.getKey();
398 info.name = Name.data();
399 assert(info.name[Name.size()] == '\0');
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000400 info.attributes = (lto_symbol_attributes)attr;
401 _symbols.push_back(info);
Nick Kledzik77595fc2008-02-26 20:26:43 +0000402}
403
Rafael Espindola38c4e532011-03-02 04:14:42 +0000404void LTOModule::addAsmGlobalSymbol(const char *name,
405 lto_symbol_attributes scope) {
Rafael Espindolacd6c93e2011-02-20 16:27:25 +0000406 StringSet::value_type &entry = _defines.GetOrCreateValue(name);
407
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000408 // only add new define if not already defined
Rafael Espindolacd6c93e2011-02-20 16:27:25 +0000409 if (entry.getValue())
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000410 return;
411
Rafael Espindolacd6c93e2011-02-20 16:27:25 +0000412 entry.setValue(1);
413 const char *symbolName = entry.getKey().data();
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000414 uint32_t attr = LTO_SYMBOL_DEFINITION_REGULAR;
Rafael Espindola38c4e532011-03-02 04:14:42 +0000415 attr |= scope;
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000416 NameAndAttributes info;
417 info.name = symbolName;
418 info.attributes = (lto_symbol_attributes)attr;
419 _symbols.push_back(info);
Devang Patelc2aec572008-07-16 18:06:52 +0000420}
Nick Kledzik77595fc2008-02-26 20:26:43 +0000421
Rafael Espindola38c4e532011-03-02 04:14:42 +0000422void LTOModule::addAsmGlobalSymbolUndef(const char *name) {
423 StringMap<NameAndAttributes>::value_type &entry =
424 _undefines.GetOrCreateValue(name);
425
426 _asm_undefines.push_back(entry.getKey().data());
427
428 // we already have the symbol
429 if (entry.getValue().name)
430 return;
431
432 uint32_t attr = LTO_SYMBOL_DEFINITION_UNDEFINED;;
433 attr |= LTO_SYMBOL_SCOPE_DEFAULT;
434 NameAndAttributes info;
435 info.name = entry.getKey().data();
436 info.attributes = (lto_symbol_attributes)attr;
437
438 entry.setValue(info);
439}
440
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000441void LTOModule::addPotentialUndefinedSymbol(GlobalValue *decl,
442 Mangler &mangler) {
443 // ignore all llvm.* symbols
444 if (decl->getName().startswith("llvm."))
445 return;
Nick Kledzik3eb445f2009-06-01 20:33:09 +0000446
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000447 // ignore all aliases
448 if (isa<GlobalAlias>(decl))
449 return;
Nick Lewycky485ded02009-07-09 06:03:04 +0000450
Rafael Espindolaef1860a2011-02-11 05:23:09 +0000451 SmallString<64> name;
452 mangler.getNameWithPrefix(name, decl, false);
Rafael Espindola7431af02009-04-24 16:55:21 +0000453
Rafael Espindolacd6c93e2011-02-20 16:27:25 +0000454 StringMap<NameAndAttributes>::value_type &entry =
455 _undefines.GetOrCreateValue(name.c_str());
456
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000457 // we already have the symbol
Rafael Espindolacd6c93e2011-02-20 16:27:25 +0000458 if (entry.getValue().name)
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000459 return;
Rafael Espindola7431af02009-04-24 16:55:21 +0000460
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000461 NameAndAttributes info;
Rafael Espindolacd6c93e2011-02-20 16:27:25 +0000462
463 info.name = entry.getKey().data();
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000464 if (decl->hasExternalWeakLinkage())
465 info.attributes = LTO_SYMBOL_DEFINITION_WEAKUNDEF;
466 else
467 info.attributes = LTO_SYMBOL_DEFINITION_UNDEFINED;
Rafael Espindolacd6c93e2011-02-20 16:27:25 +0000468
469 entry.setValue(info);
Nick Kledzik77595fc2008-02-26 20:26:43 +0000470}
471
472
473
Nick Lewyckyd42b58b2009-07-26 22:16:39 +0000474// Find external symbols referenced by VALUE. This is a recursive function.
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000475void LTOModule::findExternalRefs(Value *value, Mangler &mangler) {
476 if (GlobalValue *gv = dyn_cast<GlobalValue>(value)) {
477 if (!gv->hasExternalLinkage())
478 addPotentialUndefinedSymbol(gv, mangler);
479 // If this is a variable definition, do not recursively process
480 // initializer. It might contain a reference to this variable
481 // and cause an infinite loop. The initializer will be
482 // processed in addDefinedDataSymbol().
483 return;
484 }
Nick Kledzik77595fc2008-02-26 20:26:43 +0000485
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000486 // GlobalValue, even with InternalLinkage type, may have operands with
487 // ExternalLinkage type. Do not ignore these operands.
488 if (Constant *c = dyn_cast<Constant>(value)) {
489 // Handle ConstantExpr, ConstantStruct, ConstantArry etc.
490 for (unsigned i = 0, e = c->getNumOperands(); i != e; ++i)
491 findExternalRefs(c->getOperand(i), mangler);
492 }
493}
494
Rafael Espindola38c4e532011-03-02 04:14:42 +0000495namespace {
496 class RecordStreamer : public MCStreamer {
497 public:
498 enum State { NeverSeen, Global, Defined, DefinedGlobal, Used};
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000499
Rafael Espindola38c4e532011-03-02 04:14:42 +0000500 private:
501 StringMap<State> Symbols;
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000502
Rafael Espindola38c4e532011-03-02 04:14:42 +0000503 void markDefined(const MCSymbol &Symbol) {
504 State &S = Symbols[Symbol.getName()];
505 switch (S) {
506 case DefinedGlobal:
507 case Global:
508 S = DefinedGlobal;
509 break;
510 case NeverSeen:
511 case Defined:
512 case Used:
513 S = Defined;
514 break;
515 }
516 }
517 void markGlobal(const MCSymbol &Symbol) {
518 State &S = Symbols[Symbol.getName()];
519 switch (S) {
520 case DefinedGlobal:
521 case Defined:
522 S = DefinedGlobal;
523 break;
524
525 case NeverSeen:
526 case Global:
527 case Used:
528 S = Global;
529 break;
530 }
531 }
532 void markUsed(const MCSymbol &Symbol) {
533 State &S = Symbols[Symbol.getName()];
534 switch (S) {
535 case DefinedGlobal:
536 case Defined:
537 case Global:
538 break;
539
540 case NeverSeen:
541 case Used:
542 S = Used;
543 break;
544 }
545 }
546
547 // FIXME: mostly copied for the obj streamer.
548 void AddValueSymbols(const MCExpr *Value) {
549 switch (Value->getKind()) {
550 case MCExpr::Target:
551 // FIXME: What should we do in here?
552 break;
553
554 case MCExpr::Constant:
555 break;
556
557 case MCExpr::Binary: {
558 const MCBinaryExpr *BE = cast<MCBinaryExpr>(Value);
559 AddValueSymbols(BE->getLHS());
560 AddValueSymbols(BE->getRHS());
561 break;
562 }
563
564 case MCExpr::SymbolRef:
565 markUsed(cast<MCSymbolRefExpr>(Value)->getSymbol());
566 break;
567
568 case MCExpr::Unary:
569 AddValueSymbols(cast<MCUnaryExpr>(Value)->getSubExpr());
570 break;
571 }
572 }
573
574 public:
575 typedef StringMap<State>::const_iterator const_iterator;
576
577 const_iterator begin() {
578 return Symbols.begin();
579 }
580
581 const_iterator end() {
582 return Symbols.end();
583 }
584
585 RecordStreamer(MCContext &Context) : MCStreamer(Context) {}
586
587 virtual void ChangeSection(const MCSection *Section) {}
588 virtual void InitSections() {}
589 virtual void EmitLabel(MCSymbol *Symbol) {
590 Symbol->setSection(*getCurrentSection());
591 markDefined(*Symbol);
592 }
593 virtual void EmitAssemblerFlag(MCAssemblerFlag Flag) {}
594 virtual void EmitThumbFunc(MCSymbol *Func) {}
595 virtual void EmitAssignment(MCSymbol *Symbol, const MCExpr *Value) {
596 // FIXME: should we handle aliases?
597 markDefined(*Symbol);
598 }
599 virtual void EmitSymbolAttribute(MCSymbol *Symbol, MCSymbolAttr Attribute) {
600 if (Attribute == MCSA_Global)
601 markGlobal(*Symbol);
602 }
603 virtual void EmitSymbolDesc(MCSymbol *Symbol, unsigned DescValue) {}
604 virtual void EmitWeakReference(MCSymbol *Alias, const MCSymbol *Symbol) {}
605 virtual void BeginCOFFSymbolDef(const MCSymbol *Symbol) {}
606 virtual void EmitCOFFSymbolStorageClass(int StorageClass) {}
607 virtual void EmitZerofill(const MCSection *Section, MCSymbol *Symbol,
608 unsigned Size , unsigned ByteAlignment) {
609 markDefined(*Symbol);
610 }
611 virtual void EmitCOFFSymbolType(int Type) {}
612 virtual void EndCOFFSymbolDef() {}
613 virtual void EmitCommonSymbol(MCSymbol *Symbol, uint64_t Size,
614 unsigned ByteAlignment) {
615 markDefined(*Symbol);
616 }
617 virtual void EmitELFSize(MCSymbol *Symbol, const MCExpr *Value) {}
618 virtual void EmitLocalCommonSymbol(MCSymbol *Symbol, uint64_t Size) {}
619 virtual void EmitTBSSSymbol(const MCSection *Section, MCSymbol *Symbol,
620 uint64_t Size, unsigned ByteAlignment) {}
621 virtual void EmitBytes(StringRef Data, unsigned AddrSpace) {}
622 virtual void EmitValueImpl(const MCExpr *Value, unsigned Size,
623 bool isPCRel, unsigned AddrSpace) {}
624 virtual void EmitULEB128Value(const MCExpr *Value,
625 unsigned AddrSpace = 0) {}
626 virtual void EmitSLEB128Value(const MCExpr *Value,
627 unsigned AddrSpace = 0) {}
628 virtual void EmitValueToAlignment(unsigned ByteAlignment, int64_t Value,
629 unsigned ValueSize,
630 unsigned MaxBytesToEmit) {}
631 virtual void EmitCodeAlignment(unsigned ByteAlignment,
632 unsigned MaxBytesToEmit) {}
633 virtual void EmitValueToOffset(const MCExpr *Offset,
634 unsigned char Value ) {}
635 virtual void EmitFileDirective(StringRef Filename) {}
636 virtual void EmitDwarfAdvanceLineAddr(int64_t LineDelta,
637 const MCSymbol *LastLabel,
638 const MCSymbol *Label) {}
639
640 virtual void EmitInstruction(const MCInst &Inst) {
641 // Scan for values.
642 for (unsigned i = Inst.getNumOperands(); i--; )
643 if (Inst.getOperand(i).isExpr())
644 AddValueSymbols(Inst.getOperand(i).getExpr());
645 }
646 virtual void Finish() {}
647 };
648}
649
650bool LTOModule::addAsmGlobalSymbols(MCContext &Context) {
651 const std::string &inlineAsm = _module->getModuleInlineAsm();
652
653 OwningPtr<RecordStreamer> Streamer(new RecordStreamer(Context));
654 MemoryBuffer *Buffer = MemoryBuffer::getMemBuffer(inlineAsm);
655 SourceMgr SrcMgr;
656 SrcMgr.AddNewSourceBuffer(Buffer, SMLoc());
657 OwningPtr<MCAsmParser> Parser(createMCAsmParser(_target->getTarget(), SrcMgr,
658 Context, *Streamer,
659 *_target->getMCAsmInfo()));
660 OwningPtr<TargetAsmParser>
661 TAP(_target->getTarget().createAsmParser(*Parser.get(), *_target.get()));
662 Parser->setTargetParser(*TAP);
663 int Res = Parser->Run(false);
664 if (Res)
665 return true;
666
667 for (RecordStreamer::const_iterator i = Streamer->begin(),
668 e = Streamer->end(); i != e; ++i) {
669 StringRef Key = i->first();
670 RecordStreamer::State Value = i->second;
671 if (Value == RecordStreamer::DefinedGlobal)
672 addAsmGlobalSymbol(Key.data(), LTO_SYMBOL_SCOPE_DEFAULT);
673 else if (Value == RecordStreamer::Defined)
674 addAsmGlobalSymbol(Key.data(), LTO_SYMBOL_SCOPE_INTERNAL);
675 else if (Value == RecordStreamer::Global ||
676 Value == RecordStreamer::Used)
677 addAsmGlobalSymbolUndef(Key.data());
678 }
679 return false;
680}
681
682bool LTOModule::ParseSymbols() {
Daniel Dunbare41d9002010-08-10 23:46:46 +0000683 // Use mangler to add GlobalPrefix to names to match linker names.
Rafael Espindola89b93722010-12-10 07:39:47 +0000684 MCContext Context(*_target->getMCAsmInfo(), NULL);
Daniel Dunbare41d9002010-08-10 23:46:46 +0000685 Mangler mangler(Context, *_target->getTargetData());
Gabor Greif4136e7b2009-09-23 02:46:12 +0000686
Daniel Dunbare41d9002010-08-10 23:46:46 +0000687 // add functions
688 for (Module::iterator f = _module->begin(); f != _module->end(); ++f) {
689 if (f->isDeclaration())
690 addPotentialUndefinedSymbol(f, mangler);
691 else
692 addDefinedFunctionSymbol(f, mangler);
693 }
Nick Kledzik77595fc2008-02-26 20:26:43 +0000694
Daniel Dunbare41d9002010-08-10 23:46:46 +0000695 // add data
696 for (Module::global_iterator v = _module->global_begin(),
697 e = _module->global_end(); v != e; ++v) {
698 if (v->isDeclaration())
699 addPotentialUndefinedSymbol(v, mangler);
700 else
701 addDefinedDataSymbol(v, mangler);
702 }
Nick Kledzik77595fc2008-02-26 20:26:43 +0000703
Daniel Dunbare41d9002010-08-10 23:46:46 +0000704 // add asm globals
Rafael Espindola38c4e532011-03-02 04:14:42 +0000705 if (addAsmGlobalSymbols(Context))
706 return true;
Daniel Dunbare41d9002010-08-10 23:46:46 +0000707
Rafael Espindola02003ca2010-10-20 04:57:22 +0000708 // add aliases
709 for (Module::alias_iterator i = _module->alias_begin(),
710 e = _module->alias_end(); i != e; ++i) {
711 if (i->isDeclaration())
712 addPotentialUndefinedSymbol(i, mangler);
713 else
714 addDefinedDataSymbol(i, mangler);
715 }
716
Daniel Dunbare41d9002010-08-10 23:46:46 +0000717 // make symbols for all undefines
718 for (StringMap<NameAndAttributes>::iterator it=_undefines.begin();
719 it != _undefines.end(); ++it) {
720 // if this symbol also has a definition, then don't make an undefine
721 // because it is a tentative definition
722 if (_defines.count(it->getKey()) == 0) {
723 NameAndAttributes info = it->getValue();
724 _symbols.push_back(info);
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000725 }
726 }
Rafael Espindola38c4e532011-03-02 04:14:42 +0000727 return false;
Nick Kledzikef194ed2008-02-27 22:25:36 +0000728}
729
730
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000731uint32_t LTOModule::getSymbolCount() {
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000732 return _symbols.size();
Nick Kledzik77595fc2008-02-26 20:26:43 +0000733}
734
735
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000736lto_symbol_attributes LTOModule::getSymbolAttributes(uint32_t index) {
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000737 if (index < _symbols.size())
738 return _symbols[index].attributes;
739 else
740 return lto_symbol_attributes(0);
Nick Kledzik77595fc2008-02-26 20:26:43 +0000741}
742
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000743const char *LTOModule::getSymbolName(uint32_t index) {
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000744 if (index < _symbols.size())
745 return _symbols[index].name;
746 else
747 return NULL;
Nick Kledzik77595fc2008-02-26 20:26:43 +0000748}