Don't open the file again in the gold plugin. To be able to do this, update
[oota-llvm.git] / tools / lto / LTOModule.cpp
1 //===-- LTOModule.cpp - LLVM Link Time Optimizer --------------------------===//
2 //
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.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements the Link Time Optimization library. This library is
11 // intended to be used by linker to optimize code at link time.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #include "LTOModule.h"
16
17 #include "llvm/Constants.h"
18 #include "llvm/LLVMContext.h"
19 #include "llvm/Module.h"
20 #include "llvm/ADT/OwningPtr.h"
21 #include "llvm/ADT/Triple.h"
22 #include "llvm/Bitcode/ReaderWriter.h"
23 #include "llvm/Support/SystemUtils.h"
24 #include "llvm/Support/MemoryBuffer.h"
25 #include "llvm/Support/MathExtras.h"
26 #include "llvm/Support/Host.h"
27 #include "llvm/Support/Path.h"
28 #include "llvm/Support/Process.h"
29 #include "llvm/Support/system_error.h"
30 #include "llvm/Target/Mangler.h"
31 #include "llvm/Target/SubtargetFeature.h"
32 #include "llvm/MC/MCAsmInfo.h"
33 #include "llvm/MC/MCContext.h"
34 #include "llvm/Target/TargetMachine.h"
35 #include "llvm/Target/TargetRegistry.h"
36 #include "llvm/Target/TargetSelect.h"
37
38 using namespace llvm;
39
40 bool LTOModule::isBitcodeFile(const void *mem, size_t length) {
41   return llvm::sys::IdentifyFileType((char*)mem, length)
42     == llvm::sys::Bitcode_FileType;
43 }
44
45 bool LTOModule::isBitcodeFile(const char *path) {
46   return llvm::sys::Path(path).isBitcodeFile();
47 }
48
49 bool LTOModule::isBitcodeFileForTarget(const void *mem, size_t length,
50                                        const char *triplePrefix) {
51   MemoryBuffer *buffer = makeBuffer(mem, length);
52   if (!buffer)
53     return false;
54   return isTargetMatch(buffer, triplePrefix);
55 }
56
57
58 bool LTOModule::isBitcodeFileForTarget(const char *path,
59                                        const char *triplePrefix) {
60   OwningPtr<MemoryBuffer> buffer;
61   if (MemoryBuffer::getFile(path, buffer))
62     return false;
63   return isTargetMatch(buffer.take(), triplePrefix);
64 }
65
66 // Takes ownership of buffer.
67 bool LTOModule::isTargetMatch(MemoryBuffer *buffer, const char *triplePrefix) {
68   std::string Triple = getBitcodeTargetTriple(buffer, getGlobalContext());
69   delete buffer;
70   return (strncmp(Triple.c_str(), triplePrefix,
71                   strlen(triplePrefix)) == 0);
72 }
73
74
75 LTOModule::LTOModule(Module *m, TargetMachine *t)
76   : _module(m), _target(t), _symbolsParsed(false)
77 {
78 }
79
80 LTOModule *LTOModule::makeLTOModule(const char *path,
81                                     std::string &errMsg) {
82   OwningPtr<MemoryBuffer> buffer;
83   if (error_code ec = MemoryBuffer::getFile(path, buffer)) {
84     errMsg = ec.message();
85     return NULL;
86   }
87   return makeLTOModule(buffer.get(), errMsg);
88 }
89
90 LTOModule *LTOModule::makeLTOModule(int fd, const char *path,
91                                     off_t size,
92                                     std::string &errMsg) {
93   OwningPtr<MemoryBuffer> buffer;
94   if (error_code ec = MemoryBuffer::getOpenFile(fd, path, buffer, size)) {
95     errMsg = ec.message();
96     return NULL;
97   }
98   return makeLTOModule(buffer.get(), errMsg);
99 }
100
101 /// makeBuffer - Create a MemoryBuffer from a memory range.  MemoryBuffer
102 /// requires the byte past end of the buffer to be a zero.  We might get lucky
103 /// and already be that way, otherwise make a copy.  Also if next byte is on a
104 /// different page, don't assume it is readable.
105 MemoryBuffer *LTOModule::makeBuffer(const void *mem, size_t length) {
106   const char *startPtr = (char*)mem;
107   const char *endPtr = startPtr+length;
108   if (((uintptr_t)endPtr & (sys::Process::GetPageSize()-1)) == 0 ||
109       *endPtr != 0)
110     return MemoryBuffer::getMemBufferCopy(StringRef(startPtr, length));
111
112   return MemoryBuffer::getMemBuffer(StringRef(startPtr, length));
113 }
114
115
116 LTOModule *LTOModule::makeLTOModule(const void *mem, size_t length,
117                                     std::string &errMsg) {
118   OwningPtr<MemoryBuffer> buffer(makeBuffer(mem, length));
119   if (!buffer)
120     return NULL;
121   return makeLTOModule(buffer.get(), errMsg);
122 }
123
124 LTOModule *LTOModule::makeLTOModule(MemoryBuffer *buffer,
125                                     std::string &errMsg) {
126   InitializeAllTargets();
127
128   // parse bitcode buffer
129   OwningPtr<Module> m(ParseBitcodeFile(buffer, getGlobalContext(), &errMsg));
130   if (!m)
131     return NULL;
132
133   std::string Triple = m->getTargetTriple();
134   if (Triple.empty())
135     Triple = sys::getHostTriple();
136
137   // find machine architecture for this module
138   const Target *march = TargetRegistry::lookupTarget(Triple, errMsg);
139   if (!march)
140     return NULL;
141
142   // construct LTModule, hand over ownership of module and target
143   SubtargetFeatures Features;
144   Features.getDefaultSubtargetFeatures("" /* cpu */, llvm::Triple(Triple));
145   std::string FeatureStr = Features.getString();
146   TargetMachine *target = march->createTargetMachine(Triple, FeatureStr);
147   return new LTOModule(m.take(), target);
148 }
149
150
151 const char *LTOModule::getTargetTriple() {
152   return _module->getTargetTriple().c_str();
153 }
154
155 void LTOModule::setTargetTriple(const char *triple) {
156   _module->setTargetTriple(triple);
157 }
158
159 void LTOModule::addDefinedFunctionSymbol(Function *f, Mangler &mangler) {
160   // add to list of defined symbols
161   addDefinedSymbol(f, mangler, true);
162
163   // add external symbols referenced by this function.
164   for (Function::iterator b = f->begin(); b != f->end(); ++b) {
165     for (BasicBlock::iterator i = b->begin(); i != b->end(); ++i) {
166       for (unsigned count = 0, total = i->getNumOperands();
167            count != total; ++count) {
168         findExternalRefs(i->getOperand(count), mangler);
169       }
170     }
171   }
172 }
173
174 // Get string that data pointer points to.
175 bool LTOModule::objcClassNameFromExpression(Constant *c, std::string &name) {
176   if (ConstantExpr *ce = dyn_cast<ConstantExpr>(c)) {
177     Constant *op = ce->getOperand(0);
178     if (GlobalVariable *gvn = dyn_cast<GlobalVariable>(op)) {
179       Constant *cn = gvn->getInitializer();
180       if (ConstantArray *ca = dyn_cast<ConstantArray>(cn)) {
181         if (ca->isCString()) {
182           name = ".objc_class_name_" + ca->getAsString();
183           return true;
184         }
185       }
186     }
187   }
188   return false;
189 }
190
191 // Parse i386/ppc ObjC class data structure.
192 void LTOModule::addObjCClass(GlobalVariable *clgv) {
193   if (ConstantStruct *c = dyn_cast<ConstantStruct>(clgv->getInitializer())) {
194     // second slot in __OBJC,__class is pointer to superclass name
195     std::string superclassName;
196     if (objcClassNameFromExpression(c->getOperand(1), superclassName)) {
197       NameAndAttributes info;
198       if (_undefines.find(superclassName.c_str()) == _undefines.end()) {
199         const char *symbolName = ::strdup(superclassName.c_str());
200         info.name = symbolName;
201         info.attributes = LTO_SYMBOL_DEFINITION_UNDEFINED;
202         // string is owned by _undefines
203         _undefines[info.name] = info;
204       }
205     }
206     // third slot in __OBJC,__class is pointer to class name
207     std::string className;
208     if (objcClassNameFromExpression(c->getOperand(2), className)) {
209       const char *symbolName = ::strdup(className.c_str());
210       NameAndAttributes info;
211       info.name = symbolName;
212       info.attributes = (lto_symbol_attributes)
213         (LTO_SYMBOL_PERMISSIONS_DATA |
214          LTO_SYMBOL_DEFINITION_REGULAR |
215          LTO_SYMBOL_SCOPE_DEFAULT);
216       _symbols.push_back(info);
217       _defines[info.name] = 1;
218     }
219   }
220 }
221
222
223 // Parse i386/ppc ObjC category data structure.
224 void LTOModule::addObjCCategory(GlobalVariable *clgv) {
225   if (ConstantStruct *c = dyn_cast<ConstantStruct>(clgv->getInitializer())) {
226     // second slot in __OBJC,__category is pointer to target class name
227     std::string targetclassName;
228     if (objcClassNameFromExpression(c->getOperand(1), targetclassName)) {
229       NameAndAttributes info;
230       if (_undefines.find(targetclassName.c_str()) == _undefines.end()) {
231         const char *symbolName = ::strdup(targetclassName.c_str());
232         info.name = symbolName;
233         info.attributes = LTO_SYMBOL_DEFINITION_UNDEFINED;
234         // string is owned by _undefines
235         _undefines[info.name] = info;
236       }
237     }
238   }
239 }
240
241
242 // Parse i386/ppc ObjC class list data structure.
243 void LTOModule::addObjCClassRef(GlobalVariable *clgv) {
244   std::string targetclassName;
245   if (objcClassNameFromExpression(clgv->getInitializer(), targetclassName)) {
246     NameAndAttributes info;
247     if (_undefines.find(targetclassName.c_str()) == _undefines.end()) {
248       const char *symbolName = ::strdup(targetclassName.c_str());
249       info.name = symbolName;
250       info.attributes = LTO_SYMBOL_DEFINITION_UNDEFINED;
251       // string is owned by _undefines
252       _undefines[info.name] = info;
253     }
254   }
255 }
256
257
258 void LTOModule::addDefinedDataSymbol(GlobalValue *v, Mangler &mangler) {
259   // Add to list of defined symbols.
260   addDefinedSymbol(v, mangler, false);
261
262   // Special case i386/ppc ObjC data structures in magic sections:
263   // The issue is that the old ObjC object format did some strange
264   // contortions to avoid real linker symbols.  For instance, the
265   // ObjC class data structure is allocated statically in the executable
266   // that defines that class.  That data structures contains a pointer to
267   // its superclass.  But instead of just initializing that part of the
268   // struct to the address of its superclass, and letting the static and
269   // dynamic linkers do the rest, the runtime works by having that field
270   // instead point to a C-string that is the name of the superclass.
271   // At runtime the objc initialization updates that pointer and sets
272   // it to point to the actual super class.  As far as the linker
273   // knows it is just a pointer to a string.  But then someone wanted the
274   // linker to issue errors at build time if the superclass was not found.
275   // So they figured out a way in mach-o object format to use an absolute
276   // symbols (.objc_class_name_Foo = 0) and a floating reference
277   // (.reference .objc_class_name_Bar) to cause the linker into erroring when
278   // a class was missing.
279   // The following synthesizes the implicit .objc_* symbols for the linker
280   // from the ObjC data structures generated by the front end.
281   if (v->hasSection() /* && isTargetDarwin */) {
282     // special case if this data blob is an ObjC class definition
283     if (v->getSection().compare(0, 15, "__OBJC,__class,") == 0) {
284       if (GlobalVariable *gv = dyn_cast<GlobalVariable>(v)) {
285         addObjCClass(gv);
286       }
287     }
288
289     // special case if this data blob is an ObjC category definition
290     else if (v->getSection().compare(0, 18, "__OBJC,__category,") == 0) {
291       if (GlobalVariable *gv = dyn_cast<GlobalVariable>(v)) {
292         addObjCCategory(gv);
293       }
294     }
295
296     // special case if this data blob is the list of referenced classes
297     else if (v->getSection().compare(0, 18, "__OBJC,__cls_refs,") == 0) {
298       if (GlobalVariable *gv = dyn_cast<GlobalVariable>(v)) {
299         addObjCClassRef(gv);
300       }
301     }
302   }
303
304   // add external symbols referenced by this data.
305   for (unsigned count = 0, total = v->getNumOperands();
306        count != total; ++count) {
307     findExternalRefs(v->getOperand(count), mangler);
308   }
309 }
310
311
312 void LTOModule::addDefinedSymbol(GlobalValue *def, Mangler &mangler,
313                                  bool isFunction) {
314   // ignore all llvm.* symbols
315   if (def->getName().startswith("llvm."))
316     return;
317
318   // ignore available_externally
319   if (def->hasAvailableExternallyLinkage())
320     return;
321
322   // string is owned by _defines
323   const char *symbolName = ::strdup(mangler.getNameWithPrefix(def).c_str());
324
325   // set alignment part log2() can have rounding errors
326   uint32_t align = def->getAlignment();
327   uint32_t attr = align ? CountTrailingZeros_32(def->getAlignment()) : 0;
328
329   // set permissions part
330   if (isFunction)
331     attr |= LTO_SYMBOL_PERMISSIONS_CODE;
332   else {
333     GlobalVariable *gv = dyn_cast<GlobalVariable>(def);
334     if (gv && gv->isConstant())
335       attr |= LTO_SYMBOL_PERMISSIONS_RODATA;
336     else
337       attr |= LTO_SYMBOL_PERMISSIONS_DATA;
338   }
339
340   // set definition part
341   if (def->hasWeakLinkage() || def->hasLinkOnceLinkage() ||
342       def->hasLinkerPrivateWeakLinkage() ||
343       def->hasLinkerPrivateWeakDefAutoLinkage())
344     attr |= LTO_SYMBOL_DEFINITION_WEAK;
345   else if (def->hasCommonLinkage())
346     attr |= LTO_SYMBOL_DEFINITION_TENTATIVE;
347   else
348     attr |= LTO_SYMBOL_DEFINITION_REGULAR;
349
350   // set scope part
351   if (def->hasHiddenVisibility())
352     attr |= LTO_SYMBOL_SCOPE_HIDDEN;
353   else if (def->hasProtectedVisibility())
354     attr |= LTO_SYMBOL_SCOPE_PROTECTED;
355   else if (def->hasExternalLinkage() || def->hasWeakLinkage() ||
356            def->hasLinkOnceLinkage() || def->hasCommonLinkage() ||
357            def->hasLinkerPrivateWeakLinkage())
358     attr |= LTO_SYMBOL_SCOPE_DEFAULT;
359   else if (def->hasLinkerPrivateWeakDefAutoLinkage())
360     attr |= LTO_SYMBOL_SCOPE_DEFAULT_CAN_BE_HIDDEN;
361   else
362     attr |= LTO_SYMBOL_SCOPE_INTERNAL;
363
364   // add to table of symbols
365   NameAndAttributes info;
366   info.name = symbolName;
367   info.attributes = (lto_symbol_attributes)attr;
368   _symbols.push_back(info);
369   _defines[info.name] = 1;
370 }
371
372 void LTOModule::addAsmGlobalSymbol(const char *name) {
373   // only add new define if not already defined
374   if (_defines.count(name))
375     return;
376
377   // string is owned by _defines
378   const char *symbolName = ::strdup(name);
379   uint32_t attr = LTO_SYMBOL_DEFINITION_REGULAR;
380   attr |= LTO_SYMBOL_SCOPE_DEFAULT;
381   NameAndAttributes info;
382   info.name = symbolName;
383   info.attributes = (lto_symbol_attributes)attr;
384   _symbols.push_back(info);
385   _defines[info.name] = 1;
386 }
387
388 void LTOModule::addPotentialUndefinedSymbol(GlobalValue *decl,
389                                             Mangler &mangler) {
390   // ignore all llvm.* symbols
391   if (decl->getName().startswith("llvm."))
392     return;
393
394   // ignore all aliases
395   if (isa<GlobalAlias>(decl))
396     return;
397
398   std::string name = mangler.getNameWithPrefix(decl);
399
400   // we already have the symbol
401   if (_undefines.find(name) != _undefines.end())
402     return;
403
404   NameAndAttributes info;
405   // string is owned by _undefines
406   info.name = ::strdup(name.c_str());
407   if (decl->hasExternalWeakLinkage())
408     info.attributes = LTO_SYMBOL_DEFINITION_WEAKUNDEF;
409   else
410     info.attributes = LTO_SYMBOL_DEFINITION_UNDEFINED;
411   _undefines[name] = info;
412 }
413
414
415
416 // Find external symbols referenced by VALUE. This is a recursive function.
417 void LTOModule::findExternalRefs(Value *value, Mangler &mangler) {
418   if (GlobalValue *gv = dyn_cast<GlobalValue>(value)) {
419     if (!gv->hasExternalLinkage())
420       addPotentialUndefinedSymbol(gv, mangler);
421     // If this is a variable definition, do not recursively process
422     // initializer.  It might contain a reference to this variable
423     // and cause an infinite loop.  The initializer will be
424     // processed in addDefinedDataSymbol().
425     return;
426   }
427
428   // GlobalValue, even with InternalLinkage type, may have operands with
429   // ExternalLinkage type. Do not ignore these operands.
430   if (Constant *c = dyn_cast<Constant>(value)) {
431     // Handle ConstantExpr, ConstantStruct, ConstantArry etc.
432     for (unsigned i = 0, e = c->getNumOperands(); i != e; ++i)
433       findExternalRefs(c->getOperand(i), mangler);
434   }
435 }
436
437 void LTOModule::lazyParseSymbols() {
438   if (_symbolsParsed)
439     return;
440
441   _symbolsParsed = true;
442
443   // Use mangler to add GlobalPrefix to names to match linker names.
444   MCContext Context(*_target->getMCAsmInfo(), NULL);
445   Mangler mangler(Context, *_target->getTargetData());
446
447   // add functions
448   for (Module::iterator f = _module->begin(); f != _module->end(); ++f) {
449     if (f->isDeclaration())
450       addPotentialUndefinedSymbol(f, mangler);
451     else
452       addDefinedFunctionSymbol(f, mangler);
453   }
454
455   // add data
456   for (Module::global_iterator v = _module->global_begin(),
457          e = _module->global_end(); v !=  e; ++v) {
458     if (v->isDeclaration())
459       addPotentialUndefinedSymbol(v, mangler);
460     else
461       addDefinedDataSymbol(v, mangler);
462   }
463
464   // add asm globals
465   const std::string &inlineAsm = _module->getModuleInlineAsm();
466   const std::string glbl = ".globl";
467   std::string asmSymbolName;
468   std::string::size_type pos = inlineAsm.find(glbl, 0);
469   while (pos != std::string::npos) {
470     // eat .globl
471     pos = pos + 6;
472
473     // skip white space between .globl and symbol name
474     std::string::size_type pbegin = inlineAsm.find_first_not_of(' ', pos);
475     if (pbegin == std::string::npos)
476       break;
477
478     // find end-of-line
479     std::string::size_type pend = inlineAsm.find_first_of('\n', pbegin);
480     if (pend == std::string::npos)
481       break;
482
483     asmSymbolName.assign(inlineAsm, pbegin, pend - pbegin);
484     addAsmGlobalSymbol(asmSymbolName.c_str());
485
486     // search next .globl
487     pos = inlineAsm.find(glbl, pend);
488   }
489
490   // add aliases
491   for (Module::alias_iterator i = _module->alias_begin(),
492          e = _module->alias_end(); i != e; ++i) {
493     if (i->isDeclaration())
494       addPotentialUndefinedSymbol(i, mangler);
495     else
496       addDefinedDataSymbol(i, mangler);
497   }
498
499   // make symbols for all undefines
500   for (StringMap<NameAndAttributes>::iterator it=_undefines.begin();
501        it != _undefines.end(); ++it) {
502     // if this symbol also has a definition, then don't make an undefine
503     // because it is a tentative definition
504     if (_defines.count(it->getKey()) == 0) {
505       NameAndAttributes info = it->getValue();
506       _symbols.push_back(info);
507     }
508   }
509 }
510
511
512 uint32_t LTOModule::getSymbolCount() {
513   lazyParseSymbols();
514   return _symbols.size();
515 }
516
517
518 lto_symbol_attributes LTOModule::getSymbolAttributes(uint32_t index) {
519   lazyParseSymbols();
520   if (index < _symbols.size())
521     return _symbols[index].attributes;
522   else
523     return lto_symbol_attributes(0);
524 }
525
526 const char *LTOModule::getSymbolName(uint32_t index) {
527   lazyParseSymbols();
528   if (index < _symbols.size())
529     return _symbols[index].name;
530   else
531     return NULL;
532 }