blob: 97e4e54dce8d2272a5575bace3db38375934d1f5 [file] [log] [blame]
Chris Lattner2eff5052010-03-12 18:44:54 +00001//===-- LTOModule.cpp - LLVM Link Time Optimizer --------------------------===//
Nick Kledzik07b4a622008-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 Dunbar5657e7b2010-08-10 23:46:39 +00007//
Nick Kledzik07b4a622008-02-26 20:26:43 +00008//===----------------------------------------------------------------------===//
9//
Daniel Dunbar5657e7b2010-08-10 23:46:39 +000010// This file implements the Link Time Optimization library. This library is
Nick Kledzik07b4a622008-02-26 20:26:43 +000011// intended to be used by linker to optimize code at link time.
12//
13//===----------------------------------------------------------------------===//
14
Nick Kledzik91a6dcf2008-02-27 22:25:36 +000015#include "LTOModule.h"
Nick Kledzikb481c202009-06-01 20:33:09 +000016#include "llvm/Constants.h"
Owen Anderson6773d382009-07-01 16:58:40 +000017#include "llvm/LLVMContext.h"
Nick Kledzik07b4a622008-02-26 20:26:43 +000018#include "llvm/Module.h"
Nick Kledzik91a6dcf2008-02-27 22:25:36 +000019#include "llvm/ADT/OwningPtr.h"
Viktor Kutuzovc3e2b6b2009-11-18 20:20:05 +000020#include "llvm/ADT/Triple.h"
Nick Kledzik07b4a622008-02-26 20:26:43 +000021#include "llvm/Bitcode/ReaderWriter.h"
Nick Kledzik07b4a622008-02-26 20:26:43 +000022#include "llvm/Support/SystemUtils.h"
Nick Kledzik07b4a622008-02-26 20:26:43 +000023#include "llvm/Support/MemoryBuffer.h"
Nick Kledzik91a6dcf2008-02-27 22:25:36 +000024#include "llvm/Support/MathExtras.h"
Michael J. Spencerab425d82010-11-29 18:47:54 +000025#include "llvm/Support/Host.h"
26#include "llvm/Support/Path.h"
27#include "llvm/Support/Process.h"
Rafael Espindola1e49a6d2011-03-02 04:14:42 +000028#include "llvm/Support/SourceMgr.h"
Evan Cheng2bb40352011-08-24 18:08:43 +000029#include "llvm/Support/TargetRegistry.h"
30#include "llvm/Support/TargetSelect.h"
Michael J. Spencerd4227232010-12-09 18:06:07 +000031#include "llvm/Support/system_error.h"
Chris Lattner7b26fce2009-08-22 20:48:53 +000032#include "llvm/MC/MCAsmInfo.h"
Rafael Espindola1e49a6d2011-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 Cheng91111d22011-07-09 05:47:46 +000037#include "llvm/MC/MCSubtargetInfo.h"
Rafael Espindola1e49a6d2011-03-02 04:14:42 +000038#include "llvm/MC/MCSymbol.h"
Evan Cheng8264e272011-06-29 01:14:12 +000039#include "llvm/MC/SubtargetFeature.h"
Evan Cheng11424442011-07-26 00:24:13 +000040#include "llvm/MC/MCTargetAsmParser.h"
Daniel Dunbar45806382009-07-16 02:41:19 +000041#include "llvm/Target/TargetMachine.h"
Evan Chengd60fa58b2011-07-18 20:57:22 +000042#include "llvm/Target/TargetRegisterInfo.h"
Nick Kledzik07b4a622008-02-26 20:26:43 +000043using namespace llvm;
44
Bill Wendlingfb440502012-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 Dunbar5657e7b2010-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 Kledzik07b4a622008-02-26 20:26:43 +000055}
56
Daniel Dunbar5657e7b2010-08-10 23:46:39 +000057bool LTOModule::isBitcodeFile(const char *path) {
58 return llvm::sys::Path(path).isBitcodeFile();
Nick Kledzik07b4a622008-02-26 20:26:43 +000059}
60
Bill Wendlingfb440502012-03-28 20:46:54 +000061/// isBitcodeFileForTarget - Returns 'true' if the file (or memory contents) is
62/// LLVM bitcode for the specified triple.
Daniel Dunbar5657e7b2010-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 Kledzikb481c202009-06-01 20:33:09 +000067 return false;
Daniel Dunbar5657e7b2010-08-10 23:46:39 +000068 return isTargetMatch(buffer, triplePrefix);
Nick Kledzikb481c202009-06-01 20:33:09 +000069}
70
Daniel Dunbar5657e7b2010-08-10 23:46:39 +000071bool LTOModule::isBitcodeFileForTarget(const char *path,
72 const char *triplePrefix) {
Michael J. Spencer39a0ffc2010-12-16 03:29:14 +000073 OwningPtr<MemoryBuffer> buffer;
74 if (MemoryBuffer::getFile(path, buffer))
Daniel Dunbar5657e7b2010-08-10 23:46:39 +000075 return false;
Michael J. Spencer39a0ffc2010-12-16 03:29:14 +000076 return isTargetMatch(buffer.take(), triplePrefix);
Daniel Dunbar5657e7b2010-08-10 23:46:39 +000077}
78
Bill Wendlingfb440502012-03-28 20:46:54 +000079/// isTargetMatch - Returns 'true' if the memory buffer is for the specified
80/// target triple.
Daniel Dunbar5657e7b2010-08-10 23:46:39 +000081bool LTOModule::isTargetMatch(MemoryBuffer *buffer, const char *triplePrefix) {
Bill Wendling0198ce02010-10-06 01:22:42 +000082 std::string Triple = getBitcodeTargetTriple(buffer, getGlobalContext());
83 delete buffer;
Bill Wendling5f689e72011-11-04 18:48:00 +000084 return strncmp(Triple.c_str(), triplePrefix, strlen(triplePrefix)) == 0;
Daniel Dunbar5657e7b2010-08-10 23:46:39 +000085}
86
Bill Wendlingfb440502012-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. Spencer39a0ffc2010-12-16 03:29:14 +000090 OwningPtr<MemoryBuffer> buffer;
91 if (error_code ec = MemoryBuffer::getFile(path, buffer)) {
Michael J. Spencerd4227232010-12-09 18:06:07 +000092 errMsg = ec.message();
Daniel Dunbar5657e7b2010-08-10 23:46:39 +000093 return NULL;
Michael J. Spencerd4227232010-12-09 18:06:07 +000094 }
Rafael Espindola5b778b22011-03-18 19:51:00 +000095 return makeLTOModule(buffer.take(), errMsg);
Daniel Dunbar5657e7b2010-08-10 23:46:39 +000096}
97
Rafael Espindola56e41f72011-02-08 22:40:47 +000098LTOModule *LTOModule::makeLTOModule(int fd, const char *path,
Bill Wendling5f689e72011-11-04 18:48:00 +000099 size_t size, std::string &errMsg) {
Rafael Espindolab39c7c72011-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 Espindola56e41f72011-02-08 22:40:47 +0000107 std::string &errMsg) {
108 OwningPtr<MemoryBuffer> buffer;
Rafael Espindolab39c7c72011-03-17 00:36:11 +0000109 if (error_code ec = MemoryBuffer::getOpenFile(fd, path, buffer, file_size,
110 map_size, offset, false)) {
Rafael Espindola56e41f72011-02-08 22:40:47 +0000111 errMsg = ec.message();
112 return NULL;
113 }
Rafael Espindola5b778b22011-03-18 19:51:00 +0000114 return makeLTOModule(buffer.take(), errMsg);
Rafael Espindola56e41f72011-02-08 22:40:47 +0000115}
116
Daniel Dunbar5657e7b2010-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 Espindola5b778b22011-03-18 19:51:00 +0000122 return makeLTOModule(buffer.take(), errMsg);
Daniel Dunbar5657e7b2010-08-10 23:46:39 +0000123}
124
125LTOModule *LTOModule::makeLTOModule(MemoryBuffer *buffer,
126 std::string &errMsg) {
Rafael Espindola1e49a6d2011-03-02 04:14:42 +0000127 static bool Initialized = false;
128 if (!Initialized) {
129 InitializeAllTargets();
Evan Cheng8c886a42011-07-22 21:58:54 +0000130 InitializeAllTargetMCs();
Rafael Espindola1e49a6d2011-03-02 04:14:42 +0000131 InitializeAllAsmParsers();
132 Initialized = true;
133 }
Daniel Dunbar5657e7b2010-08-10 23:46:39 +0000134
135 // parse bitcode buffer
Rafael Espindola5b778b22011-03-18 19:51:00 +0000136 OwningPtr<Module> m(getLazyBitcodeModule(buffer, getGlobalContext(),
137 &errMsg));
138 if (!m) {
139 delete buffer;
Daniel Dunbar5657e7b2010-08-10 23:46:39 +0000140 return NULL;
Rafael Espindola5b778b22011-03-18 19:51:00 +0000141 }
Daniel Dunbar5657e7b2010-08-10 23:46:39 +0000142
143 std::string Triple = m->getTargetTriple();
144 if (Triple.empty())
Sebastian Pop94441fb2011-11-01 21:32:20 +0000145 Triple = sys::getDefaultTargetTriple();
Daniel Dunbar5657e7b2010-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 Lewycky364c04a2011-04-21 01:54:08 +0000152 // construct LTOModule, hand over ownership of module and target
Daniel Dunbar5657e7b2010-08-10 23:46:39 +0000153 SubtargetFeatures Features;
Evan Chengfe6e4052011-06-30 01:53:36 +0000154 Features.getDefaultSubtargetFeatures(llvm::Triple(Triple));
Daniel Dunbar5657e7b2010-08-10 23:46:39 +0000155 std::string FeatureStr = Features.getString();
Evan Chengfe6e4052011-06-30 01:53:36 +0000156 std::string CPU;
Nick Lewycky50f02cb2011-12-02 22:16:29 +0000157 TargetOptions Options;
158 TargetMachine *target = march->createTargetMachine(Triple, CPU, FeatureStr,
159 Options);
Rafael Espindola1e49a6d2011-03-02 04:14:42 +0000160 LTOModule *Ret = new LTOModule(m.take(), target);
Bill Wendling7e58b382012-03-28 23:12:18 +0000161 if (Ret->parseSymbols(errMsg)) {
Rafael Espindola1e49a6d2011-03-02 04:14:42 +0000162 delete Ret;
163 return NULL;
164 }
Bill Wendling5f689e72011-11-04 18:48:00 +0000165
Rafael Espindola1e49a6d2011-03-02 04:14:42 +0000166 return Ret;
Daniel Dunbar5657e7b2010-08-10 23:46:39 +0000167}
168
Bill Wendlingfb440502012-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 Dunbar5657e7b2010-08-10 23:46:39 +0000173}
174
Bill Wendlingfb440502012-03-28 20:46:54 +0000175/// objcClassNameFromExpression - Get string that the data pointer points to.
Daniel Dunbar5657e7b2010-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 Lattnercf9e8f62012-02-05 02:29:43 +0000181 if (ConstantDataArray *ca = dyn_cast<ConstantDataArray>(cn)) {
Daniel Dunbar5657e7b2010-08-10 23:46:39 +0000182 if (ca->isCString()) {
Chris Lattnercf9e8f62012-02-05 02:29:43 +0000183 name = ".objc_class_name_" + ca->getAsCString().str();
Daniel Dunbar5657e7b2010-08-10 23:46:39 +0000184 return true;
Nick Kledzikb481c202009-06-01 20:33:09 +0000185 }
Daniel Dunbar5657e7b2010-08-10 23:46:39 +0000186 }
Nick Kledzikb481c202009-06-01 20:33:09 +0000187 }
Daniel Dunbar5657e7b2010-08-10 23:46:39 +0000188 }
189 return false;
190}
191
Bill Wendlingfb440502012-03-28 20:46:54 +0000192/// addObjCClass - Parse i386/ppc ObjC class data structure.
Daniel Dunbar5657e7b2010-08-10 23:46:39 +0000193void LTOModule::addObjCClass(GlobalVariable *clgv) {
Bill Wendling5f689e72011-11-04 18:48:00 +0000194 ConstantStruct *c = dyn_cast<ConstantStruct>(clgv->getInitializer());
195 if (!c) return;
Nick Kledzikb481c202009-06-01 20:33:09 +0000196
Bill Wendling5f689e72011-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 Espindola477d11f2011-02-20 16:27:25 +0000204 const char *symbolName = entry.getKey().data();
205 info.name = symbolName;
206 info.attributes = LTO_SYMBOL_DEFINITION_UNDEFINED;
Bill Wendling9ee2d332012-03-29 08:27:32 +0000207 info.isFunction = false;
208 info.symbol = clgv;
Rafael Espindola477d11f2011-02-20 16:27:25 +0000209 entry.setValue(info);
Nick Kledzikb481c202009-06-01 20:33:09 +0000210 }
Daniel Dunbar5657e7b2010-08-10 23:46:39 +0000211 }
Bill Wendling5f689e72011-11-04 18:48:00 +0000212
213 // third slot in __OBJC,__class is pointer to class name
214 std::string className;
215 if (objcClassNameFromExpression(c->getOperand(2), className)) {
216 StringSet::value_type &entry = _defines.GetOrCreateValue(className);
217 entry.setValue(1);
Bill Wendling9ee2d332012-03-29 08:27:32 +0000218
Bill Wendling5f689e72011-11-04 18:48:00 +0000219 NameAndAttributes info;
220 info.name = entry.getKey().data();
Bill Wendling9ee2d332012-03-29 08:27:32 +0000221 info.attributes = LTO_SYMBOL_PERMISSIONS_DATA |
222 LTO_SYMBOL_DEFINITION_REGULAR | LTO_SYMBOL_SCOPE_DEFAULT;
223 info.isFunction = false;
224 info.symbol = clgv;
Bill Wendling5f689e72011-11-04 18:48:00 +0000225 _symbols.push_back(info);
226 }
227}
228
Bill Wendlingfb440502012-03-28 20:46:54 +0000229/// addObjCCategory - Parse i386/ppc ObjC category data structure.
Bill Wendling5f689e72011-11-04 18:48:00 +0000230void LTOModule::addObjCCategory(GlobalVariable *clgv) {
231 ConstantStruct *c = dyn_cast<ConstantStruct>(clgv->getInitializer());
232 if (!c) return;
233
234 // second slot in __OBJC,__category is pointer to target class name
235 std::string targetclassName;
236 if (!objcClassNameFromExpression(c->getOperand(1), targetclassName))
237 return;
238
239 NameAndAttributes info;
240 StringMap<NameAndAttributes>::value_type &entry =
241 _undefines.GetOrCreateValue(targetclassName);
242
243 if (entry.getValue().name)
244 return;
245
246 const char *symbolName = entry.getKey().data();
247 info.name = symbolName;
248 info.attributes = LTO_SYMBOL_DEFINITION_UNDEFINED;
Bill Wendling9ee2d332012-03-29 08:27:32 +0000249 info.isFunction = false;
250 info.symbol = clgv;
Bill Wendling5f689e72011-11-04 18:48:00 +0000251 entry.setValue(info);
Nick Kledzikb481c202009-06-01 20:33:09 +0000252}
253
Bill Wendlingfb440502012-03-28 20:46:54 +0000254/// addObjCClassRef - Parse i386/ppc ObjC class list data structure.
Daniel Dunbar5657e7b2010-08-10 23:46:39 +0000255void LTOModule::addObjCClassRef(GlobalVariable *clgv) {
256 std::string targetclassName;
Bill Wendling5f689e72011-11-04 18:48:00 +0000257 if (!objcClassNameFromExpression(clgv->getInitializer(), targetclassName))
258 return;
Rafael Espindola477d11f2011-02-20 16:27:25 +0000259
Bill Wendling5f689e72011-11-04 18:48:00 +0000260 NameAndAttributes info;
261 StringMap<NameAndAttributes>::value_type &entry =
262 _undefines.GetOrCreateValue(targetclassName);
263 if (entry.getValue().name)
264 return;
Rafael Espindola477d11f2011-02-20 16:27:25 +0000265
Bill Wendling5f689e72011-11-04 18:48:00 +0000266 const char *symbolName = entry.getKey().data();
267 info.name = symbolName;
268 info.attributes = LTO_SYMBOL_DEFINITION_UNDEFINED;
Bill Wendling9ee2d332012-03-29 08:27:32 +0000269 info.isFunction = false;
270 info.symbol = clgv;
Bill Wendling5f689e72011-11-04 18:48:00 +0000271 entry.setValue(info);
Daniel Dunbar5657e7b2010-08-10 23:46:39 +0000272}
273
Bill Wendlingfb440502012-03-28 20:46:54 +0000274/// addDefinedDataSymbol - Add a data symbol as defined to the list.
Bill Wendlinga2af6742011-11-04 09:30:19 +0000275void LTOModule::addDefinedDataSymbol(GlobalValue *v) {
Daniel Dunbar5657e7b2010-08-10 23:46:39 +0000276 // Add to list of defined symbols.
Bill Wendlinga2af6742011-11-04 09:30:19 +0000277 addDefinedSymbol(v, false);
Daniel Dunbar5657e7b2010-08-10 23:46:39 +0000278
279 // Special case i386/ppc ObjC data structures in magic sections:
280 // The issue is that the old ObjC object format did some strange
281 // contortions to avoid real linker symbols. For instance, the
282 // ObjC class data structure is allocated statically in the executable
283 // that defines that class. That data structures contains a pointer to
284 // its superclass. But instead of just initializing that part of the
285 // struct to the address of its superclass, and letting the static and
286 // dynamic linkers do the rest, the runtime works by having that field
287 // instead point to a C-string that is the name of the superclass.
288 // At runtime the objc initialization updates that pointer and sets
289 // it to point to the actual super class. As far as the linker
290 // knows it is just a pointer to a string. But then someone wanted the
291 // linker to issue errors at build time if the superclass was not found.
292 // So they figured out a way in mach-o object format to use an absolute
293 // symbols (.objc_class_name_Foo = 0) and a floating reference
294 // (.reference .objc_class_name_Bar) to cause the linker into erroring when
295 // a class was missing.
296 // The following synthesizes the implicit .objc_* symbols for the linker
297 // from the ObjC data structures generated by the front end.
298 if (v->hasSection() /* && isTargetDarwin */) {
299 // special case if this data blob is an ObjC class definition
300 if (v->getSection().compare(0, 15, "__OBJC,__class,") == 0) {
301 if (GlobalVariable *gv = dyn_cast<GlobalVariable>(v)) {
302 addObjCClass(gv);
303 }
304 }
305
306 // special case if this data blob is an ObjC category definition
307 else if (v->getSection().compare(0, 18, "__OBJC,__category,") == 0) {
308 if (GlobalVariable *gv = dyn_cast<GlobalVariable>(v)) {
309 addObjCCategory(gv);
310 }
311 }
312
313 // special case if this data blob is the list of referenced classes
314 else if (v->getSection().compare(0, 18, "__OBJC,__cls_refs,") == 0) {
315 if (GlobalVariable *gv = dyn_cast<GlobalVariable>(v)) {
316 addObjCClassRef(gv);
317 }
318 }
319 }
Daniel Dunbar5657e7b2010-08-10 23:46:39 +0000320}
321
Bill Wendlingfb440502012-03-28 20:46:54 +0000322/// addDefinedFunctionSymbol - Add a function symbol as defined to the list.
323void LTOModule::addDefinedFunctionSymbol(Function *f) {
324 // add to list of defined symbols
325 addDefinedSymbol(f, true);
326}
327
328/// addDefinedSymbol - Add a defined symbol to the list.
Bill Wendlinga2af6742011-11-04 09:30:19 +0000329void LTOModule::addDefinedSymbol(GlobalValue *def, bool isFunction) {
Daniel Dunbar5657e7b2010-08-10 23:46:39 +0000330 // ignore all llvm.* symbols
331 if (def->getName().startswith("llvm."))
332 return;
333
334 // string is owned by _defines
Rafael Espindola34b59382011-02-11 05:23:09 +0000335 SmallString<64> Buffer;
Bill Wendlinga2af6742011-11-04 09:30:19 +0000336 _mangler.getNameWithPrefix(Buffer, def, false);
Daniel Dunbar5657e7b2010-08-10 23:46:39 +0000337
338 // set alignment part log2() can have rounding errors
339 uint32_t align = def->getAlignment();
340 uint32_t attr = align ? CountTrailingZeros_32(def->getAlignment()) : 0;
341
342 // set permissions part
Bill Wendling9ee2d332012-03-29 08:27:32 +0000343 if (isFunction) {
Daniel Dunbar5657e7b2010-08-10 23:46:39 +0000344 attr |= LTO_SYMBOL_PERMISSIONS_CODE;
Bill Wendling9ee2d332012-03-29 08:27:32 +0000345 } else {
Daniel Dunbar5657e7b2010-08-10 23:46:39 +0000346 GlobalVariable *gv = dyn_cast<GlobalVariable>(def);
347 if (gv && gv->isConstant())
348 attr |= LTO_SYMBOL_PERMISSIONS_RODATA;
349 else
350 attr |= LTO_SYMBOL_PERMISSIONS_DATA;
351 }
352
353 // set definition part
Bill Wendling2776d462010-09-27 18:05:19 +0000354 if (def->hasWeakLinkage() || def->hasLinkOnceLinkage() ||
355 def->hasLinkerPrivateWeakLinkage() ||
Bill Wendlingdcd7c2b2010-09-27 20:17:45 +0000356 def->hasLinkerPrivateWeakDefAutoLinkage())
Daniel Dunbar5657e7b2010-08-10 23:46:39 +0000357 attr |= LTO_SYMBOL_DEFINITION_WEAK;
Bill Wendlingdcd7c2b2010-09-27 20:17:45 +0000358 else if (def->hasCommonLinkage())
Daniel Dunbar5657e7b2010-08-10 23:46:39 +0000359 attr |= LTO_SYMBOL_DEFINITION_TENTATIVE;
Bill Wendlingdcd7c2b2010-09-27 20:17:45 +0000360 else
Daniel Dunbar5657e7b2010-08-10 23:46:39 +0000361 attr |= LTO_SYMBOL_DEFINITION_REGULAR;
Daniel Dunbar5657e7b2010-08-10 23:46:39 +0000362
363 // set scope part
364 if (def->hasHiddenVisibility())
365 attr |= LTO_SYMBOL_SCOPE_HIDDEN;
366 else if (def->hasProtectedVisibility())
367 attr |= LTO_SYMBOL_SCOPE_PROTECTED;
Bill Wendlingdcd7c2b2010-09-27 20:17:45 +0000368 else if (def->hasExternalLinkage() || def->hasWeakLinkage() ||
369 def->hasLinkOnceLinkage() || def->hasCommonLinkage() ||
370 def->hasLinkerPrivateWeakLinkage())
Daniel Dunbar5657e7b2010-08-10 23:46:39 +0000371 attr |= LTO_SYMBOL_SCOPE_DEFAULT;
Bill Wendlingdcd7c2b2010-09-27 20:17:45 +0000372 else if (def->hasLinkerPrivateWeakDefAutoLinkage())
373 attr |= LTO_SYMBOL_SCOPE_DEFAULT_CAN_BE_HIDDEN;
Daniel Dunbar5657e7b2010-08-10 23:46:39 +0000374 else
375 attr |= LTO_SYMBOL_SCOPE_INTERNAL;
376
Chad Rosier772a91f2011-06-28 18:26:12 +0000377 StringSet::value_type &entry = _defines.GetOrCreateValue(Buffer);
Rafael Espindola477d11f2011-02-20 16:27:25 +0000378 entry.setValue(1);
379
Bill Wendling9ee2d332012-03-29 08:27:32 +0000380 // fill information structure
381 NameAndAttributes info;
Rafael Espindola477d11f2011-02-20 16:27:25 +0000382 StringRef Name = entry.getKey();
383 info.name = Name.data();
384 assert(info.name[Name.size()] == '\0');
Bill Wendling9ee2d332012-03-29 08:27:32 +0000385 info.attributes = attr;
386 info.isFunction = isFunction;
387 info.symbol = def;
388
389 // add to table of symbols
Daniel Dunbar5657e7b2010-08-10 23:46:39 +0000390 _symbols.push_back(info);
Nick Kledzik07b4a622008-02-26 20:26:43 +0000391}
392
Bill Wendlingfb440502012-03-28 20:46:54 +0000393/// addAsmGlobalSymbol - Add a global symbol from module-level ASM to the
394/// defined list.
Rafael Espindola1e49a6d2011-03-02 04:14:42 +0000395void LTOModule::addAsmGlobalSymbol(const char *name,
396 lto_symbol_attributes scope) {
Rafael Espindola477d11f2011-02-20 16:27:25 +0000397 StringSet::value_type &entry = _defines.GetOrCreateValue(name);
398
Daniel Dunbar5657e7b2010-08-10 23:46:39 +0000399 // only add new define if not already defined
Rafael Espindola477d11f2011-02-20 16:27:25 +0000400 if (entry.getValue())
Daniel Dunbar5657e7b2010-08-10 23:46:39 +0000401 return;
402
Rafael Espindola477d11f2011-02-20 16:27:25 +0000403 entry.setValue(1);
Bill Wendling9ee2d332012-03-29 08:27:32 +0000404
405 NameAndAttributes &info = _undefines[entry.getKey().data()];
406
407 if (info.isFunction)
408 addDefinedFunctionSymbol(cast<Function>(info.symbol));
409 else
410 addDefinedDataSymbol(info.symbol);
Devang Patela59fe952008-07-16 18:06:52 +0000411}
Nick Kledzik07b4a622008-02-26 20:26:43 +0000412
Bill Wendlingfb440502012-03-28 20:46:54 +0000413/// addAsmGlobalSymbolUndef - Add a global symbol from module-level ASM to the
414/// undefined list.
Rafael Espindola1e49a6d2011-03-02 04:14:42 +0000415void LTOModule::addAsmGlobalSymbolUndef(const char *name) {
416 StringMap<NameAndAttributes>::value_type &entry =
417 _undefines.GetOrCreateValue(name);
418
419 _asm_undefines.push_back(entry.getKey().data());
420
421 // we already have the symbol
422 if (entry.getValue().name)
423 return;
424
425 uint32_t attr = LTO_SYMBOL_DEFINITION_UNDEFINED;;
426 attr |= LTO_SYMBOL_SCOPE_DEFAULT;
427 NameAndAttributes info;
428 info.name = entry.getKey().data();
Bill Wendling9ee2d332012-03-29 08:27:32 +0000429 info.attributes = attr;
430 info.isFunction = false;
431 info.symbol = 0;
Rafael Espindola1e49a6d2011-03-02 04:14:42 +0000432
433 entry.setValue(info);
434}
435
Bill Wendlingfb440502012-03-28 20:46:54 +0000436/// addPotentialUndefinedSymbol - Add a symbol which isn't defined just yet to a
437/// list to be resolved later.
Bill Wendling9ee2d332012-03-29 08:27:32 +0000438void LTOModule::addPotentialUndefinedSymbol(GlobalValue *decl, bool isFunc) {
Daniel Dunbar5657e7b2010-08-10 23:46:39 +0000439 // ignore all llvm.* symbols
440 if (decl->getName().startswith("llvm."))
441 return;
Nick Kledzikb481c202009-06-01 20:33:09 +0000442
Daniel Dunbar5657e7b2010-08-10 23:46:39 +0000443 // ignore all aliases
444 if (isa<GlobalAlias>(decl))
445 return;
Nick Lewycky0661b932009-07-09 06:03:04 +0000446
Rafael Espindola34b59382011-02-11 05:23:09 +0000447 SmallString<64> name;
Bill Wendlinga2af6742011-11-04 09:30:19 +0000448 _mangler.getNameWithPrefix(name, decl, false);
Rafael Espindola56548522009-04-24 16:55:21 +0000449
Rafael Espindola477d11f2011-02-20 16:27:25 +0000450 StringMap<NameAndAttributes>::value_type &entry =
Chad Rosier772a91f2011-06-28 18:26:12 +0000451 _undefines.GetOrCreateValue(name);
Rafael Espindola477d11f2011-02-20 16:27:25 +0000452
Daniel Dunbar5657e7b2010-08-10 23:46:39 +0000453 // we already have the symbol
Rafael Espindola477d11f2011-02-20 16:27:25 +0000454 if (entry.getValue().name)
Daniel Dunbar5657e7b2010-08-10 23:46:39 +0000455 return;
Rafael Espindola56548522009-04-24 16:55:21 +0000456
Daniel Dunbar5657e7b2010-08-10 23:46:39 +0000457 NameAndAttributes info;
Rafael Espindola477d11f2011-02-20 16:27:25 +0000458
459 info.name = entry.getKey().data();
Bill Wendlingfb440502012-03-28 20:46:54 +0000460
Daniel Dunbar5657e7b2010-08-10 23:46:39 +0000461 if (decl->hasExternalWeakLinkage())
462 info.attributes = LTO_SYMBOL_DEFINITION_WEAKUNDEF;
463 else
464 info.attributes = LTO_SYMBOL_DEFINITION_UNDEFINED;
Rafael Espindola477d11f2011-02-20 16:27:25 +0000465
Bill Wendling9ee2d332012-03-29 08:27:32 +0000466 info.isFunction = isFunc;
467 info.symbol = decl;
468
Rafael Espindola477d11f2011-02-20 16:27:25 +0000469 entry.setValue(info);
Nick Kledzik07b4a622008-02-26 20:26:43 +0000470}
471
Rafael Espindola1e49a6d2011-03-02 04:14:42 +0000472namespace {
473 class RecordStreamer : public MCStreamer {
474 public:
475 enum State { NeverSeen, Global, Defined, DefinedGlobal, Used};
Daniel Dunbar5657e7b2010-08-10 23:46:39 +0000476
Rafael Espindola1e49a6d2011-03-02 04:14:42 +0000477 private:
478 StringMap<State> Symbols;
Daniel Dunbar5657e7b2010-08-10 23:46:39 +0000479
Rafael Espindola1e49a6d2011-03-02 04:14:42 +0000480 void markDefined(const MCSymbol &Symbol) {
481 State &S = Symbols[Symbol.getName()];
482 switch (S) {
483 case DefinedGlobal:
484 case Global:
485 S = DefinedGlobal;
486 break;
487 case NeverSeen:
488 case Defined:
489 case Used:
490 S = Defined;
491 break;
492 }
493 }
494 void markGlobal(const MCSymbol &Symbol) {
495 State &S = Symbols[Symbol.getName()];
496 switch (S) {
497 case DefinedGlobal:
498 case Defined:
499 S = DefinedGlobal;
500 break;
501
502 case NeverSeen:
503 case Global:
504 case Used:
505 S = Global;
506 break;
507 }
508 }
509 void markUsed(const MCSymbol &Symbol) {
510 State &S = Symbols[Symbol.getName()];
511 switch (S) {
512 case DefinedGlobal:
513 case Defined:
514 case Global:
515 break;
516
517 case NeverSeen:
518 case Used:
519 S = Used;
520 break;
521 }
522 }
523
524 // FIXME: mostly copied for the obj streamer.
525 void AddValueSymbols(const MCExpr *Value) {
526 switch (Value->getKind()) {
527 case MCExpr::Target:
528 // FIXME: What should we do in here?
529 break;
530
531 case MCExpr::Constant:
532 break;
533
534 case MCExpr::Binary: {
535 const MCBinaryExpr *BE = cast<MCBinaryExpr>(Value);
536 AddValueSymbols(BE->getLHS());
537 AddValueSymbols(BE->getRHS());
538 break;
539 }
540
541 case MCExpr::SymbolRef:
542 markUsed(cast<MCSymbolRefExpr>(Value)->getSymbol());
543 break;
544
545 case MCExpr::Unary:
546 AddValueSymbols(cast<MCUnaryExpr>(Value)->getSubExpr());
547 break;
548 }
549 }
550
551 public:
552 typedef StringMap<State>::const_iterator const_iterator;
553
554 const_iterator begin() {
555 return Symbols.begin();
556 }
557
558 const_iterator end() {
559 return Symbols.end();
560 }
561
562 RecordStreamer(MCContext &Context) : MCStreamer(Context) {}
563
564 virtual void ChangeSection(const MCSection *Section) {}
565 virtual void InitSections() {}
566 virtual void EmitLabel(MCSymbol *Symbol) {
567 Symbol->setSection(*getCurrentSection());
568 markDefined(*Symbol);
569 }
570 virtual void EmitAssemblerFlag(MCAssemblerFlag Flag) {}
571 virtual void EmitThumbFunc(MCSymbol *Func) {}
572 virtual void EmitAssignment(MCSymbol *Symbol, const MCExpr *Value) {
573 // FIXME: should we handle aliases?
574 markDefined(*Symbol);
575 }
576 virtual void EmitSymbolAttribute(MCSymbol *Symbol, MCSymbolAttr Attribute) {
577 if (Attribute == MCSA_Global)
578 markGlobal(*Symbol);
579 }
580 virtual void EmitSymbolDesc(MCSymbol *Symbol, unsigned DescValue) {}
581 virtual void EmitWeakReference(MCSymbol *Alias, const MCSymbol *Symbol) {}
582 virtual void BeginCOFFSymbolDef(const MCSymbol *Symbol) {}
583 virtual void EmitCOFFSymbolStorageClass(int StorageClass) {}
584 virtual void EmitZerofill(const MCSection *Section, MCSymbol *Symbol,
585 unsigned Size , unsigned ByteAlignment) {
586 markDefined(*Symbol);
587 }
588 virtual void EmitCOFFSymbolType(int Type) {}
589 virtual void EndCOFFSymbolDef() {}
590 virtual void EmitCommonSymbol(MCSymbol *Symbol, uint64_t Size,
591 unsigned ByteAlignment) {
592 markDefined(*Symbol);
593 }
594 virtual void EmitELFSize(MCSymbol *Symbol, const MCExpr *Value) {}
Benjamin Kramer63970512011-09-01 23:04:27 +0000595 virtual void EmitLocalCommonSymbol(MCSymbol *Symbol, uint64_t Size,
596 unsigned ByteAlignment) {}
Rafael Espindola1e49a6d2011-03-02 04:14:42 +0000597 virtual void EmitTBSSSymbol(const MCSection *Section, MCSymbol *Symbol,
598 uint64_t Size, unsigned ByteAlignment) {}
599 virtual void EmitBytes(StringRef Data, unsigned AddrSpace) {}
600 virtual void EmitValueImpl(const MCExpr *Value, unsigned Size,
Rafael Espindolafd057852011-05-01 03:50:49 +0000601 unsigned AddrSpace) {}
Rafael Espindola6aea5922011-04-21 23:39:26 +0000602 virtual void EmitULEB128Value(const MCExpr *Value) {}
603 virtual void EmitSLEB128Value(const MCExpr *Value) {}
Rafael Espindola1e49a6d2011-03-02 04:14:42 +0000604 virtual void EmitValueToAlignment(unsigned ByteAlignment, int64_t Value,
605 unsigned ValueSize,
606 unsigned MaxBytesToEmit) {}
607 virtual void EmitCodeAlignment(unsigned ByteAlignment,
608 unsigned MaxBytesToEmit) {}
Jim Grosbachb5912772012-01-27 00:37:08 +0000609 virtual bool EmitValueToOffset(const MCExpr *Offset,
610 unsigned char Value ) { return false; }
Rafael Espindola1e49a6d2011-03-02 04:14:42 +0000611 virtual void EmitFileDirective(StringRef Filename) {}
612 virtual void EmitDwarfAdvanceLineAddr(int64_t LineDelta,
613 const MCSymbol *LastLabel,
Evan Chengc7ac6902011-07-14 05:43:07 +0000614 const MCSymbol *Label,
615 unsigned PointerSize) {}
Rafael Espindola1e49a6d2011-03-02 04:14:42 +0000616
617 virtual void EmitInstruction(const MCInst &Inst) {
618 // Scan for values.
619 for (unsigned i = Inst.getNumOperands(); i--; )
620 if (Inst.getOperand(i).isExpr())
621 AddValueSymbols(Inst.getOperand(i).getExpr());
622 }
Rafael Espindola07082092012-01-07 03:13:18 +0000623 virtual void FinishImpl() {}
Rafael Espindola1e49a6d2011-03-02 04:14:42 +0000624 };
Bill Wendling9ee2d332012-03-29 08:27:32 +0000625} // end anonymous namespace
Rafael Espindola1e49a6d2011-03-02 04:14:42 +0000626
Bill Wendlingfb440502012-03-28 20:46:54 +0000627/// addAsmGlobalSymbols - Add global symbols from module-level ASM to the
628/// defined or undefined lists.
Bill Wendlingac2abde2011-11-04 09:24:40 +0000629bool LTOModule::addAsmGlobalSymbols(std::string &errMsg) {
Rafael Espindola1e49a6d2011-03-02 04:14:42 +0000630 const std::string &inlineAsm = _module->getModuleInlineAsm();
Ivan Krasincc2a8012011-09-08 07:38:25 +0000631 if (inlineAsm.empty())
632 return false;
Rafael Espindola1e49a6d2011-03-02 04:14:42 +0000633
Bill Wendlingac2abde2011-11-04 09:24:40 +0000634 OwningPtr<RecordStreamer> Streamer(new RecordStreamer(_context));
Rafael Espindola1e49a6d2011-03-02 04:14:42 +0000635 MemoryBuffer *Buffer = MemoryBuffer::getMemBuffer(inlineAsm);
636 SourceMgr SrcMgr;
637 SrcMgr.AddNewSourceBuffer(Buffer, SMLoc());
Jim Grosbach345768c2011-08-16 18:33:49 +0000638 OwningPtr<MCAsmParser> Parser(createMCAsmParser(SrcMgr,
Bill Wendlingac2abde2011-11-04 09:24:40 +0000639 _context, *Streamer,
Rafael Espindola1e49a6d2011-03-02 04:14:42 +0000640 *_target->getMCAsmInfo()));
Evan Cheng91111d22011-07-09 05:47:46 +0000641 OwningPtr<MCSubtargetInfo> STI(_target->getTarget().
642 createMCSubtargetInfo(_target->getTargetTriple(),
643 _target->getTargetCPU(),
644 _target->getTargetFeatureString()));
Evan Cheng11424442011-07-26 00:24:13 +0000645 OwningPtr<MCTargetAsmParser>
646 TAP(_target->getTarget().createMCAsmParser(*STI, *Parser.get()));
Ivan Krasin8149dd62011-09-08 07:36:39 +0000647 if (!TAP) {
648 errMsg = "target " + std::string(_target->getTarget().getName()) +
649 " does not define AsmParser.";
650 return true;
651 }
652
Rafael Espindola1e49a6d2011-03-02 04:14:42 +0000653 Parser->setTargetParser(*TAP);
654 int Res = Parser->Run(false);
655 if (Res)
656 return true;
657
658 for (RecordStreamer::const_iterator i = Streamer->begin(),
659 e = Streamer->end(); i != e; ++i) {
660 StringRef Key = i->first();
661 RecordStreamer::State Value = i->second;
662 if (Value == RecordStreamer::DefinedGlobal)
663 addAsmGlobalSymbol(Key.data(), LTO_SYMBOL_SCOPE_DEFAULT);
664 else if (Value == RecordStreamer::Defined)
665 addAsmGlobalSymbol(Key.data(), LTO_SYMBOL_SCOPE_INTERNAL);
666 else if (Value == RecordStreamer::Global ||
667 Value == RecordStreamer::Used)
668 addAsmGlobalSymbolUndef(Key.data());
669 }
670 return false;
671}
672
Bill Wendlingfb440502012-03-28 20:46:54 +0000673/// isDeclaration - Return 'true' if the global value is a declaration.
Rafael Espindola5b778b22011-03-18 19:51:00 +0000674static bool isDeclaration(const GlobalValue &V) {
675 if (V.hasAvailableExternallyLinkage())
676 return true;
677 if (V.isMaterializable())
678 return false;
679 return V.isDeclaration();
680}
681
Bill Wendling7e58b382012-03-28 23:12:18 +0000682/// parseSymbols - Parse the symbols from the module and model-level ASM and add
Bill Wendlingfb440502012-03-28 20:46:54 +0000683/// them to either the defined or undefined lists.
Bill Wendling7e58b382012-03-28 23:12:18 +0000684bool LTOModule::parseSymbols(std::string &errMsg) {
Daniel Dunbar919660b2010-08-10 23:46:46 +0000685 // add functions
Bill Wendling763acfc2012-03-29 03:34:57 +0000686 for (Module::iterator f = _module->begin(), e = _module->end(); f != e; ++f) {
Rafael Espindola5b778b22011-03-18 19:51:00 +0000687 if (isDeclaration(*f))
Bill Wendling9ee2d332012-03-29 08:27:32 +0000688 addPotentialUndefinedSymbol(f, true);
Daniel Dunbar919660b2010-08-10 23:46:46 +0000689 else
Bill Wendlinga2af6742011-11-04 09:30:19 +0000690 addDefinedFunctionSymbol(f);
Daniel Dunbar919660b2010-08-10 23:46:46 +0000691 }
Nick Kledzik07b4a622008-02-26 20:26:43 +0000692
Daniel Dunbar919660b2010-08-10 23:46:46 +0000693 // add data
694 for (Module::global_iterator v = _module->global_begin(),
695 e = _module->global_end(); v != e; ++v) {
Rafael Espindola5b778b22011-03-18 19:51:00 +0000696 if (isDeclaration(*v))
Bill Wendling9ee2d332012-03-29 08:27:32 +0000697 addPotentialUndefinedSymbol(v, false);
Daniel Dunbar919660b2010-08-10 23:46:46 +0000698 else
Bill Wendlinga2af6742011-11-04 09:30:19 +0000699 addDefinedDataSymbol(v);
Daniel Dunbar919660b2010-08-10 23:46:46 +0000700 }
Nick Kledzik07b4a622008-02-26 20:26:43 +0000701
Daniel Dunbar919660b2010-08-10 23:46:46 +0000702 // add asm globals
Bill Wendlingac2abde2011-11-04 09:24:40 +0000703 if (addAsmGlobalSymbols(errMsg))
Rafael Espindola1e49a6d2011-03-02 04:14:42 +0000704 return true;
Daniel Dunbar919660b2010-08-10 23:46:46 +0000705
Rafael Espindolaa8a74ec2010-10-20 04:57:22 +0000706 // add aliases
Bill Wendling9ee2d332012-03-29 08:27:32 +0000707 for (Module::alias_iterator a = _module->alias_begin(),
708 e = _module->alias_end(); a != e; ++a) {
709 if (isDeclaration(*a->getAliasedGlobal()))
Bill Wendlingd58ed732012-03-28 20:48:49 +0000710 // Is an alias to a declaration.
Bill Wendling9ee2d332012-03-29 08:27:32 +0000711 addPotentialUndefinedSymbol(a, false);
Rafael Espindolaa8a74ec2010-10-20 04:57:22 +0000712 else
Bill Wendling9ee2d332012-03-29 08:27:32 +0000713 addDefinedDataSymbol(a);
Rafael Espindolaa8a74ec2010-10-20 04:57:22 +0000714 }
715
Daniel Dunbar919660b2010-08-10 23:46:46 +0000716 // make symbols for all undefines
Bill Wendling9ee2d332012-03-29 08:27:32 +0000717 for (StringMap<NameAndAttributes>::iterator u =_undefines.begin(),
718 e = _undefines.end(); u != e; ++u) {
719 // If this symbol also has a definition, then don't make an undefine because
720 // it is a tentative definition.
721 if (_defines.count(u->getKey())) continue;
722 NameAndAttributes info = u->getValue();
723 _symbols.push_back(info);
Daniel Dunbar5657e7b2010-08-10 23:46:39 +0000724 }
Bill Wendling9ee2d332012-03-29 08:27:32 +0000725
Rafael Espindola1e49a6d2011-03-02 04:14:42 +0000726 return false;
Nick Kledzik91a6dcf2008-02-27 22:25:36 +0000727}