blob: 9c35fa0074e2ff665f1d3e345351508071195daf [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 Kledzikef194ed2008-02-27 22:25:36 +000019#include "llvm/ADT/OwningPtr.h"
Viktor Kutuzove823db82009-11-18 20:20:05 +000020#include "llvm/ADT/Triple.h"
Nick Kledzik77595fc2008-02-26 20:26:43 +000021#include "llvm/Bitcode/ReaderWriter.h"
Nick Kledzik77595fc2008-02-26 20:26:43 +000022#include "llvm/Support/SystemUtils.h"
Nick Kledzik77595fc2008-02-26 20:26:43 +000023#include "llvm/Support/MemoryBuffer.h"
Nick Kledzikef194ed2008-02-27 22:25:36 +000024#include "llvm/Support/MathExtras.h"
Michael J. Spencer3cc52ea2010-11-29 18:47:54 +000025#include "llvm/Support/Host.h"
26#include "llvm/Support/Path.h"
27#include "llvm/Support/Process.h"
Rafael Espindola38c4e532011-03-02 04:14:42 +000028#include "llvm/Support/SourceMgr.h"
Evan Cheng3e74d6f2011-08-24 18:08:43 +000029#include "llvm/Support/TargetRegistry.h"
30#include "llvm/Support/TargetSelect.h"
Michael J. Spencerf2f516f2010-12-09 18:06:07 +000031#include "llvm/Support/system_error.h"
Chris Lattneraf76e592009-08-22 20:48:53 +000032#include "llvm/MC/MCAsmInfo.h"
Rafael Espindola38c4e532011-03-02 04:14:42 +000033#include "llvm/MC/MCExpr.h"
34#include "llvm/MC/MCInst.h"
35#include "llvm/MC/MCParser/MCAsmParser.h"
36#include "llvm/MC/MCStreamer.h"
Evan Chengffc0e732011-07-09 05:47:46 +000037#include "llvm/MC/MCSubtargetInfo.h"
Rafael Espindola38c4e532011-03-02 04:14:42 +000038#include "llvm/MC/MCSymbol.h"
Evan Chengab8be962011-06-29 01:14:12 +000039#include "llvm/MC/SubtargetFeature.h"
Evan Cheng94b95502011-07-26 00:24:13 +000040#include "llvm/MC/MCTargetAsmParser.h"
Daniel Dunbarff9834a2009-07-16 02:41:19 +000041#include "llvm/Target/TargetMachine.h"
Evan Cheng0e6a0522011-07-18 20:57:22 +000042#include "llvm/Target/TargetRegisterInfo.h"
Nick Kledzik77595fc2008-02-26 20:26:43 +000043using namespace llvm;
44
Bill Wendling62cf01e2012-03-28 20:46:54 +000045LTOModule::LTOModule(llvm::Module *m, llvm::TargetMachine *t)
46 : _module(m), _target(t),
47 _context(*_target->getMCAsmInfo(), *_target->getRegisterInfo(), NULL),
48 _mangler(_context, *_target->getTargetData()) {}
49
50/// isBitcodeFile - Returns 'true' if the file (or memory contents) is LLVM
51/// bitcode.
Daniel Dunbarb06913d2010-08-10 23:46:39 +000052bool LTOModule::isBitcodeFile(const void *mem, size_t length) {
53 return llvm::sys::IdentifyFileType((char*)mem, length)
54 == llvm::sys::Bitcode_FileType;
Nick Kledzik77595fc2008-02-26 20:26:43 +000055}
56
Daniel Dunbarb06913d2010-08-10 23:46:39 +000057bool LTOModule::isBitcodeFile(const char *path) {
58 return llvm::sys::Path(path).isBitcodeFile();
Nick Kledzik77595fc2008-02-26 20:26:43 +000059}
60
Bill Wendling62cf01e2012-03-28 20:46:54 +000061/// isBitcodeFileForTarget - Returns 'true' if the file (or memory contents) is
62/// LLVM bitcode for the specified triple.
Daniel Dunbarb06913d2010-08-10 23:46:39 +000063bool LTOModule::isBitcodeFileForTarget(const void *mem, size_t length,
64 const char *triplePrefix) {
65 MemoryBuffer *buffer = makeBuffer(mem, length);
66 if (!buffer)
Nick Kledzik3eb445f2009-06-01 20:33:09 +000067 return false;
Daniel Dunbarb06913d2010-08-10 23:46:39 +000068 return isTargetMatch(buffer, triplePrefix);
Nick Kledzik3eb445f2009-06-01 20:33:09 +000069}
70
Daniel Dunbarb06913d2010-08-10 23:46:39 +000071bool LTOModule::isBitcodeFileForTarget(const char *path,
72 const char *triplePrefix) {
Michael J. Spencer3ff95632010-12-16 03:29:14 +000073 OwningPtr<MemoryBuffer> buffer;
74 if (MemoryBuffer::getFile(path, buffer))
Daniel Dunbarb06913d2010-08-10 23:46:39 +000075 return false;
Michael J. Spencer3ff95632010-12-16 03:29:14 +000076 return isTargetMatch(buffer.take(), triplePrefix);
Daniel Dunbarb06913d2010-08-10 23:46:39 +000077}
78
Bill Wendling62cf01e2012-03-28 20:46:54 +000079/// isTargetMatch - Returns 'true' if the memory buffer is for the specified
80/// target triple.
Daniel Dunbarb06913d2010-08-10 23:46:39 +000081bool LTOModule::isTargetMatch(MemoryBuffer *buffer, const char *triplePrefix) {
Bill Wendling34711742010-10-06 01:22:42 +000082 std::string Triple = getBitcodeTargetTriple(buffer, getGlobalContext());
83 delete buffer;
Bill Wendling931d4c22011-11-04 18:48:00 +000084 return strncmp(Triple.c_str(), triplePrefix, strlen(triplePrefix)) == 0;
Daniel Dunbarb06913d2010-08-10 23:46:39 +000085}
86
Bill Wendling62cf01e2012-03-28 20:46:54 +000087/// makeLTOModule - Create an LTOModule. N.B. These methods take ownership of
88/// the buffer.
89LTOModule *LTOModule::makeLTOModule(const char *path, std::string &errMsg) {
Michael J. Spencer3ff95632010-12-16 03:29:14 +000090 OwningPtr<MemoryBuffer> buffer;
91 if (error_code ec = MemoryBuffer::getFile(path, buffer)) {
Michael J. Spencerf2f516f2010-12-09 18:06:07 +000092 errMsg = ec.message();
Daniel Dunbarb06913d2010-08-10 23:46:39 +000093 return NULL;
Michael J. Spencerf2f516f2010-12-09 18:06:07 +000094 }
Rafael Espindolaf19d7a72011-03-18 19:51:00 +000095 return makeLTOModule(buffer.take(), errMsg);
Daniel Dunbarb06913d2010-08-10 23:46:39 +000096}
97
Rafael Espindolab4cc0312011-02-08 22:40:47 +000098LTOModule *LTOModule::makeLTOModule(int fd, const char *path,
Bill Wendling931d4c22011-11-04 18:48:00 +000099 size_t size, std::string &errMsg) {
Rafael Espindolaf21b1052011-03-17 00:36:11 +0000100 return makeLTOModule(fd, path, size, size, 0, errMsg);
101}
102
103LTOModule *LTOModule::makeLTOModule(int fd, const char *path,
104 size_t file_size,
105 size_t map_size,
106 off_t offset,
Rafael Espindolab4cc0312011-02-08 22:40:47 +0000107 std::string &errMsg) {
108 OwningPtr<MemoryBuffer> buffer;
Rafael Espindolaf21b1052011-03-17 00:36:11 +0000109 if (error_code ec = MemoryBuffer::getOpenFile(fd, path, buffer, file_size,
110 map_size, offset, false)) {
Rafael Espindolab4cc0312011-02-08 22:40:47 +0000111 errMsg = ec.message();
112 return NULL;
113 }
Rafael Espindolaf19d7a72011-03-18 19:51:00 +0000114 return makeLTOModule(buffer.take(), errMsg);
Rafael Espindolab4cc0312011-02-08 22:40:47 +0000115}
116
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000117LTOModule *LTOModule::makeLTOModule(const void *mem, size_t length,
118 std::string &errMsg) {
119 OwningPtr<MemoryBuffer> buffer(makeBuffer(mem, length));
120 if (!buffer)
121 return NULL;
Rafael Espindolaf19d7a72011-03-18 19:51:00 +0000122 return makeLTOModule(buffer.take(), errMsg);
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000123}
124
125LTOModule *LTOModule::makeLTOModule(MemoryBuffer *buffer,
126 std::string &errMsg) {
Rafael Espindola38c4e532011-03-02 04:14:42 +0000127 static bool Initialized = false;
128 if (!Initialized) {
129 InitializeAllTargets();
Evan Chenge78085a2011-07-22 21:58:54 +0000130 InitializeAllTargetMCs();
Rafael Espindola38c4e532011-03-02 04:14:42 +0000131 InitializeAllAsmParsers();
132 Initialized = true;
133 }
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000134
135 // parse bitcode buffer
Rafael Espindolaf19d7a72011-03-18 19:51:00 +0000136 OwningPtr<Module> m(getLazyBitcodeModule(buffer, getGlobalContext(),
137 &errMsg));
138 if (!m) {
139 delete buffer;
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000140 return NULL;
Rafael Espindolaf19d7a72011-03-18 19:51:00 +0000141 }
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000142
143 std::string Triple = m->getTargetTriple();
144 if (Triple.empty())
Sebastian Pop01738642011-11-01 21:32:20 +0000145 Triple = sys::getDefaultTargetTriple();
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000146
147 // find machine architecture for this module
148 const Target *march = TargetRegistry::lookupTarget(Triple, errMsg);
149 if (!march)
150 return NULL;
151
Nick Lewycky333ed452011-04-21 01:54:08 +0000152 // construct LTOModule, hand over ownership of module and target
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000153 SubtargetFeatures Features;
Evan Cheng276365d2011-06-30 01:53:36 +0000154 Features.getDefaultSubtargetFeatures(llvm::Triple(Triple));
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000155 std::string FeatureStr = Features.getString();
Evan Cheng276365d2011-06-30 01:53:36 +0000156 std::string CPU;
Nick Lewycky8a8d4792011-12-02 22:16:29 +0000157 TargetOptions Options;
158 TargetMachine *target = march->createTargetMachine(Triple, CPU, FeatureStr,
159 Options);
Rafael Espindola38c4e532011-03-02 04:14:42 +0000160 LTOModule *Ret = new LTOModule(m.take(), target);
Bill Wendling3bb17382012-03-28 23:12:18 +0000161 if (Ret->parseSymbols(errMsg)) {
Rafael Espindola38c4e532011-03-02 04:14:42 +0000162 delete Ret;
163 return NULL;
164 }
Bill Wendling931d4c22011-11-04 18:48:00 +0000165
Rafael Espindola38c4e532011-03-02 04:14:42 +0000166 return Ret;
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000167}
168
Bill Wendling62cf01e2012-03-28 20:46:54 +0000169/// makeBuffer - Create a MemoryBuffer from a memory range.
170MemoryBuffer *LTOModule::makeBuffer(const void *mem, size_t length) {
171 const char *startPtr = (char*)mem;
172 return MemoryBuffer::getMemBuffer(StringRef(startPtr, length), "", false);
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000173}
174
Bill Wendling62cf01e2012-03-28 20:46:54 +0000175/// objcClassNameFromExpression - Get string that the data pointer points to.
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000176bool LTOModule::objcClassNameFromExpression(Constant *c, std::string &name) {
177 if (ConstantExpr *ce = dyn_cast<ConstantExpr>(c)) {
178 Constant *op = ce->getOperand(0);
179 if (GlobalVariable *gvn = dyn_cast<GlobalVariable>(op)) {
180 Constant *cn = gvn->getInitializer();
Chris Lattner18c7f802012-02-05 02:29:43 +0000181 if (ConstantDataArray *ca = dyn_cast<ConstantDataArray>(cn)) {
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000182 if (ca->isCString()) {
Chris Lattner18c7f802012-02-05 02:29:43 +0000183 name = ".objc_class_name_" + ca->getAsCString().str();
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000184 return true;
Nick Kledzik3eb445f2009-06-01 20:33:09 +0000185 }
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000186 }
Nick Kledzik3eb445f2009-06-01 20:33:09 +0000187 }
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000188 }
189 return false;
190}
191
Bill Wendling62cf01e2012-03-28 20:46:54 +0000192/// addObjCClass - Parse i386/ppc ObjC class data structure.
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000193void LTOModule::addObjCClass(GlobalVariable *clgv) {
Bill Wendling931d4c22011-11-04 18:48:00 +0000194 ConstantStruct *c = dyn_cast<ConstantStruct>(clgv->getInitializer());
195 if (!c) return;
Nick Kledzik3eb445f2009-06-01 20:33:09 +0000196
Bill Wendling931d4c22011-11-04 18:48:00 +0000197 // second slot in __OBJC,__class is pointer to superclass name
198 std::string superclassName;
199 if (objcClassNameFromExpression(c->getOperand(1), superclassName)) {
200 NameAndAttributes info;
201 StringMap<NameAndAttributes>::value_type &entry =
202 _undefines.GetOrCreateValue(superclassName);
203 if (!entry.getValue().name) {
Rafael Espindolacd6c93e2011-02-20 16:27:25 +0000204 const char *symbolName = entry.getKey().data();
205 info.name = symbolName;
206 info.attributes = LTO_SYMBOL_DEFINITION_UNDEFINED;
207 entry.setValue(info);
Nick Kledzik3eb445f2009-06-01 20:33:09 +0000208 }
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000209 }
Bill Wendling931d4c22011-11-04 18:48:00 +0000210
211 // third slot in __OBJC,__class is pointer to class name
212 std::string className;
213 if (objcClassNameFromExpression(c->getOperand(2), className)) {
214 StringSet::value_type &entry = _defines.GetOrCreateValue(className);
215 entry.setValue(1);
216 NameAndAttributes info;
217 info.name = entry.getKey().data();
218 info.attributes = lto_symbol_attributes(LTO_SYMBOL_PERMISSIONS_DATA |
219 LTO_SYMBOL_DEFINITION_REGULAR |
220 LTO_SYMBOL_SCOPE_DEFAULT);
221 _symbols.push_back(info);
222 }
223}
224
Bill Wendling62cf01e2012-03-28 20:46:54 +0000225/// addObjCCategory - Parse i386/ppc ObjC category data structure.
Bill Wendling931d4c22011-11-04 18:48:00 +0000226void LTOModule::addObjCCategory(GlobalVariable *clgv) {
227 ConstantStruct *c = dyn_cast<ConstantStruct>(clgv->getInitializer());
228 if (!c) return;
229
230 // second slot in __OBJC,__category is pointer to target class name
231 std::string targetclassName;
232 if (!objcClassNameFromExpression(c->getOperand(1), targetclassName))
233 return;
234
235 NameAndAttributes info;
236 StringMap<NameAndAttributes>::value_type &entry =
237 _undefines.GetOrCreateValue(targetclassName);
238
239 if (entry.getValue().name)
240 return;
241
242 const char *symbolName = entry.getKey().data();
243 info.name = symbolName;
244 info.attributes = LTO_SYMBOL_DEFINITION_UNDEFINED;
245 entry.setValue(info);
Nick Kledzik3eb445f2009-06-01 20:33:09 +0000246}
247
Bill Wendling62cf01e2012-03-28 20:46:54 +0000248/// addObjCClassRef - Parse i386/ppc ObjC class list data structure.
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000249void LTOModule::addObjCClassRef(GlobalVariable *clgv) {
250 std::string targetclassName;
Bill Wendling931d4c22011-11-04 18:48:00 +0000251 if (!objcClassNameFromExpression(clgv->getInitializer(), targetclassName))
252 return;
Rafael Espindolacd6c93e2011-02-20 16:27:25 +0000253
Bill Wendling931d4c22011-11-04 18:48:00 +0000254 NameAndAttributes info;
255 StringMap<NameAndAttributes>::value_type &entry =
256 _undefines.GetOrCreateValue(targetclassName);
257 if (entry.getValue().name)
258 return;
Rafael Espindolacd6c93e2011-02-20 16:27:25 +0000259
Bill Wendling931d4c22011-11-04 18:48:00 +0000260 const char *symbolName = entry.getKey().data();
261 info.name = symbolName;
262 info.attributes = LTO_SYMBOL_DEFINITION_UNDEFINED;
263 entry.setValue(info);
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000264}
265
Bill Wendling62cf01e2012-03-28 20:46:54 +0000266/// addDefinedDataSymbol - Add a data symbol as defined to the list.
Bill Wendlinga7280fd2011-11-04 09:30:19 +0000267void LTOModule::addDefinedDataSymbol(GlobalValue *v) {
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000268 // Add to list of defined symbols.
Bill Wendlinga7280fd2011-11-04 09:30:19 +0000269 addDefinedSymbol(v, false);
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000270
271 // Special case i386/ppc ObjC data structures in magic sections:
272 // The issue is that the old ObjC object format did some strange
273 // contortions to avoid real linker symbols. For instance, the
274 // ObjC class data structure is allocated statically in the executable
275 // that defines that class. That data structures contains a pointer to
276 // its superclass. But instead of just initializing that part of the
277 // struct to the address of its superclass, and letting the static and
278 // dynamic linkers do the rest, the runtime works by having that field
279 // instead point to a C-string that is the name of the superclass.
280 // At runtime the objc initialization updates that pointer and sets
281 // it to point to the actual super class. As far as the linker
282 // knows it is just a pointer to a string. But then someone wanted the
283 // linker to issue errors at build time if the superclass was not found.
284 // So they figured out a way in mach-o object format to use an absolute
285 // symbols (.objc_class_name_Foo = 0) and a floating reference
286 // (.reference .objc_class_name_Bar) to cause the linker into erroring when
287 // a class was missing.
288 // The following synthesizes the implicit .objc_* symbols for the linker
289 // from the ObjC data structures generated by the front end.
290 if (v->hasSection() /* && isTargetDarwin */) {
291 // special case if this data blob is an ObjC class definition
292 if (v->getSection().compare(0, 15, "__OBJC,__class,") == 0) {
293 if (GlobalVariable *gv = dyn_cast<GlobalVariable>(v)) {
294 addObjCClass(gv);
295 }
296 }
297
298 // special case if this data blob is an ObjC category definition
299 else if (v->getSection().compare(0, 18, "__OBJC,__category,") == 0) {
300 if (GlobalVariable *gv = dyn_cast<GlobalVariable>(v)) {
301 addObjCCategory(gv);
302 }
303 }
304
305 // special case if this data blob is the list of referenced classes
306 else if (v->getSection().compare(0, 18, "__OBJC,__cls_refs,") == 0) {
307 if (GlobalVariable *gv = dyn_cast<GlobalVariable>(v)) {
308 addObjCClassRef(gv);
309 }
310 }
311 }
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000312}
313
Bill Wendling62cf01e2012-03-28 20:46:54 +0000314/// addDefinedFunctionSymbol - Add a function symbol as defined to the list.
315void LTOModule::addDefinedFunctionSymbol(Function *f) {
316 // add to list of defined symbols
317 addDefinedSymbol(f, true);
318}
319
320/// addDefinedSymbol - Add a defined symbol to the list.
Bill Wendlinga7280fd2011-11-04 09:30:19 +0000321void LTOModule::addDefinedSymbol(GlobalValue *def, bool isFunction) {
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000322 // ignore all llvm.* symbols
323 if (def->getName().startswith("llvm."))
324 return;
325
326 // string is owned by _defines
Rafael Espindolaef1860a2011-02-11 05:23:09 +0000327 SmallString<64> Buffer;
Bill Wendlinga7280fd2011-11-04 09:30:19 +0000328 _mangler.getNameWithPrefix(Buffer, def, false);
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000329
330 // set alignment part log2() can have rounding errors
331 uint32_t align = def->getAlignment();
332 uint32_t attr = align ? CountTrailingZeros_32(def->getAlignment()) : 0;
333
334 // set permissions part
335 if (isFunction)
336 attr |= LTO_SYMBOL_PERMISSIONS_CODE;
337 else {
338 GlobalVariable *gv = dyn_cast<GlobalVariable>(def);
339 if (gv && gv->isConstant())
340 attr |= LTO_SYMBOL_PERMISSIONS_RODATA;
341 else
342 attr |= LTO_SYMBOL_PERMISSIONS_DATA;
343 }
344
345 // set definition part
Bill Wendling563ef5e2010-09-27 18:05:19 +0000346 if (def->hasWeakLinkage() || def->hasLinkOnceLinkage() ||
347 def->hasLinkerPrivateWeakLinkage() ||
Bill Wendling7afea0c2010-09-27 20:17:45 +0000348 def->hasLinkerPrivateWeakDefAutoLinkage())
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000349 attr |= LTO_SYMBOL_DEFINITION_WEAK;
Bill Wendling7afea0c2010-09-27 20:17:45 +0000350 else if (def->hasCommonLinkage())
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000351 attr |= LTO_SYMBOL_DEFINITION_TENTATIVE;
Bill Wendling7afea0c2010-09-27 20:17:45 +0000352 else
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000353 attr |= LTO_SYMBOL_DEFINITION_REGULAR;
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000354
355 // set scope part
356 if (def->hasHiddenVisibility())
357 attr |= LTO_SYMBOL_SCOPE_HIDDEN;
358 else if (def->hasProtectedVisibility())
359 attr |= LTO_SYMBOL_SCOPE_PROTECTED;
Bill Wendling7afea0c2010-09-27 20:17:45 +0000360 else if (def->hasExternalLinkage() || def->hasWeakLinkage() ||
361 def->hasLinkOnceLinkage() || def->hasCommonLinkage() ||
362 def->hasLinkerPrivateWeakLinkage())
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000363 attr |= LTO_SYMBOL_SCOPE_DEFAULT;
Bill Wendling7afea0c2010-09-27 20:17:45 +0000364 else if (def->hasLinkerPrivateWeakDefAutoLinkage())
365 attr |= LTO_SYMBOL_SCOPE_DEFAULT_CAN_BE_HIDDEN;
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000366 else
367 attr |= LTO_SYMBOL_SCOPE_INTERNAL;
368
369 // add to table of symbols
370 NameAndAttributes info;
Chad Rosierbd35f272011-06-28 18:26:12 +0000371 StringSet::value_type &entry = _defines.GetOrCreateValue(Buffer);
Rafael Espindolacd6c93e2011-02-20 16:27:25 +0000372 entry.setValue(1);
373
374 StringRef Name = entry.getKey();
375 info.name = Name.data();
376 assert(info.name[Name.size()] == '\0');
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000377 info.attributes = (lto_symbol_attributes)attr;
378 _symbols.push_back(info);
Nick Kledzik77595fc2008-02-26 20:26:43 +0000379}
380
Bill Wendling62cf01e2012-03-28 20:46:54 +0000381/// addAsmGlobalSymbol - Add a global symbol from module-level ASM to the
382/// defined list.
Rafael Espindola38c4e532011-03-02 04:14:42 +0000383void LTOModule::addAsmGlobalSymbol(const char *name,
384 lto_symbol_attributes scope) {
Rafael Espindolacd6c93e2011-02-20 16:27:25 +0000385 StringSet::value_type &entry = _defines.GetOrCreateValue(name);
386
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000387 // only add new define if not already defined
Rafael Espindolacd6c93e2011-02-20 16:27:25 +0000388 if (entry.getValue())
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000389 return;
390
Rafael Espindolacd6c93e2011-02-20 16:27:25 +0000391 entry.setValue(1);
392 const char *symbolName = entry.getKey().data();
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000393 uint32_t attr = LTO_SYMBOL_DEFINITION_REGULAR;
Rafael Espindola38c4e532011-03-02 04:14:42 +0000394 attr |= scope;
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000395 NameAndAttributes info;
396 info.name = symbolName;
397 info.attributes = (lto_symbol_attributes)attr;
398 _symbols.push_back(info);
Devang Patelc2aec572008-07-16 18:06:52 +0000399}
Nick Kledzik77595fc2008-02-26 20:26:43 +0000400
Bill Wendling62cf01e2012-03-28 20:46:54 +0000401/// addAsmGlobalSymbolUndef - Add a global symbol from module-level ASM to the
402/// undefined list.
Rafael Espindola38c4e532011-03-02 04:14:42 +0000403void LTOModule::addAsmGlobalSymbolUndef(const char *name) {
404 StringMap<NameAndAttributes>::value_type &entry =
405 _undefines.GetOrCreateValue(name);
406
407 _asm_undefines.push_back(entry.getKey().data());
408
409 // we already have the symbol
410 if (entry.getValue().name)
411 return;
412
413 uint32_t attr = LTO_SYMBOL_DEFINITION_UNDEFINED;;
414 attr |= LTO_SYMBOL_SCOPE_DEFAULT;
415 NameAndAttributes info;
416 info.name = entry.getKey().data();
417 info.attributes = (lto_symbol_attributes)attr;
418
419 entry.setValue(info);
420}
421
Bill Wendling62cf01e2012-03-28 20:46:54 +0000422/// addPotentialUndefinedSymbol - Add a symbol which isn't defined just yet to a
423/// list to be resolved later.
Bill Wendlinga7280fd2011-11-04 09:30:19 +0000424void LTOModule::addPotentialUndefinedSymbol(GlobalValue *decl) {
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000425 // ignore all llvm.* symbols
426 if (decl->getName().startswith("llvm."))
427 return;
Nick Kledzik3eb445f2009-06-01 20:33:09 +0000428
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000429 // ignore all aliases
430 if (isa<GlobalAlias>(decl))
431 return;
Nick Lewycky485ded02009-07-09 06:03:04 +0000432
Rafael Espindolaef1860a2011-02-11 05:23:09 +0000433 SmallString<64> name;
Bill Wendlinga7280fd2011-11-04 09:30:19 +0000434 _mangler.getNameWithPrefix(name, decl, false);
Rafael Espindola7431af02009-04-24 16:55:21 +0000435
Rafael Espindolacd6c93e2011-02-20 16:27:25 +0000436 StringMap<NameAndAttributes>::value_type &entry =
Chad Rosierbd35f272011-06-28 18:26:12 +0000437 _undefines.GetOrCreateValue(name);
Rafael Espindolacd6c93e2011-02-20 16:27:25 +0000438
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000439 // we already have the symbol
Rafael Espindolacd6c93e2011-02-20 16:27:25 +0000440 if (entry.getValue().name)
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000441 return;
Rafael Espindola7431af02009-04-24 16:55:21 +0000442
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000443 NameAndAttributes info;
Rafael Espindolacd6c93e2011-02-20 16:27:25 +0000444
445 info.name = entry.getKey().data();
Bill Wendling62cf01e2012-03-28 20:46:54 +0000446
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) {}
Jim Grosbachebd4c052012-01-27 00:37:08 +0000592 virtual bool EmitValueToOffset(const MCExpr *Offset,
593 unsigned char Value ) { return false; }
Rafael Espindola38c4e532011-03-02 04:14:42 +0000594 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 }
Rafael Espindola99b42372012-01-07 03:13:18 +0000606 virtual void FinishImpl() {}
Rafael Espindola38c4e532011-03-02 04:14:42 +0000607 };
608}
609
Bill Wendling62cf01e2012-03-28 20:46:54 +0000610/// addAsmGlobalSymbols - Add global symbols from module-level ASM to the
611/// defined or undefined lists.
Bill Wendlingb9bff962011-11-04 09:24:40 +0000612bool LTOModule::addAsmGlobalSymbols(std::string &errMsg) {
Rafael Espindola38c4e532011-03-02 04:14:42 +0000613 const std::string &inlineAsm = _module->getModuleInlineAsm();
Ivan Krasin6d483c22011-09-08 07:38:25 +0000614 if (inlineAsm.empty())
615 return false;
Rafael Espindola38c4e532011-03-02 04:14:42 +0000616
Bill Wendlingb9bff962011-11-04 09:24:40 +0000617 OwningPtr<RecordStreamer> Streamer(new RecordStreamer(_context));
Rafael Espindola38c4e532011-03-02 04:14:42 +0000618 MemoryBuffer *Buffer = MemoryBuffer::getMemBuffer(inlineAsm);
619 SourceMgr SrcMgr;
620 SrcMgr.AddNewSourceBuffer(Buffer, SMLoc());
Jim Grosbach1b84cce2011-08-16 18:33:49 +0000621 OwningPtr<MCAsmParser> Parser(createMCAsmParser(SrcMgr,
Bill Wendlingb9bff962011-11-04 09:24:40 +0000622 _context, *Streamer,
Rafael Espindola38c4e532011-03-02 04:14:42 +0000623 *_target->getMCAsmInfo()));
Evan Chengffc0e732011-07-09 05:47:46 +0000624 OwningPtr<MCSubtargetInfo> STI(_target->getTarget().
625 createMCSubtargetInfo(_target->getTargetTriple(),
626 _target->getTargetCPU(),
627 _target->getTargetFeatureString()));
Evan Cheng94b95502011-07-26 00:24:13 +0000628 OwningPtr<MCTargetAsmParser>
629 TAP(_target->getTarget().createMCAsmParser(*STI, *Parser.get()));
Ivan Krasin603e1032011-09-08 07:36:39 +0000630 if (!TAP) {
631 errMsg = "target " + std::string(_target->getTarget().getName()) +
632 " does not define AsmParser.";
633 return true;
634 }
635
Rafael Espindola38c4e532011-03-02 04:14:42 +0000636 Parser->setTargetParser(*TAP);
637 int Res = Parser->Run(false);
638 if (Res)
639 return true;
640
641 for (RecordStreamer::const_iterator i = Streamer->begin(),
642 e = Streamer->end(); i != e; ++i) {
643 StringRef Key = i->first();
644 RecordStreamer::State Value = i->second;
645 if (Value == RecordStreamer::DefinedGlobal)
646 addAsmGlobalSymbol(Key.data(), LTO_SYMBOL_SCOPE_DEFAULT);
647 else if (Value == RecordStreamer::Defined)
648 addAsmGlobalSymbol(Key.data(), LTO_SYMBOL_SCOPE_INTERNAL);
649 else if (Value == RecordStreamer::Global ||
650 Value == RecordStreamer::Used)
651 addAsmGlobalSymbolUndef(Key.data());
652 }
653 return false;
654}
655
Bill Wendling62cf01e2012-03-28 20:46:54 +0000656/// isDeclaration - Return 'true' if the global value is a declaration.
Rafael Espindolaf19d7a72011-03-18 19:51:00 +0000657static bool isDeclaration(const GlobalValue &V) {
658 if (V.hasAvailableExternallyLinkage())
659 return true;
660 if (V.isMaterializable())
661 return false;
662 return V.isDeclaration();
663}
664
Bill Wendling3bb17382012-03-28 23:12:18 +0000665/// parseSymbols - Parse the symbols from the module and model-level ASM and add
Bill Wendling62cf01e2012-03-28 20:46:54 +0000666/// them to either the defined or undefined lists.
Bill Wendling3bb17382012-03-28 23:12:18 +0000667bool LTOModule::parseSymbols(std::string &errMsg) {
Daniel Dunbare41d9002010-08-10 23:46:46 +0000668 // add functions
669 for (Module::iterator f = _module->begin(); f != _module->end(); ++f) {
Rafael Espindolaf19d7a72011-03-18 19:51:00 +0000670 if (isDeclaration(*f))
Bill Wendlinga7280fd2011-11-04 09:30:19 +0000671 addPotentialUndefinedSymbol(f);
Daniel Dunbare41d9002010-08-10 23:46:46 +0000672 else
Bill Wendlinga7280fd2011-11-04 09:30:19 +0000673 addDefinedFunctionSymbol(f);
Daniel Dunbare41d9002010-08-10 23:46:46 +0000674 }
Nick Kledzik77595fc2008-02-26 20:26:43 +0000675
Daniel Dunbare41d9002010-08-10 23:46:46 +0000676 // add data
677 for (Module::global_iterator v = _module->global_begin(),
678 e = _module->global_end(); v != e; ++v) {
Rafael Espindolaf19d7a72011-03-18 19:51:00 +0000679 if (isDeclaration(*v))
Bill Wendlinga7280fd2011-11-04 09:30:19 +0000680 addPotentialUndefinedSymbol(v);
Daniel Dunbare41d9002010-08-10 23:46:46 +0000681 else
Bill Wendlinga7280fd2011-11-04 09:30:19 +0000682 addDefinedDataSymbol(v);
Daniel Dunbare41d9002010-08-10 23:46:46 +0000683 }
Nick Kledzik77595fc2008-02-26 20:26:43 +0000684
Daniel Dunbare41d9002010-08-10 23:46:46 +0000685 // add asm globals
Bill Wendlingb9bff962011-11-04 09:24:40 +0000686 if (addAsmGlobalSymbols(errMsg))
Rafael Espindola38c4e532011-03-02 04:14:42 +0000687 return true;
Daniel Dunbare41d9002010-08-10 23:46:46 +0000688
Rafael Espindola02003ca2010-10-20 04:57:22 +0000689 // add aliases
690 for (Module::alias_iterator i = _module->alias_begin(),
691 e = _module->alias_end(); i != e; ++i) {
Bill Wendling61476d62012-03-28 20:48:49 +0000692 if (isDeclaration(*i->getAliasedGlobal()))
693 // Is an alias to a declaration.
Bill Wendlinga7280fd2011-11-04 09:30:19 +0000694 addPotentialUndefinedSymbol(i);
Rafael Espindola02003ca2010-10-20 04:57:22 +0000695 else
Bill Wendlinga7280fd2011-11-04 09:30:19 +0000696 addDefinedDataSymbol(i);
Rafael Espindola02003ca2010-10-20 04:57:22 +0000697 }
698
Daniel Dunbare41d9002010-08-10 23:46:46 +0000699 // make symbols for all undefines
700 for (StringMap<NameAndAttributes>::iterator it=_undefines.begin();
701 it != _undefines.end(); ++it) {
702 // if this symbol also has a definition, then don't make an undefine
703 // because it is a tentative definition
704 if (_defines.count(it->getKey()) == 0) {
705 NameAndAttributes info = it->getValue();
706 _symbols.push_back(info);
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000707 }
708 }
Rafael Espindola38c4e532011-03-02 04:14:42 +0000709 return false;
Nick Kledzikef194ed2008-02-27 22:25:36 +0000710}