blob: 0b737293ae25e180b0e2a2fd02e426ab1acceaed [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"
Evan Cheng3e74d6f2011-08-24 18:08:43 +000030#include "llvm/Support/TargetRegistry.h"
31#include "llvm/Support/TargetSelect.h"
Michael J. Spencerf2f516f2010-12-09 18:06:07 +000032#include "llvm/Support/system_error.h"
Chris Lattneraf76e592009-08-22 20:48:53 +000033#include "llvm/MC/MCAsmInfo.h"
Rafael Espindola38c4e532011-03-02 04:14:42 +000034#include "llvm/MC/MCExpr.h"
35#include "llvm/MC/MCInst.h"
36#include "llvm/MC/MCParser/MCAsmParser.h"
37#include "llvm/MC/MCStreamer.h"
Evan Chengffc0e732011-07-09 05:47:46 +000038#include "llvm/MC/MCSubtargetInfo.h"
Rafael Espindola38c4e532011-03-02 04:14:42 +000039#include "llvm/MC/MCSymbol.h"
Evan Chengab8be962011-06-29 01:14:12 +000040#include "llvm/MC/SubtargetFeature.h"
Evan Cheng94b95502011-07-26 00:24:13 +000041#include "llvm/MC/MCTargetAsmParser.h"
Daniel Dunbarff9834a2009-07-16 02:41:19 +000042#include "llvm/Target/TargetMachine.h"
Evan Cheng0e6a0522011-07-18 20:57:22 +000043#include "llvm/Target/TargetRegisterInfo.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 +000064bool LTOModule::isBitcodeFileForTarget(const char *path,
65 const char *triplePrefix) {
Michael J. Spencer3ff95632010-12-16 03:29:14 +000066 OwningPtr<MemoryBuffer> buffer;
67 if (MemoryBuffer::getFile(path, buffer))
Daniel Dunbarb06913d2010-08-10 23:46:39 +000068 return false;
Michael J. Spencer3ff95632010-12-16 03:29:14 +000069 return isTargetMatch(buffer.take(), triplePrefix);
Daniel Dunbarb06913d2010-08-10 23:46:39 +000070}
71
72// Takes ownership of buffer.
73bool LTOModule::isTargetMatch(MemoryBuffer *buffer, const char *triplePrefix) {
Bill Wendling34711742010-10-06 01:22:42 +000074 std::string Triple = getBitcodeTargetTriple(buffer, getGlobalContext());
75 delete buffer;
Bill Wendling931d4c22011-11-04 18:48:00 +000076 return strncmp(Triple.c_str(), triplePrefix, strlen(triplePrefix)) == 0;
Daniel Dunbarb06913d2010-08-10 23:46:39 +000077}
78
79
80LTOModule::LTOModule(Module *m, TargetMachine *t)
Bill Wendlingb9bff962011-11-04 09:24:40 +000081 : _module(m), _target(t),
Bill Wendlinga7280fd2011-11-04 09:30:19 +000082 _context(*_target->getMCAsmInfo(), *_target->getRegisterInfo(), NULL),
83 _mangler(_context, *_target->getTargetData())
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,
Bill Wendling931d4c22011-11-04 18:48:00 +000098 size_t size, std::string &errMsg) {
Rafael Espindolaf21b1052011-03-17 00:36:11 +000099 return makeLTOModule(fd, path, size, size, 0, errMsg);
100}
101
102LTOModule *LTOModule::makeLTOModule(int fd, const char *path,
103 size_t file_size,
104 size_t map_size,
105 off_t offset,
Rafael Espindolab4cc0312011-02-08 22:40:47 +0000106 std::string &errMsg) {
107 OwningPtr<MemoryBuffer> buffer;
Rafael Espindolaf21b1052011-03-17 00:36:11 +0000108 if (error_code ec = MemoryBuffer::getOpenFile(fd, path, buffer, file_size,
109 map_size, offset, false)) {
Rafael Espindolab4cc0312011-02-08 22:40:47 +0000110 errMsg = ec.message();
111 return NULL;
112 }
Rafael Espindolaf19d7a72011-03-18 19:51:00 +0000113 return makeLTOModule(buffer.take(), errMsg);
Rafael Espindolab4cc0312011-02-08 22:40:47 +0000114}
115
Rafael Espindola9916d2a2011-03-17 22:18:42 +0000116/// makeBuffer - Create a MemoryBuffer from a memory range.
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000117MemoryBuffer *LTOModule::makeBuffer(const void *mem, size_t length) {
118 const char *startPtr = (char*)mem;
Rafael Espindola9916d2a2011-03-17 22:18:42 +0000119 return MemoryBuffer::getMemBuffer(StringRef(startPtr, length), "", false);
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000120}
121
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000122LTOModule *LTOModule::makeLTOModule(const void *mem, size_t length,
123 std::string &errMsg) {
124 OwningPtr<MemoryBuffer> buffer(makeBuffer(mem, length));
125 if (!buffer)
126 return NULL;
Rafael Espindolaf19d7a72011-03-18 19:51:00 +0000127 return makeLTOModule(buffer.take(), errMsg);
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000128}
129
130LTOModule *LTOModule::makeLTOModule(MemoryBuffer *buffer,
131 std::string &errMsg) {
Rafael Espindola38c4e532011-03-02 04:14:42 +0000132 static bool Initialized = false;
133 if (!Initialized) {
134 InitializeAllTargets();
Evan Chenge78085a2011-07-22 21:58:54 +0000135 InitializeAllTargetMCs();
Rafael Espindola38c4e532011-03-02 04:14:42 +0000136 InitializeAllAsmParsers();
137 Initialized = true;
138 }
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000139
140 // parse bitcode buffer
Rafael Espindolaf19d7a72011-03-18 19:51:00 +0000141 OwningPtr<Module> m(getLazyBitcodeModule(buffer, getGlobalContext(),
142 &errMsg));
143 if (!m) {
144 delete buffer;
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000145 return NULL;
Rafael Espindolaf19d7a72011-03-18 19:51:00 +0000146 }
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000147
148 std::string Triple = m->getTargetTriple();
149 if (Triple.empty())
Sebastian Pop01738642011-11-01 21:32:20 +0000150 Triple = sys::getDefaultTargetTriple();
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000151
152 // find machine architecture for this module
153 const Target *march = TargetRegistry::lookupTarget(Triple, errMsg);
154 if (!march)
155 return NULL;
156
Nick Lewycky333ed452011-04-21 01:54:08 +0000157 // construct LTOModule, hand over ownership of module and target
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000158 SubtargetFeatures Features;
Evan Cheng276365d2011-06-30 01:53:36 +0000159 Features.getDefaultSubtargetFeatures(llvm::Triple(Triple));
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000160 std::string FeatureStr = Features.getString();
Evan Cheng276365d2011-06-30 01:53:36 +0000161 std::string CPU;
Nick Lewycky8a8d4792011-12-02 22:16:29 +0000162 TargetOptions Options;
163 TargetMachine *target = march->createTargetMachine(Triple, CPU, FeatureStr,
164 Options);
Rafael Espindola38c4e532011-03-02 04:14:42 +0000165 LTOModule *Ret = new LTOModule(m.take(), target);
Bill Wendling931d4c22011-11-04 18:48:00 +0000166 if (Ret->ParseSymbols(errMsg)) {
Rafael Espindola38c4e532011-03-02 04:14:42 +0000167 delete Ret;
168 return NULL;
169 }
Bill Wendling931d4c22011-11-04 18:48:00 +0000170
Rafael Espindola38c4e532011-03-02 04:14:42 +0000171 return Ret;
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000172}
173
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000174const char *LTOModule::getTargetTriple() {
175 return _module->getTargetTriple().c_str();
176}
177
178void LTOModule::setTargetTriple(const char *triple) {
179 _module->setTargetTriple(triple);
180}
181
Bill Wendlinga7280fd2011-11-04 09:30:19 +0000182void LTOModule::addDefinedFunctionSymbol(Function *f) {
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000183 // add to list of defined symbols
Bill Wendlinga7280fd2011-11-04 09:30:19 +0000184 addDefinedSymbol(f, true);
Nick Kledzik3eb445f2009-06-01 20:33:09 +0000185}
186
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000187// Get string that data pointer points to.
188bool LTOModule::objcClassNameFromExpression(Constant *c, std::string &name) {
189 if (ConstantExpr *ce = dyn_cast<ConstantExpr>(c)) {
190 Constant *op = ce->getOperand(0);
191 if (GlobalVariable *gvn = dyn_cast<GlobalVariable>(op)) {
192 Constant *cn = gvn->getInitializer();
193 if (ConstantArray *ca = dyn_cast<ConstantArray>(cn)) {
194 if (ca->isCString()) {
Jay Foad4f910542011-06-28 08:24:19 +0000195 name = ".objc_class_name_" + ca->getAsCString();
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000196 return true;
Nick Kledzik3eb445f2009-06-01 20:33:09 +0000197 }
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000198 }
Nick Kledzik3eb445f2009-06-01 20:33:09 +0000199 }
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000200 }
201 return false;
202}
203
204// Parse i386/ppc ObjC class data structure.
205void LTOModule::addObjCClass(GlobalVariable *clgv) {
Bill Wendling931d4c22011-11-04 18:48:00 +0000206 ConstantStruct *c = dyn_cast<ConstantStruct>(clgv->getInitializer());
207 if (!c) return;
Nick Kledzik3eb445f2009-06-01 20:33:09 +0000208
Bill Wendling931d4c22011-11-04 18:48:00 +0000209 // second slot in __OBJC,__class is pointer to superclass name
210 std::string superclassName;
211 if (objcClassNameFromExpression(c->getOperand(1), superclassName)) {
212 NameAndAttributes info;
213 StringMap<NameAndAttributes>::value_type &entry =
214 _undefines.GetOrCreateValue(superclassName);
215 if (!entry.getValue().name) {
Rafael Espindolacd6c93e2011-02-20 16:27:25 +0000216 const char *symbolName = entry.getKey().data();
217 info.name = symbolName;
218 info.attributes = LTO_SYMBOL_DEFINITION_UNDEFINED;
219 entry.setValue(info);
Nick Kledzik3eb445f2009-06-01 20:33:09 +0000220 }
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000221 }
Bill Wendling931d4c22011-11-04 18:48:00 +0000222
223 // third slot in __OBJC,__class is pointer to class name
224 std::string className;
225 if (objcClassNameFromExpression(c->getOperand(2), className)) {
226 StringSet::value_type &entry = _defines.GetOrCreateValue(className);
227 entry.setValue(1);
228 NameAndAttributes info;
229 info.name = entry.getKey().data();
230 info.attributes = lto_symbol_attributes(LTO_SYMBOL_PERMISSIONS_DATA |
231 LTO_SYMBOL_DEFINITION_REGULAR |
232 LTO_SYMBOL_SCOPE_DEFAULT);
233 _symbols.push_back(info);
234 }
235}
236
237
238// Parse i386/ppc ObjC category data structure.
239void LTOModule::addObjCCategory(GlobalVariable *clgv) {
240 ConstantStruct *c = dyn_cast<ConstantStruct>(clgv->getInitializer());
241 if (!c) return;
242
243 // second slot in __OBJC,__category is pointer to target class name
244 std::string targetclassName;
245 if (!objcClassNameFromExpression(c->getOperand(1), targetclassName))
246 return;
247
248 NameAndAttributes info;
249 StringMap<NameAndAttributes>::value_type &entry =
250 _undefines.GetOrCreateValue(targetclassName);
251
252 if (entry.getValue().name)
253 return;
254
255 const char *symbolName = entry.getKey().data();
256 info.name = symbolName;
257 info.attributes = LTO_SYMBOL_DEFINITION_UNDEFINED;
258 entry.setValue(info);
Nick Kledzik3eb445f2009-06-01 20:33:09 +0000259}
260
261
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000262// Parse i386/ppc ObjC class list data structure.
263void LTOModule::addObjCClassRef(GlobalVariable *clgv) {
264 std::string targetclassName;
Bill Wendling931d4c22011-11-04 18:48:00 +0000265 if (!objcClassNameFromExpression(clgv->getInitializer(), targetclassName))
266 return;
Rafael Espindolacd6c93e2011-02-20 16:27:25 +0000267
Bill Wendling931d4c22011-11-04 18:48:00 +0000268 NameAndAttributes info;
269 StringMap<NameAndAttributes>::value_type &entry =
270 _undefines.GetOrCreateValue(targetclassName);
271 if (entry.getValue().name)
272 return;
Rafael Espindolacd6c93e2011-02-20 16:27:25 +0000273
Bill Wendling931d4c22011-11-04 18:48:00 +0000274 const char *symbolName = entry.getKey().data();
275 info.name = symbolName;
276 info.attributes = LTO_SYMBOL_DEFINITION_UNDEFINED;
277 entry.setValue(info);
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000278}
279
280
Bill Wendlinga7280fd2011-11-04 09:30:19 +0000281void LTOModule::addDefinedDataSymbol(GlobalValue *v) {
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000282 // Add to list of defined symbols.
Bill Wendlinga7280fd2011-11-04 09:30:19 +0000283 addDefinedSymbol(v, false);
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000284
285 // Special case i386/ppc ObjC data structures in magic sections:
286 // The issue is that the old ObjC object format did some strange
287 // contortions to avoid real linker symbols. For instance, the
288 // ObjC class data structure is allocated statically in the executable
289 // that defines that class. That data structures contains a pointer to
290 // its superclass. But instead of just initializing that part of the
291 // struct to the address of its superclass, and letting the static and
292 // dynamic linkers do the rest, the runtime works by having that field
293 // instead point to a C-string that is the name of the superclass.
294 // At runtime the objc initialization updates that pointer and sets
295 // it to point to the actual super class. As far as the linker
296 // knows it is just a pointer to a string. But then someone wanted the
297 // linker to issue errors at build time if the superclass was not found.
298 // So they figured out a way in mach-o object format to use an absolute
299 // symbols (.objc_class_name_Foo = 0) and a floating reference
300 // (.reference .objc_class_name_Bar) to cause the linker into erroring when
301 // a class was missing.
302 // The following synthesizes the implicit .objc_* symbols for the linker
303 // from the ObjC data structures generated by the front end.
304 if (v->hasSection() /* && isTargetDarwin */) {
305 // special case if this data blob is an ObjC class definition
306 if (v->getSection().compare(0, 15, "__OBJC,__class,") == 0) {
307 if (GlobalVariable *gv = dyn_cast<GlobalVariable>(v)) {
308 addObjCClass(gv);
309 }
310 }
311
312 // special case if this data blob is an ObjC category definition
313 else if (v->getSection().compare(0, 18, "__OBJC,__category,") == 0) {
314 if (GlobalVariable *gv = dyn_cast<GlobalVariable>(v)) {
315 addObjCCategory(gv);
316 }
317 }
318
319 // special case if this data blob is the list of referenced classes
320 else if (v->getSection().compare(0, 18, "__OBJC,__cls_refs,") == 0) {
321 if (GlobalVariable *gv = dyn_cast<GlobalVariable>(v)) {
322 addObjCClassRef(gv);
323 }
324 }
325 }
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000326}
327
Bill Wendlinga7280fd2011-11-04 09:30:19 +0000328void LTOModule::addDefinedSymbol(GlobalValue *def, bool isFunction) {
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000329 // 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;
Bill Wendlinga7280fd2011-11-04 09:30:19 +0000335 _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;
Chad Rosierbd35f272011-06-28 18:26:12 +0000378 StringSet::value_type &entry = _defines.GetOrCreateValue(Buffer);
Rafael Espindolacd6c93e2011-02-20 16:27:25 +0000379 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
Bill Wendlinga7280fd2011-11-04 09:30:19 +0000425void LTOModule::addPotentialUndefinedSymbol(GlobalValue *decl) {
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000426 // ignore all llvm.* symbols
427 if (decl->getName().startswith("llvm."))
428 return;
Nick Kledzik3eb445f2009-06-01 20:33:09 +0000429
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000430 // ignore all aliases
431 if (isa<GlobalAlias>(decl))
432 return;
Nick Lewycky485ded02009-07-09 06:03:04 +0000433
Rafael Espindolaef1860a2011-02-11 05:23:09 +0000434 SmallString<64> name;
Bill Wendlinga7280fd2011-11-04 09:30:19 +0000435 _mangler.getNameWithPrefix(name, decl, false);
Rafael Espindola7431af02009-04-24 16:55:21 +0000436
Rafael Espindolacd6c93e2011-02-20 16:27:25 +0000437 StringMap<NameAndAttributes>::value_type &entry =
Chad Rosierbd35f272011-06-28 18:26:12 +0000438 _undefines.GetOrCreateValue(name);
Rafael Espindolacd6c93e2011-02-20 16:27:25 +0000439
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000440 // we already have the symbol
Rafael Espindolacd6c93e2011-02-20 16:27:25 +0000441 if (entry.getValue().name)
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000442 return;
Rafael Espindola7431af02009-04-24 16:55:21 +0000443
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000444 NameAndAttributes info;
Rafael Espindolacd6c93e2011-02-20 16:27:25 +0000445
446 info.name = entry.getKey().data();
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000447 if (decl->hasExternalWeakLinkage())
448 info.attributes = LTO_SYMBOL_DEFINITION_WEAKUNDEF;
449 else
450 info.attributes = LTO_SYMBOL_DEFINITION_UNDEFINED;
Rafael Espindolacd6c93e2011-02-20 16:27:25 +0000451
452 entry.setValue(info);
Nick Kledzik77595fc2008-02-26 20:26:43 +0000453}
454
Rafael Espindola38c4e532011-03-02 04:14:42 +0000455namespace {
456 class RecordStreamer : public MCStreamer {
457 public:
458 enum State { NeverSeen, Global, Defined, DefinedGlobal, Used};
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000459
Rafael Espindola38c4e532011-03-02 04:14:42 +0000460 private:
461 StringMap<State> Symbols;
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000462
Rafael Espindola38c4e532011-03-02 04:14:42 +0000463 void markDefined(const MCSymbol &Symbol) {
464 State &S = Symbols[Symbol.getName()];
465 switch (S) {
466 case DefinedGlobal:
467 case Global:
468 S = DefinedGlobal;
469 break;
470 case NeverSeen:
471 case Defined:
472 case Used:
473 S = Defined;
474 break;
475 }
476 }
477 void markGlobal(const MCSymbol &Symbol) {
478 State &S = Symbols[Symbol.getName()];
479 switch (S) {
480 case DefinedGlobal:
481 case Defined:
482 S = DefinedGlobal;
483 break;
484
485 case NeverSeen:
486 case Global:
487 case Used:
488 S = Global;
489 break;
490 }
491 }
492 void markUsed(const MCSymbol &Symbol) {
493 State &S = Symbols[Symbol.getName()];
494 switch (S) {
495 case DefinedGlobal:
496 case Defined:
497 case Global:
498 break;
499
500 case NeverSeen:
501 case Used:
502 S = Used;
503 break;
504 }
505 }
506
507 // FIXME: mostly copied for the obj streamer.
508 void AddValueSymbols(const MCExpr *Value) {
509 switch (Value->getKind()) {
510 case MCExpr::Target:
511 // FIXME: What should we do in here?
512 break;
513
514 case MCExpr::Constant:
515 break;
516
517 case MCExpr::Binary: {
518 const MCBinaryExpr *BE = cast<MCBinaryExpr>(Value);
519 AddValueSymbols(BE->getLHS());
520 AddValueSymbols(BE->getRHS());
521 break;
522 }
523
524 case MCExpr::SymbolRef:
525 markUsed(cast<MCSymbolRefExpr>(Value)->getSymbol());
526 break;
527
528 case MCExpr::Unary:
529 AddValueSymbols(cast<MCUnaryExpr>(Value)->getSubExpr());
530 break;
531 }
532 }
533
534 public:
535 typedef StringMap<State>::const_iterator const_iterator;
536
537 const_iterator begin() {
538 return Symbols.begin();
539 }
540
541 const_iterator end() {
542 return Symbols.end();
543 }
544
545 RecordStreamer(MCContext &Context) : MCStreamer(Context) {}
546
547 virtual void ChangeSection(const MCSection *Section) {}
548 virtual void InitSections() {}
549 virtual void EmitLabel(MCSymbol *Symbol) {
550 Symbol->setSection(*getCurrentSection());
551 markDefined(*Symbol);
552 }
553 virtual void EmitAssemblerFlag(MCAssemblerFlag Flag) {}
554 virtual void EmitThumbFunc(MCSymbol *Func) {}
555 virtual void EmitAssignment(MCSymbol *Symbol, const MCExpr *Value) {
556 // FIXME: should we handle aliases?
557 markDefined(*Symbol);
558 }
559 virtual void EmitSymbolAttribute(MCSymbol *Symbol, MCSymbolAttr Attribute) {
560 if (Attribute == MCSA_Global)
561 markGlobal(*Symbol);
562 }
563 virtual void EmitSymbolDesc(MCSymbol *Symbol, unsigned DescValue) {}
564 virtual void EmitWeakReference(MCSymbol *Alias, const MCSymbol *Symbol) {}
565 virtual void BeginCOFFSymbolDef(const MCSymbol *Symbol) {}
566 virtual void EmitCOFFSymbolStorageClass(int StorageClass) {}
567 virtual void EmitZerofill(const MCSection *Section, MCSymbol *Symbol,
568 unsigned Size , unsigned ByteAlignment) {
569 markDefined(*Symbol);
570 }
571 virtual void EmitCOFFSymbolType(int Type) {}
572 virtual void EndCOFFSymbolDef() {}
573 virtual void EmitCommonSymbol(MCSymbol *Symbol, uint64_t Size,
574 unsigned ByteAlignment) {
575 markDefined(*Symbol);
576 }
577 virtual void EmitELFSize(MCSymbol *Symbol, const MCExpr *Value) {}
Benjamin Kramer36a16012011-09-01 23:04:27 +0000578 virtual void EmitLocalCommonSymbol(MCSymbol *Symbol, uint64_t Size,
579 unsigned ByteAlignment) {}
Rafael Espindola38c4e532011-03-02 04:14:42 +0000580 virtual void EmitTBSSSymbol(const MCSection *Section, MCSymbol *Symbol,
581 uint64_t Size, unsigned ByteAlignment) {}
582 virtual void EmitBytes(StringRef Data, unsigned AddrSpace) {}
583 virtual void EmitValueImpl(const MCExpr *Value, unsigned Size,
Rafael Espindoladebd7e42011-05-01 03:50:49 +0000584 unsigned AddrSpace) {}
Rafael Espindolae8cfbd82011-04-21 23:39:26 +0000585 virtual void EmitULEB128Value(const MCExpr *Value) {}
586 virtual void EmitSLEB128Value(const MCExpr *Value) {}
Rafael Espindola38c4e532011-03-02 04:14:42 +0000587 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,
Evan Cheng672b93a2011-07-14 05:43:07 +0000597 const MCSymbol *Label,
598 unsigned PointerSize) {}
Rafael Espindola38c4e532011-03-02 04:14:42 +0000599
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
Bill Wendlingb9bff962011-11-04 09:24:40 +0000610bool LTOModule::addAsmGlobalSymbols(std::string &errMsg) {
Rafael Espindola38c4e532011-03-02 04:14:42 +0000611 const std::string &inlineAsm = _module->getModuleInlineAsm();
Ivan Krasin6d483c22011-09-08 07:38:25 +0000612 if (inlineAsm.empty())
613 return false;
Rafael Espindola38c4e532011-03-02 04:14:42 +0000614
Bill Wendlingb9bff962011-11-04 09:24:40 +0000615 OwningPtr<RecordStreamer> Streamer(new RecordStreamer(_context));
Rafael Espindola38c4e532011-03-02 04:14:42 +0000616 MemoryBuffer *Buffer = MemoryBuffer::getMemBuffer(inlineAsm);
617 SourceMgr SrcMgr;
618 SrcMgr.AddNewSourceBuffer(Buffer, SMLoc());
Jim Grosbach1b84cce2011-08-16 18:33:49 +0000619 OwningPtr<MCAsmParser> Parser(createMCAsmParser(SrcMgr,
Bill Wendlingb9bff962011-11-04 09:24:40 +0000620 _context, *Streamer,
Rafael Espindola38c4e532011-03-02 04:14:42 +0000621 *_target->getMCAsmInfo()));
Evan Chengffc0e732011-07-09 05:47:46 +0000622 OwningPtr<MCSubtargetInfo> STI(_target->getTarget().
623 createMCSubtargetInfo(_target->getTargetTriple(),
624 _target->getTargetCPU(),
625 _target->getTargetFeatureString()));
Evan Cheng94b95502011-07-26 00:24:13 +0000626 OwningPtr<MCTargetAsmParser>
627 TAP(_target->getTarget().createMCAsmParser(*STI, *Parser.get()));
Ivan Krasin603e1032011-09-08 07:36:39 +0000628 if (!TAP) {
629 errMsg = "target " + std::string(_target->getTarget().getName()) +
630 " does not define AsmParser.";
631 return true;
632 }
633
Rafael Espindola38c4e532011-03-02 04:14:42 +0000634 Parser->setTargetParser(*TAP);
635 int Res = Parser->Run(false);
636 if (Res)
637 return true;
638
639 for (RecordStreamer::const_iterator i = Streamer->begin(),
640 e = Streamer->end(); i != e; ++i) {
641 StringRef Key = i->first();
642 RecordStreamer::State Value = i->second;
643 if (Value == RecordStreamer::DefinedGlobal)
644 addAsmGlobalSymbol(Key.data(), LTO_SYMBOL_SCOPE_DEFAULT);
645 else if (Value == RecordStreamer::Defined)
646 addAsmGlobalSymbol(Key.data(), LTO_SYMBOL_SCOPE_INTERNAL);
647 else if (Value == RecordStreamer::Global ||
648 Value == RecordStreamer::Used)
649 addAsmGlobalSymbolUndef(Key.data());
650 }
651 return false;
652}
653
Rafael Espindolaf19d7a72011-03-18 19:51:00 +0000654static bool isDeclaration(const GlobalValue &V) {
655 if (V.hasAvailableExternallyLinkage())
656 return true;
657 if (V.isMaterializable())
658 return false;
659 return V.isDeclaration();
660}
661
662static bool isAliasToDeclaration(const GlobalAlias &V) {
663 return isDeclaration(*V.getAliasedGlobal());
664}
665
Ivan Krasin603e1032011-09-08 07:36:39 +0000666bool LTOModule::ParseSymbols(std::string &errMsg) {
Daniel Dunbare41d9002010-08-10 23:46:46 +0000667 // add functions
668 for (Module::iterator f = _module->begin(); f != _module->end(); ++f) {
Rafael Espindolaf19d7a72011-03-18 19:51:00 +0000669 if (isDeclaration(*f))
Bill Wendlinga7280fd2011-11-04 09:30:19 +0000670 addPotentialUndefinedSymbol(f);
Daniel Dunbare41d9002010-08-10 23:46:46 +0000671 else
Bill Wendlinga7280fd2011-11-04 09:30:19 +0000672 addDefinedFunctionSymbol(f);
Daniel Dunbare41d9002010-08-10 23:46:46 +0000673 }
Nick Kledzik77595fc2008-02-26 20:26:43 +0000674
Daniel Dunbare41d9002010-08-10 23:46:46 +0000675 // add data
676 for (Module::global_iterator v = _module->global_begin(),
677 e = _module->global_end(); v != e; ++v) {
Rafael Espindolaf19d7a72011-03-18 19:51:00 +0000678 if (isDeclaration(*v))
Bill Wendlinga7280fd2011-11-04 09:30:19 +0000679 addPotentialUndefinedSymbol(v);
Daniel Dunbare41d9002010-08-10 23:46:46 +0000680 else
Bill Wendlinga7280fd2011-11-04 09:30:19 +0000681 addDefinedDataSymbol(v);
Daniel Dunbare41d9002010-08-10 23:46:46 +0000682 }
Nick Kledzik77595fc2008-02-26 20:26:43 +0000683
Daniel Dunbare41d9002010-08-10 23:46:46 +0000684 // add asm globals
Bill Wendlingb9bff962011-11-04 09:24:40 +0000685 if (addAsmGlobalSymbols(errMsg))
Rafael Espindola38c4e532011-03-02 04:14:42 +0000686 return true;
Daniel Dunbare41d9002010-08-10 23:46:46 +0000687
Rafael Espindola02003ca2010-10-20 04:57:22 +0000688 // add aliases
689 for (Module::alias_iterator i = _module->alias_begin(),
690 e = _module->alias_end(); i != e; ++i) {
Rafael Espindolaf19d7a72011-03-18 19:51:00 +0000691 if (isAliasToDeclaration(*i))
Bill Wendlinga7280fd2011-11-04 09:30:19 +0000692 addPotentialUndefinedSymbol(i);
Rafael Espindola02003ca2010-10-20 04:57:22 +0000693 else
Bill Wendlinga7280fd2011-11-04 09:30:19 +0000694 addDefinedDataSymbol(i);
Rafael Espindola02003ca2010-10-20 04:57:22 +0000695 }
696
Daniel Dunbare41d9002010-08-10 23:46:46 +0000697 // make symbols for all undefines
698 for (StringMap<NameAndAttributes>::iterator it=_undefines.begin();
699 it != _undefines.end(); ++it) {
700 // if this symbol also has a definition, then don't make an undefine
701 // because it is a tentative definition
702 if (_defines.count(it->getKey()) == 0) {
703 NameAndAttributes info = it->getValue();
704 _symbols.push_back(info);
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000705 }
706 }
Rafael Espindola38c4e532011-03-02 04:14:42 +0000707 return false;
Nick Kledzikef194ed2008-02-27 22:25:36 +0000708}
709
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000710uint32_t LTOModule::getSymbolCount() {
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000711 return _symbols.size();
Nick Kledzik77595fc2008-02-26 20:26:43 +0000712}
713
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000714lto_symbol_attributes LTOModule::getSymbolAttributes(uint32_t index) {
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000715 if (index < _symbols.size())
716 return _symbols[index].attributes;
717 else
718 return lto_symbol_attributes(0);
Nick Kledzik77595fc2008-02-26 20:26:43 +0000719}
720
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000721const char *LTOModule::getSymbolName(uint32_t index) {
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000722 if (index < _symbols.size())
723 return _symbols[index].name;
724 else
725 return NULL;
Nick Kledzik77595fc2008-02-26 20:26:43 +0000726}