blob: 97b58896d216db6ddbaca88768db7f832de3ef22 [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"
Nick Kledzik3eb445f2009-06-01 20:33:09 +000016#include "llvm/Constants.h"
Owen Anderson8b477ed2009-07-01 16:58:40 +000017#include "llvm/LLVMContext.h"
Nick Kledzik77595fc2008-02-26 20:26:43 +000018#include "llvm/Module.h"
Nick Kledzik77595fc2008-02-26 20:26:43 +000019#include "llvm/Bitcode/ReaderWriter.h"
Rafael Espindola38c4e532011-03-02 04:14:42 +000020#include "llvm/MC/MCExpr.h"
21#include "llvm/MC/MCInst.h"
Rafael Espindola38c4e532011-03-02 04:14:42 +000022#include "llvm/MC/MCStreamer.h"
Evan Chengffc0e732011-07-09 05:47:46 +000023#include "llvm/MC/MCSubtargetInfo.h"
Rafael Espindola38c4e532011-03-02 04:14:42 +000024#include "llvm/MC/MCSymbol.h"
Evan Cheng94b95502011-07-26 00:24:13 +000025#include "llvm/MC/MCTargetAsmParser.h"
Bill Wendling5ff4bc22012-03-30 23:26:06 +000026#include "llvm/MC/SubtargetFeature.h"
27#include "llvm/MC/MCParser/MCAsmParser.h"
Evan Cheng0e6a0522011-07-18 20:57:22 +000028#include "llvm/Target/TargetRegisterInfo.h"
Bill Wendling5ff4bc22012-03-30 23:26:06 +000029#include "llvm/Support/Host.h"
Bill Wendling5ff4bc22012-03-30 23:26:06 +000030#include "llvm/Support/MemoryBuffer.h"
31#include "llvm/Support/Path.h"
Bill Wendling5ff4bc22012-03-30 23:26:06 +000032#include "llvm/Support/SourceMgr.h"
Bill Wendling5ff4bc22012-03-30 23:26:06 +000033#include "llvm/Support/TargetRegistry.h"
34#include "llvm/Support/TargetSelect.h"
35#include "llvm/Support/system_error.h"
36#include "llvm/ADT/OwningPtr.h"
37#include "llvm/ADT/Triple.h"
Nick Kledzik77595fc2008-02-26 20:26:43 +000038using namespace llvm;
39
Bill Wendling62cf01e2012-03-28 20:46:54 +000040LTOModule::LTOModule(llvm::Module *m, llvm::TargetMachine *t)
41 : _module(m), _target(t),
42 _context(*_target->getMCAsmInfo(), *_target->getRegisterInfo(), NULL),
43 _mangler(_context, *_target->getTargetData()) {}
44
45/// isBitcodeFile - Returns 'true' if the file (or memory contents) is LLVM
46/// bitcode.
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
Bill Wendling62cf01e2012-03-28 20:46:54 +000056/// isBitcodeFileForTarget - Returns 'true' if the file (or memory contents) is
57/// LLVM bitcode for the specified triple.
Daniel Dunbarb06913d2010-08-10 23:46:39 +000058bool LTOModule::isBitcodeFileForTarget(const void *mem, size_t length,
59 const char *triplePrefix) {
60 MemoryBuffer *buffer = makeBuffer(mem, length);
61 if (!buffer)
Nick Kledzik3eb445f2009-06-01 20:33:09 +000062 return false;
Daniel Dunbarb06913d2010-08-10 23:46:39 +000063 return isTargetMatch(buffer, triplePrefix);
Nick Kledzik3eb445f2009-06-01 20:33:09 +000064}
65
Daniel Dunbarb06913d2010-08-10 23:46:39 +000066bool LTOModule::isBitcodeFileForTarget(const char *path,
67 const char *triplePrefix) {
Michael J. Spencer3ff95632010-12-16 03:29:14 +000068 OwningPtr<MemoryBuffer> buffer;
69 if (MemoryBuffer::getFile(path, buffer))
Daniel Dunbarb06913d2010-08-10 23:46:39 +000070 return false;
Michael J. Spencer3ff95632010-12-16 03:29:14 +000071 return isTargetMatch(buffer.take(), triplePrefix);
Daniel Dunbarb06913d2010-08-10 23:46:39 +000072}
73
Bill Wendling62cf01e2012-03-28 20:46:54 +000074/// isTargetMatch - Returns 'true' if the memory buffer is for the specified
75/// target triple.
Daniel Dunbarb06913d2010-08-10 23:46:39 +000076bool LTOModule::isTargetMatch(MemoryBuffer *buffer, const char *triplePrefix) {
Bill Wendling34711742010-10-06 01:22:42 +000077 std::string Triple = getBitcodeTargetTriple(buffer, getGlobalContext());
78 delete buffer;
Bill Wendling931d4c22011-11-04 18:48:00 +000079 return strncmp(Triple.c_str(), triplePrefix, strlen(triplePrefix)) == 0;
Daniel Dunbarb06913d2010-08-10 23:46:39 +000080}
81
Bill Wendling62cf01e2012-03-28 20:46:54 +000082/// makeLTOModule - Create an LTOModule. N.B. These methods take ownership of
83/// the buffer.
84LTOModule *LTOModule::makeLTOModule(const char *path, std::string &errMsg) {
Michael J. Spencer3ff95632010-12-16 03:29:14 +000085 OwningPtr<MemoryBuffer> buffer;
86 if (error_code ec = MemoryBuffer::getFile(path, buffer)) {
Michael J. Spencerf2f516f2010-12-09 18:06:07 +000087 errMsg = ec.message();
Daniel Dunbarb06913d2010-08-10 23:46:39 +000088 return NULL;
Michael J. Spencerf2f516f2010-12-09 18:06:07 +000089 }
Rafael Espindolaf19d7a72011-03-18 19:51:00 +000090 return makeLTOModule(buffer.take(), errMsg);
Daniel Dunbarb06913d2010-08-10 23:46:39 +000091}
92
Rafael Espindolab4cc0312011-02-08 22:40:47 +000093LTOModule *LTOModule::makeLTOModule(int fd, const char *path,
Bill Wendling931d4c22011-11-04 18:48:00 +000094 size_t size, std::string &errMsg) {
Rafael Espindolaf21b1052011-03-17 00:36:11 +000095 return makeLTOModule(fd, path, size, size, 0, errMsg);
96}
97
98LTOModule *LTOModule::makeLTOModule(int fd, const char *path,
99 size_t file_size,
100 size_t map_size,
101 off_t offset,
Rafael Espindolab4cc0312011-02-08 22:40:47 +0000102 std::string &errMsg) {
103 OwningPtr<MemoryBuffer> buffer;
Rafael Espindolaf21b1052011-03-17 00:36:11 +0000104 if (error_code ec = MemoryBuffer::getOpenFile(fd, path, buffer, file_size,
105 map_size, offset, false)) {
Rafael Espindolab4cc0312011-02-08 22:40:47 +0000106 errMsg = ec.message();
107 return NULL;
108 }
Rafael Espindolaf19d7a72011-03-18 19:51:00 +0000109 return makeLTOModule(buffer.take(), errMsg);
Rafael Espindolab4cc0312011-02-08 22:40:47 +0000110}
111
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000112LTOModule *LTOModule::makeLTOModule(const void *mem, size_t length,
113 std::string &errMsg) {
114 OwningPtr<MemoryBuffer> buffer(makeBuffer(mem, length));
115 if (!buffer)
116 return NULL;
Rafael Espindolaf19d7a72011-03-18 19:51:00 +0000117 return makeLTOModule(buffer.take(), errMsg);
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000118}
119
120LTOModule *LTOModule::makeLTOModule(MemoryBuffer *buffer,
121 std::string &errMsg) {
Rafael Espindola38c4e532011-03-02 04:14:42 +0000122 static bool Initialized = false;
123 if (!Initialized) {
124 InitializeAllTargets();
Evan Chenge78085a2011-07-22 21:58:54 +0000125 InitializeAllTargetMCs();
Rafael Espindola38c4e532011-03-02 04:14:42 +0000126 InitializeAllAsmParsers();
127 Initialized = true;
128 }
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000129
130 // parse bitcode buffer
Rafael Espindolaf19d7a72011-03-18 19:51:00 +0000131 OwningPtr<Module> m(getLazyBitcodeModule(buffer, getGlobalContext(),
132 &errMsg));
133 if (!m) {
134 delete buffer;
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000135 return NULL;
Rafael Espindolaf19d7a72011-03-18 19:51:00 +0000136 }
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000137
138 std::string Triple = m->getTargetTriple();
139 if (Triple.empty())
Sebastian Pop01738642011-11-01 21:32:20 +0000140 Triple = sys::getDefaultTargetTriple();
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000141
142 // find machine architecture for this module
143 const Target *march = TargetRegistry::lookupTarget(Triple, errMsg);
144 if (!march)
145 return NULL;
146
Nick Lewycky333ed452011-04-21 01:54:08 +0000147 // construct LTOModule, hand over ownership of module and target
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000148 SubtargetFeatures Features;
Evan Cheng276365d2011-06-30 01:53:36 +0000149 Features.getDefaultSubtargetFeatures(llvm::Triple(Triple));
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000150 std::string FeatureStr = Features.getString();
Evan Cheng276365d2011-06-30 01:53:36 +0000151 std::string CPU;
Nick Lewycky8a8d4792011-12-02 22:16:29 +0000152 TargetOptions Options;
153 TargetMachine *target = march->createTargetMachine(Triple, CPU, FeatureStr,
154 Options);
Rafael Espindola38c4e532011-03-02 04:14:42 +0000155 LTOModule *Ret = new LTOModule(m.take(), target);
Bill Wendling3bb17382012-03-28 23:12:18 +0000156 if (Ret->parseSymbols(errMsg)) {
Rafael Espindola38c4e532011-03-02 04:14:42 +0000157 delete Ret;
158 return NULL;
159 }
Bill Wendling931d4c22011-11-04 18:48:00 +0000160
Rafael Espindola38c4e532011-03-02 04:14:42 +0000161 return Ret;
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000162}
163
Bill Wendling62cf01e2012-03-28 20:46:54 +0000164/// makeBuffer - Create a MemoryBuffer from a memory range.
165MemoryBuffer *LTOModule::makeBuffer(const void *mem, size_t length) {
166 const char *startPtr = (char*)mem;
167 return MemoryBuffer::getMemBuffer(StringRef(startPtr, length), "", false);
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000168}
169
Bill Wendling62cf01e2012-03-28 20:46:54 +0000170/// objcClassNameFromExpression - Get string that the data pointer points to.
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000171bool LTOModule::objcClassNameFromExpression(Constant *c, std::string &name) {
172 if (ConstantExpr *ce = dyn_cast<ConstantExpr>(c)) {
173 Constant *op = ce->getOperand(0);
174 if (GlobalVariable *gvn = dyn_cast<GlobalVariable>(op)) {
175 Constant *cn = gvn->getInitializer();
Chris Lattner18c7f802012-02-05 02:29:43 +0000176 if (ConstantDataArray *ca = dyn_cast<ConstantDataArray>(cn)) {
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000177 if (ca->isCString()) {
Chris Lattner18c7f802012-02-05 02:29:43 +0000178 name = ".objc_class_name_" + ca->getAsCString().str();
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000179 return true;
Nick Kledzik3eb445f2009-06-01 20:33:09 +0000180 }
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000181 }
Nick Kledzik3eb445f2009-06-01 20:33:09 +0000182 }
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000183 }
184 return false;
185}
186
Bill Wendling62cf01e2012-03-28 20:46:54 +0000187/// addObjCClass - Parse i386/ppc ObjC class data structure.
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000188void LTOModule::addObjCClass(GlobalVariable *clgv) {
Bill Wendling931d4c22011-11-04 18:48:00 +0000189 ConstantStruct *c = dyn_cast<ConstantStruct>(clgv->getInitializer());
190 if (!c) return;
Nick Kledzik3eb445f2009-06-01 20:33:09 +0000191
Bill Wendling931d4c22011-11-04 18:48:00 +0000192 // second slot in __OBJC,__class is pointer to superclass name
193 std::string superclassName;
194 if (objcClassNameFromExpression(c->getOperand(1), superclassName)) {
195 NameAndAttributes info;
196 StringMap<NameAndAttributes>::value_type &entry =
197 _undefines.GetOrCreateValue(superclassName);
198 if (!entry.getValue().name) {
Rafael Espindolacd6c93e2011-02-20 16:27:25 +0000199 const char *symbolName = entry.getKey().data();
200 info.name = symbolName;
201 info.attributes = LTO_SYMBOL_DEFINITION_UNDEFINED;
Bill Wendling24b87802012-03-29 08:27:32 +0000202 info.isFunction = false;
203 info.symbol = clgv;
Rafael Espindolacd6c93e2011-02-20 16:27:25 +0000204 entry.setValue(info);
Nick Kledzik3eb445f2009-06-01 20:33:09 +0000205 }
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000206 }
Bill Wendling931d4c22011-11-04 18:48:00 +0000207
208 // third slot in __OBJC,__class is pointer to class name
209 std::string className;
210 if (objcClassNameFromExpression(c->getOperand(2), className)) {
211 StringSet::value_type &entry = _defines.GetOrCreateValue(className);
212 entry.setValue(1);
Bill Wendling24b87802012-03-29 08:27:32 +0000213
Bill Wendling931d4c22011-11-04 18:48:00 +0000214 NameAndAttributes info;
215 info.name = entry.getKey().data();
Bill Wendling24b87802012-03-29 08:27:32 +0000216 info.attributes = LTO_SYMBOL_PERMISSIONS_DATA |
217 LTO_SYMBOL_DEFINITION_REGULAR | LTO_SYMBOL_SCOPE_DEFAULT;
218 info.isFunction = false;
219 info.symbol = clgv;
Bill Wendling931d4c22011-11-04 18:48:00 +0000220 _symbols.push_back(info);
221 }
222}
223
Bill Wendling62cf01e2012-03-28 20:46:54 +0000224/// addObjCCategory - Parse i386/ppc ObjC category data structure.
Bill Wendling931d4c22011-11-04 18:48:00 +0000225void LTOModule::addObjCCategory(GlobalVariable *clgv) {
226 ConstantStruct *c = dyn_cast<ConstantStruct>(clgv->getInitializer());
227 if (!c) return;
228
229 // second slot in __OBJC,__category is pointer to target class name
230 std::string targetclassName;
231 if (!objcClassNameFromExpression(c->getOperand(1), targetclassName))
232 return;
233
234 NameAndAttributes info;
235 StringMap<NameAndAttributes>::value_type &entry =
236 _undefines.GetOrCreateValue(targetclassName);
237
238 if (entry.getValue().name)
239 return;
240
241 const char *symbolName = entry.getKey().data();
242 info.name = symbolName;
243 info.attributes = LTO_SYMBOL_DEFINITION_UNDEFINED;
Bill Wendling24b87802012-03-29 08:27:32 +0000244 info.isFunction = false;
245 info.symbol = clgv;
Bill Wendling931d4c22011-11-04 18:48:00 +0000246 entry.setValue(info);
Nick Kledzik3eb445f2009-06-01 20:33:09 +0000247}
248
Bill Wendling62cf01e2012-03-28 20:46:54 +0000249/// addObjCClassRef - Parse i386/ppc ObjC class list data structure.
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000250void LTOModule::addObjCClassRef(GlobalVariable *clgv) {
251 std::string targetclassName;
Bill Wendling931d4c22011-11-04 18:48:00 +0000252 if (!objcClassNameFromExpression(clgv->getInitializer(), targetclassName))
253 return;
Rafael Espindolacd6c93e2011-02-20 16:27:25 +0000254
Bill Wendling931d4c22011-11-04 18:48:00 +0000255 NameAndAttributes info;
256 StringMap<NameAndAttributes>::value_type &entry =
257 _undefines.GetOrCreateValue(targetclassName);
258 if (entry.getValue().name)
259 return;
Rafael Espindolacd6c93e2011-02-20 16:27:25 +0000260
Bill Wendling931d4c22011-11-04 18:48:00 +0000261 const char *symbolName = entry.getKey().data();
262 info.name = symbolName;
263 info.attributes = LTO_SYMBOL_DEFINITION_UNDEFINED;
Bill Wendling24b87802012-03-29 08:27:32 +0000264 info.isFunction = false;
265 info.symbol = clgv;
Bill Wendling931d4c22011-11-04 18:48:00 +0000266 entry.setValue(info);
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000267}
268
Bill Wendling62cf01e2012-03-28 20:46:54 +0000269/// addDefinedDataSymbol - Add a data symbol as defined to the list.
Bill Wendlinga7280fd2011-11-04 09:30:19 +0000270void LTOModule::addDefinedDataSymbol(GlobalValue *v) {
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000271 // Add to list of defined symbols.
Bill Wendlinga7280fd2011-11-04 09:30:19 +0000272 addDefinedSymbol(v, false);
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000273
274 // Special case i386/ppc ObjC data structures in magic sections:
275 // The issue is that the old ObjC object format did some strange
276 // contortions to avoid real linker symbols. For instance, the
277 // ObjC class data structure is allocated statically in the executable
278 // that defines that class. That data structures contains a pointer to
279 // its superclass. But instead of just initializing that part of the
280 // struct to the address of its superclass, and letting the static and
281 // dynamic linkers do the rest, the runtime works by having that field
282 // instead point to a C-string that is the name of the superclass.
283 // At runtime the objc initialization updates that pointer and sets
284 // it to point to the actual super class. As far as the linker
285 // knows it is just a pointer to a string. But then someone wanted the
286 // linker to issue errors at build time if the superclass was not found.
287 // So they figured out a way in mach-o object format to use an absolute
288 // symbols (.objc_class_name_Foo = 0) and a floating reference
289 // (.reference .objc_class_name_Bar) to cause the linker into erroring when
290 // a class was missing.
291 // The following synthesizes the implicit .objc_* symbols for the linker
292 // from the ObjC data structures generated by the front end.
293 if (v->hasSection() /* && isTargetDarwin */) {
294 // special case if this data blob is an ObjC class definition
295 if (v->getSection().compare(0, 15, "__OBJC,__class,") == 0) {
296 if (GlobalVariable *gv = dyn_cast<GlobalVariable>(v)) {
297 addObjCClass(gv);
298 }
299 }
300
301 // special case if this data blob is an ObjC category definition
302 else if (v->getSection().compare(0, 18, "__OBJC,__category,") == 0) {
303 if (GlobalVariable *gv = dyn_cast<GlobalVariable>(v)) {
304 addObjCCategory(gv);
305 }
306 }
307
308 // special case if this data blob is the list of referenced classes
309 else if (v->getSection().compare(0, 18, "__OBJC,__cls_refs,") == 0) {
310 if (GlobalVariable *gv = dyn_cast<GlobalVariable>(v)) {
311 addObjCClassRef(gv);
312 }
313 }
314 }
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000315}
316
Bill Wendling62cf01e2012-03-28 20:46:54 +0000317/// addDefinedFunctionSymbol - Add a function symbol as defined to the list.
318void LTOModule::addDefinedFunctionSymbol(Function *f) {
319 // add to list of defined symbols
320 addDefinedSymbol(f, true);
321}
322
323/// addDefinedSymbol - Add a defined symbol to the list.
Bill Wendlinga7280fd2011-11-04 09:30:19 +0000324void LTOModule::addDefinedSymbol(GlobalValue *def, bool isFunction) {
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000325 // ignore all llvm.* symbols
326 if (def->getName().startswith("llvm."))
327 return;
328
329 // string is owned by _defines
Rafael Espindolaef1860a2011-02-11 05:23:09 +0000330 SmallString<64> Buffer;
Bill Wendlinga7280fd2011-11-04 09:30:19 +0000331 _mangler.getNameWithPrefix(Buffer, def, false);
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000332
333 // set alignment part log2() can have rounding errors
334 uint32_t align = def->getAlignment();
335 uint32_t attr = align ? CountTrailingZeros_32(def->getAlignment()) : 0;
336
337 // set permissions part
Bill Wendling24b87802012-03-29 08:27:32 +0000338 if (isFunction) {
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000339 attr |= LTO_SYMBOL_PERMISSIONS_CODE;
Bill Wendling24b87802012-03-29 08:27:32 +0000340 } else {
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000341 GlobalVariable *gv = dyn_cast<GlobalVariable>(def);
342 if (gv && gv->isConstant())
343 attr |= LTO_SYMBOL_PERMISSIONS_RODATA;
344 else
345 attr |= LTO_SYMBOL_PERMISSIONS_DATA;
346 }
347
348 // set definition part
Bill Wendling563ef5e2010-09-27 18:05:19 +0000349 if (def->hasWeakLinkage() || def->hasLinkOnceLinkage() ||
350 def->hasLinkerPrivateWeakLinkage() ||
Bill Wendling7afea0c2010-09-27 20:17:45 +0000351 def->hasLinkerPrivateWeakDefAutoLinkage())
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000352 attr |= LTO_SYMBOL_DEFINITION_WEAK;
Bill Wendling7afea0c2010-09-27 20:17:45 +0000353 else if (def->hasCommonLinkage())
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000354 attr |= LTO_SYMBOL_DEFINITION_TENTATIVE;
Bill Wendling7afea0c2010-09-27 20:17:45 +0000355 else
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000356 attr |= LTO_SYMBOL_DEFINITION_REGULAR;
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000357
358 // set scope part
359 if (def->hasHiddenVisibility())
360 attr |= LTO_SYMBOL_SCOPE_HIDDEN;
361 else if (def->hasProtectedVisibility())
362 attr |= LTO_SYMBOL_SCOPE_PROTECTED;
Bill Wendling7afea0c2010-09-27 20:17:45 +0000363 else if (def->hasExternalLinkage() || def->hasWeakLinkage() ||
364 def->hasLinkOnceLinkage() || def->hasCommonLinkage() ||
365 def->hasLinkerPrivateWeakLinkage())
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000366 attr |= LTO_SYMBOL_SCOPE_DEFAULT;
Bill Wendling7afea0c2010-09-27 20:17:45 +0000367 else if (def->hasLinkerPrivateWeakDefAutoLinkage())
368 attr |= LTO_SYMBOL_SCOPE_DEFAULT_CAN_BE_HIDDEN;
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000369 else
370 attr |= LTO_SYMBOL_SCOPE_INTERNAL;
371
Chad Rosierbd35f272011-06-28 18:26:12 +0000372 StringSet::value_type &entry = _defines.GetOrCreateValue(Buffer);
Rafael Espindolacd6c93e2011-02-20 16:27:25 +0000373 entry.setValue(1);
374
Bill Wendling24b87802012-03-29 08:27:32 +0000375 // fill information structure
376 NameAndAttributes info;
Rafael Espindolacd6c93e2011-02-20 16:27:25 +0000377 StringRef Name = entry.getKey();
378 info.name = Name.data();
379 assert(info.name[Name.size()] == '\0');
Bill Wendling24b87802012-03-29 08:27:32 +0000380 info.attributes = attr;
381 info.isFunction = isFunction;
382 info.symbol = def;
383
384 // add to table of symbols
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000385 _symbols.push_back(info);
Nick Kledzik77595fc2008-02-26 20:26:43 +0000386}
387
Bill Wendling62cf01e2012-03-28 20:46:54 +0000388/// addAsmGlobalSymbol - Add a global symbol from module-level ASM to the
389/// defined list.
Rafael Espindola38c4e532011-03-02 04:14:42 +0000390void LTOModule::addAsmGlobalSymbol(const char *name,
391 lto_symbol_attributes scope) {
Rafael Espindolacd6c93e2011-02-20 16:27:25 +0000392 StringSet::value_type &entry = _defines.GetOrCreateValue(name);
393
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000394 // only add new define if not already defined
Rafael Espindolacd6c93e2011-02-20 16:27:25 +0000395 if (entry.getValue())
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000396 return;
397
Rafael Espindolacd6c93e2011-02-20 16:27:25 +0000398 entry.setValue(1);
Bill Wendling24b87802012-03-29 08:27:32 +0000399
400 NameAndAttributes &info = _undefines[entry.getKey().data()];
401
Bill Wendling1fcbca02012-04-02 03:33:31 +0000402 if (info.symbol == 0) {
Bill Wendling8ba94052012-04-02 10:01:21 +0000403 // FIXME: This is trying to take care of module ASM like this:
404 //
405 // module asm ".zerofill __FOO, __foo, _bar_baz_qux, 0"
406 //
407 // but is gross and its mother dresses it funny. Have the ASM parser give us
408 // more details for this type of situation so that we're not guessing so
409 // much.
410
411 // fill information structure
Rafael Espindola383fd7a2012-05-11 03:42:13 +0000412 info.name = entry.getKey().data();
Bill Wendling8ba94052012-04-02 10:01:21 +0000413 info.attributes =
414 LTO_SYMBOL_PERMISSIONS_DATA | LTO_SYMBOL_DEFINITION_REGULAR | scope;
415 info.isFunction = false;
416 info.symbol = 0;
417
418 // add to table of symbols
419 _symbols.push_back(info);
Bill Wendling1fcbca02012-04-02 03:33:31 +0000420 return;
421 }
422
Bill Wendling24b87802012-03-29 08:27:32 +0000423 if (info.isFunction)
424 addDefinedFunctionSymbol(cast<Function>(info.symbol));
425 else
426 addDefinedDataSymbol(info.symbol);
Bill Wendling5ff4bc22012-03-30 23:26:06 +0000427
428 _symbols.back().attributes &= ~LTO_SYMBOL_SCOPE_MASK;
429 _symbols.back().attributes |= scope;
Devang Patelc2aec572008-07-16 18:06:52 +0000430}
Nick Kledzik77595fc2008-02-26 20:26:43 +0000431
Bill Wendling62cf01e2012-03-28 20:46:54 +0000432/// addAsmGlobalSymbolUndef - Add a global symbol from module-level ASM to the
433/// undefined list.
Rafael Espindola38c4e532011-03-02 04:14:42 +0000434void LTOModule::addAsmGlobalSymbolUndef(const char *name) {
435 StringMap<NameAndAttributes>::value_type &entry =
436 _undefines.GetOrCreateValue(name);
437
438 _asm_undefines.push_back(entry.getKey().data());
439
440 // we already have the symbol
441 if (entry.getValue().name)
442 return;
443
444 uint32_t attr = LTO_SYMBOL_DEFINITION_UNDEFINED;;
445 attr |= LTO_SYMBOL_SCOPE_DEFAULT;
446 NameAndAttributes info;
447 info.name = entry.getKey().data();
Bill Wendling24b87802012-03-29 08:27:32 +0000448 info.attributes = attr;
449 info.isFunction = false;
450 info.symbol = 0;
Rafael Espindola38c4e532011-03-02 04:14:42 +0000451
452 entry.setValue(info);
453}
454
Bill Wendling62cf01e2012-03-28 20:46:54 +0000455/// addPotentialUndefinedSymbol - Add a symbol which isn't defined just yet to a
456/// list to be resolved later.
Bill Wendling24b87802012-03-29 08:27:32 +0000457void LTOModule::addPotentialUndefinedSymbol(GlobalValue *decl, bool isFunc) {
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000458 // ignore all llvm.* symbols
459 if (decl->getName().startswith("llvm."))
460 return;
Nick Kledzik3eb445f2009-06-01 20:33:09 +0000461
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000462 // ignore all aliases
463 if (isa<GlobalAlias>(decl))
464 return;
Nick Lewycky485ded02009-07-09 06:03:04 +0000465
Rafael Espindolaef1860a2011-02-11 05:23:09 +0000466 SmallString<64> name;
Bill Wendlinga7280fd2011-11-04 09:30:19 +0000467 _mangler.getNameWithPrefix(name, decl, false);
Rafael Espindola7431af02009-04-24 16:55:21 +0000468
Rafael Espindolacd6c93e2011-02-20 16:27:25 +0000469 StringMap<NameAndAttributes>::value_type &entry =
Chad Rosierbd35f272011-06-28 18:26:12 +0000470 _undefines.GetOrCreateValue(name);
Rafael Espindolacd6c93e2011-02-20 16:27:25 +0000471
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000472 // we already have the symbol
Rafael Espindolacd6c93e2011-02-20 16:27:25 +0000473 if (entry.getValue().name)
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000474 return;
Rafael Espindola7431af02009-04-24 16:55:21 +0000475
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000476 NameAndAttributes info;
Rafael Espindolacd6c93e2011-02-20 16:27:25 +0000477
478 info.name = entry.getKey().data();
Bill Wendling62cf01e2012-03-28 20:46:54 +0000479
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000480 if (decl->hasExternalWeakLinkage())
481 info.attributes = LTO_SYMBOL_DEFINITION_WEAKUNDEF;
482 else
483 info.attributes = LTO_SYMBOL_DEFINITION_UNDEFINED;
Rafael Espindolacd6c93e2011-02-20 16:27:25 +0000484
Bill Wendling24b87802012-03-29 08:27:32 +0000485 info.isFunction = isFunc;
486 info.symbol = decl;
487
Rafael Espindolacd6c93e2011-02-20 16:27:25 +0000488 entry.setValue(info);
Nick Kledzik77595fc2008-02-26 20:26:43 +0000489}
490
Rafael Espindola38c4e532011-03-02 04:14:42 +0000491namespace {
492 class RecordStreamer : public MCStreamer {
493 public:
Bill Wendling90e7d4f2012-04-03 03:56:52 +0000494 enum State { NeverSeen, Global, Defined, DefinedGlobal, Used };
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000495
Rafael Espindola38c4e532011-03-02 04:14:42 +0000496 private:
497 StringMap<State> Symbols;
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000498
Rafael Espindola38c4e532011-03-02 04:14:42 +0000499 void markDefined(const MCSymbol &Symbol) {
500 State &S = Symbols[Symbol.getName()];
501 switch (S) {
502 case DefinedGlobal:
503 case Global:
504 S = DefinedGlobal;
505 break;
506 case NeverSeen:
507 case Defined:
508 case Used:
509 S = Defined;
510 break;
511 }
512 }
513 void markGlobal(const MCSymbol &Symbol) {
514 State &S = Symbols[Symbol.getName()];
515 switch (S) {
516 case DefinedGlobal:
517 case Defined:
518 S = DefinedGlobal;
519 break;
520
521 case NeverSeen:
522 case Global:
523 case Used:
524 S = Global;
525 break;
526 }
527 }
528 void markUsed(const MCSymbol &Symbol) {
529 State &S = Symbols[Symbol.getName()];
530 switch (S) {
531 case DefinedGlobal:
532 case Defined:
533 case Global:
534 break;
535
536 case NeverSeen:
537 case Used:
538 S = Used;
539 break;
540 }
541 }
542
543 // FIXME: mostly copied for the obj streamer.
544 void AddValueSymbols(const MCExpr *Value) {
545 switch (Value->getKind()) {
546 case MCExpr::Target:
547 // FIXME: What should we do in here?
548 break;
549
550 case MCExpr::Constant:
551 break;
552
553 case MCExpr::Binary: {
554 const MCBinaryExpr *BE = cast<MCBinaryExpr>(Value);
555 AddValueSymbols(BE->getLHS());
556 AddValueSymbols(BE->getRHS());
557 break;
558 }
559
560 case MCExpr::SymbolRef:
561 markUsed(cast<MCSymbolRefExpr>(Value)->getSymbol());
562 break;
563
564 case MCExpr::Unary:
565 AddValueSymbols(cast<MCUnaryExpr>(Value)->getSubExpr());
566 break;
567 }
568 }
569
570 public:
571 typedef StringMap<State>::const_iterator const_iterator;
572
573 const_iterator begin() {
574 return Symbols.begin();
575 }
576
577 const_iterator end() {
578 return Symbols.end();
579 }
580
581 RecordStreamer(MCContext &Context) : MCStreamer(Context) {}
582
Bill Wendling90e7d4f2012-04-03 03:56:52 +0000583 virtual void EmitInstruction(const MCInst &Inst) {
584 // Scan for values.
585 for (unsigned i = Inst.getNumOperands(); i--; )
586 if (Inst.getOperand(i).isExpr())
587 AddValueSymbols(Inst.getOperand(i).getExpr());
588 }
Rafael Espindola38c4e532011-03-02 04:14:42 +0000589 virtual void EmitLabel(MCSymbol *Symbol) {
590 Symbol->setSection(*getCurrentSection());
591 markDefined(*Symbol);
592 }
Rafael Espindola38c4e532011-03-02 04:14:42 +0000593 virtual void EmitAssignment(MCSymbol *Symbol, const MCExpr *Value) {
594 // FIXME: should we handle aliases?
595 markDefined(*Symbol);
596 }
597 virtual void EmitSymbolAttribute(MCSymbol *Symbol, MCSymbolAttr Attribute) {
598 if (Attribute == MCSA_Global)
599 markGlobal(*Symbol);
600 }
Rafael Espindola38c4e532011-03-02 04:14:42 +0000601 virtual void EmitZerofill(const MCSection *Section, MCSymbol *Symbol,
Evan Chengdf42d412012-06-22 20:30:39 +0000602 uint64_t Size , unsigned ByteAlignment) {
Rafael Espindola38c4e532011-03-02 04:14:42 +0000603 markDefined(*Symbol);
604 }
Rafael Espindola38c4e532011-03-02 04:14:42 +0000605 virtual void EmitCommonSymbol(MCSymbol *Symbol, uint64_t Size,
606 unsigned ByteAlignment) {
607 markDefined(*Symbol);
608 }
Bill Wendling90e7d4f2012-04-03 03:56:52 +0000609
610 // Noop calls.
611 virtual void ChangeSection(const MCSection *Section) {}
612 virtual void InitSections() {}
613 virtual void EmitAssemblerFlag(MCAssemblerFlag Flag) {}
614 virtual void EmitThumbFunc(MCSymbol *Func) {}
615 virtual void EmitSymbolDesc(MCSymbol *Symbol, unsigned DescValue) {}
616 virtual void EmitWeakReference(MCSymbol *Alias, const MCSymbol *Symbol) {}
617 virtual void BeginCOFFSymbolDef(const MCSymbol *Symbol) {}
618 virtual void EmitCOFFSymbolStorageClass(int StorageClass) {}
619 virtual void EmitCOFFSymbolType(int Type) {}
620 virtual void EndCOFFSymbolDef() {}
Rafael Espindola38c4e532011-03-02 04:14:42 +0000621 virtual void EmitELFSize(MCSymbol *Symbol, const MCExpr *Value) {}
Benjamin Kramer36a16012011-09-01 23:04:27 +0000622 virtual void EmitLocalCommonSymbol(MCSymbol *Symbol, uint64_t Size,
623 unsigned ByteAlignment) {}
Rafael Espindola38c4e532011-03-02 04:14:42 +0000624 virtual void EmitTBSSSymbol(const MCSection *Section, MCSymbol *Symbol,
625 uint64_t Size, unsigned ByteAlignment) {}
626 virtual void EmitBytes(StringRef Data, unsigned AddrSpace) {}
627 virtual void EmitValueImpl(const MCExpr *Value, unsigned Size,
Rafael Espindoladebd7e42011-05-01 03:50:49 +0000628 unsigned AddrSpace) {}
Rafael Espindolae8cfbd82011-04-21 23:39:26 +0000629 virtual void EmitULEB128Value(const MCExpr *Value) {}
630 virtual void EmitSLEB128Value(const MCExpr *Value) {}
Rafael Espindola38c4e532011-03-02 04:14:42 +0000631 virtual void EmitValueToAlignment(unsigned ByteAlignment, int64_t Value,
632 unsigned ValueSize,
633 unsigned MaxBytesToEmit) {}
634 virtual void EmitCodeAlignment(unsigned ByteAlignment,
635 unsigned MaxBytesToEmit) {}
Jim Grosbachebd4c052012-01-27 00:37:08 +0000636 virtual bool EmitValueToOffset(const MCExpr *Offset,
637 unsigned char Value ) { return false; }
Rafael Espindola38c4e532011-03-02 04:14:42 +0000638 virtual void EmitFileDirective(StringRef Filename) {}
639 virtual void EmitDwarfAdvanceLineAddr(int64_t LineDelta,
640 const MCSymbol *LastLabel,
Evan Cheng672b93a2011-07-14 05:43:07 +0000641 const MCSymbol *Label,
642 unsigned PointerSize) {}
Rafael Espindola99b42372012-01-07 03:13:18 +0000643 virtual void FinishImpl() {}
Rafael Espindola38c4e532011-03-02 04:14:42 +0000644 };
Bill Wendling24b87802012-03-29 08:27:32 +0000645} // end anonymous namespace
Rafael Espindola38c4e532011-03-02 04:14:42 +0000646
Bill Wendling62cf01e2012-03-28 20:46:54 +0000647/// addAsmGlobalSymbols - Add global symbols from module-level ASM to the
648/// defined or undefined lists.
Bill Wendlingb9bff962011-11-04 09:24:40 +0000649bool LTOModule::addAsmGlobalSymbols(std::string &errMsg) {
Rafael Espindola38c4e532011-03-02 04:14:42 +0000650 const std::string &inlineAsm = _module->getModuleInlineAsm();
Ivan Krasin6d483c22011-09-08 07:38:25 +0000651 if (inlineAsm.empty())
652 return false;
Rafael Espindola38c4e532011-03-02 04:14:42 +0000653
Bill Wendlingb9bff962011-11-04 09:24:40 +0000654 OwningPtr<RecordStreamer> Streamer(new RecordStreamer(_context));
Rafael Espindola38c4e532011-03-02 04:14:42 +0000655 MemoryBuffer *Buffer = MemoryBuffer::getMemBuffer(inlineAsm);
656 SourceMgr SrcMgr;
657 SrcMgr.AddNewSourceBuffer(Buffer, SMLoc());
Jim Grosbach1b84cce2011-08-16 18:33:49 +0000658 OwningPtr<MCAsmParser> Parser(createMCAsmParser(SrcMgr,
Bill Wendlingb9bff962011-11-04 09:24:40 +0000659 _context, *Streamer,
Rafael Espindola38c4e532011-03-02 04:14:42 +0000660 *_target->getMCAsmInfo()));
Evan Chengffc0e732011-07-09 05:47:46 +0000661 OwningPtr<MCSubtargetInfo> STI(_target->getTarget().
662 createMCSubtargetInfo(_target->getTargetTriple(),
663 _target->getTargetCPU(),
664 _target->getTargetFeatureString()));
Evan Cheng94b95502011-07-26 00:24:13 +0000665 OwningPtr<MCTargetAsmParser>
666 TAP(_target->getTarget().createMCAsmParser(*STI, *Parser.get()));
Ivan Krasin603e1032011-09-08 07:36:39 +0000667 if (!TAP) {
668 errMsg = "target " + std::string(_target->getTarget().getName()) +
669 " does not define AsmParser.";
670 return true;
671 }
672
Rafael Espindola38c4e532011-03-02 04:14:42 +0000673 Parser->setTargetParser(*TAP);
674 int Res = Parser->Run(false);
675 if (Res)
676 return true;
677
678 for (RecordStreamer::const_iterator i = Streamer->begin(),
679 e = Streamer->end(); i != e; ++i) {
680 StringRef Key = i->first();
681 RecordStreamer::State Value = i->second;
682 if (Value == RecordStreamer::DefinedGlobal)
683 addAsmGlobalSymbol(Key.data(), LTO_SYMBOL_SCOPE_DEFAULT);
684 else if (Value == RecordStreamer::Defined)
685 addAsmGlobalSymbol(Key.data(), LTO_SYMBOL_SCOPE_INTERNAL);
686 else if (Value == RecordStreamer::Global ||
687 Value == RecordStreamer::Used)
688 addAsmGlobalSymbolUndef(Key.data());
689 }
690 return false;
691}
692
Bill Wendling62cf01e2012-03-28 20:46:54 +0000693/// isDeclaration - Return 'true' if the global value is a declaration.
Rafael Espindolaf19d7a72011-03-18 19:51:00 +0000694static bool isDeclaration(const GlobalValue &V) {
695 if (V.hasAvailableExternallyLinkage())
696 return true;
697 if (V.isMaterializable())
698 return false;
699 return V.isDeclaration();
700}
701
Bill Wendling3bb17382012-03-28 23:12:18 +0000702/// parseSymbols - Parse the symbols from the module and model-level ASM and add
Bill Wendling62cf01e2012-03-28 20:46:54 +0000703/// them to either the defined or undefined lists.
Bill Wendling3bb17382012-03-28 23:12:18 +0000704bool LTOModule::parseSymbols(std::string &errMsg) {
Daniel Dunbare41d9002010-08-10 23:46:46 +0000705 // add functions
Bill Wendling9f3b4832012-03-29 03:34:57 +0000706 for (Module::iterator f = _module->begin(), e = _module->end(); f != e; ++f) {
Rafael Espindolaf19d7a72011-03-18 19:51:00 +0000707 if (isDeclaration(*f))
Bill Wendling24b87802012-03-29 08:27:32 +0000708 addPotentialUndefinedSymbol(f, true);
Daniel Dunbare41d9002010-08-10 23:46:46 +0000709 else
Bill Wendlinga7280fd2011-11-04 09:30:19 +0000710 addDefinedFunctionSymbol(f);
Daniel Dunbare41d9002010-08-10 23:46:46 +0000711 }
Nick Kledzik77595fc2008-02-26 20:26:43 +0000712
Daniel Dunbare41d9002010-08-10 23:46:46 +0000713 // add data
714 for (Module::global_iterator v = _module->global_begin(),
715 e = _module->global_end(); v != e; ++v) {
Rafael Espindolaf19d7a72011-03-18 19:51:00 +0000716 if (isDeclaration(*v))
Bill Wendling24b87802012-03-29 08:27:32 +0000717 addPotentialUndefinedSymbol(v, false);
Daniel Dunbare41d9002010-08-10 23:46:46 +0000718 else
Bill Wendlinga7280fd2011-11-04 09:30:19 +0000719 addDefinedDataSymbol(v);
Daniel Dunbare41d9002010-08-10 23:46:46 +0000720 }
Nick Kledzik77595fc2008-02-26 20:26:43 +0000721
Daniel Dunbare41d9002010-08-10 23:46:46 +0000722 // add asm globals
Bill Wendlingb9bff962011-11-04 09:24:40 +0000723 if (addAsmGlobalSymbols(errMsg))
Rafael Espindola38c4e532011-03-02 04:14:42 +0000724 return true;
Daniel Dunbare41d9002010-08-10 23:46:46 +0000725
Rafael Espindola02003ca2010-10-20 04:57:22 +0000726 // add aliases
Bill Wendling24b87802012-03-29 08:27:32 +0000727 for (Module::alias_iterator a = _module->alias_begin(),
728 e = _module->alias_end(); a != e; ++a) {
729 if (isDeclaration(*a->getAliasedGlobal()))
Bill Wendling61476d62012-03-28 20:48:49 +0000730 // Is an alias to a declaration.
Bill Wendling24b87802012-03-29 08:27:32 +0000731 addPotentialUndefinedSymbol(a, false);
Rafael Espindola02003ca2010-10-20 04:57:22 +0000732 else
Bill Wendling24b87802012-03-29 08:27:32 +0000733 addDefinedDataSymbol(a);
Rafael Espindola02003ca2010-10-20 04:57:22 +0000734 }
735
Daniel Dunbare41d9002010-08-10 23:46:46 +0000736 // make symbols for all undefines
Bill Wendling24b87802012-03-29 08:27:32 +0000737 for (StringMap<NameAndAttributes>::iterator u =_undefines.begin(),
738 e = _undefines.end(); u != e; ++u) {
739 // If this symbol also has a definition, then don't make an undefine because
740 // it is a tentative definition.
741 if (_defines.count(u->getKey())) continue;
742 NameAndAttributes info = u->getValue();
743 _symbols.push_back(info);
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000744 }
Bill Wendling24b87802012-03-29 08:27:32 +0000745
Rafael Espindola38c4e532011-03-02 04:14:42 +0000746 return false;
Nick Kledzikef194ed2008-02-27 22:25:36 +0000747}