1 //===-- LTOModule.cpp - LLVM Link Time Optimizer --------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
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.
13 //===----------------------------------------------------------------------===//
15 #include "LTOModule.h"
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/SourceMgr.h"
30 #include "llvm/Support/system_error.h"
31 #include "llvm/Target/Mangler.h"
32 #include "llvm/MC/MCAsmInfo.h"
33 #include "llvm/MC/MCContext.h"
34 #include "llvm/MC/MCExpr.h"
35 #include "llvm/MC/MCInst.h"
36 #include "llvm/MC/MCParser/MCAsmParser.h"
37 #include "llvm/MC/MCStreamer.h"
38 #include "llvm/MC/MCSymbol.h"
39 #include "llvm/MC/SubtargetFeature.h"
40 #include "llvm/Target/TargetAsmParser.h"
41 #include "llvm/Target/TargetMachine.h"
42 #include "llvm/Target/TargetRegistry.h"
43 #include "llvm/Target/TargetSelect.h"
47 bool LTOModule::isBitcodeFile(const void *mem, size_t length) {
48 return llvm::sys::IdentifyFileType((char*)mem, length)
49 == llvm::sys::Bitcode_FileType;
52 bool LTOModule::isBitcodeFile(const char *path) {
53 return llvm::sys::Path(path).isBitcodeFile();
56 bool LTOModule::isBitcodeFileForTarget(const void *mem, size_t length,
57 const char *triplePrefix) {
58 MemoryBuffer *buffer = makeBuffer(mem, length);
61 return isTargetMatch(buffer, triplePrefix);
65 bool LTOModule::isBitcodeFileForTarget(const char *path,
66 const char *triplePrefix) {
67 OwningPtr<MemoryBuffer> buffer;
68 if (MemoryBuffer::getFile(path, buffer))
70 return isTargetMatch(buffer.take(), triplePrefix);
73 // Takes ownership of buffer.
74 bool LTOModule::isTargetMatch(MemoryBuffer *buffer, const char *triplePrefix) {
75 std::string Triple = getBitcodeTargetTriple(buffer, getGlobalContext());
77 return (strncmp(Triple.c_str(), triplePrefix,
78 strlen(triplePrefix)) == 0);
82 LTOModule::LTOModule(Module *m, TargetMachine *t)
83 : _module(m), _target(t)
87 LTOModule *LTOModule::makeLTOModule(const char *path,
88 std::string &errMsg) {
89 OwningPtr<MemoryBuffer> buffer;
90 if (error_code ec = MemoryBuffer::getFile(path, buffer)) {
91 errMsg = ec.message();
94 return makeLTOModule(buffer.take(), errMsg);
97 LTOModule *LTOModule::makeLTOModule(int fd, const char *path,
99 std::string &errMsg) {
100 return makeLTOModule(fd, path, size, size, 0, errMsg);
103 LTOModule *LTOModule::makeLTOModule(int fd, const char *path,
107 std::string &errMsg) {
108 OwningPtr<MemoryBuffer> buffer;
109 if (error_code ec = MemoryBuffer::getOpenFile(fd, path, buffer, file_size,
110 map_size, offset, false)) {
111 errMsg = ec.message();
114 return makeLTOModule(buffer.take(), errMsg);
117 /// makeBuffer - Create a MemoryBuffer from a memory range.
118 MemoryBuffer *LTOModule::makeBuffer(const void *mem, size_t length) {
119 const char *startPtr = (char*)mem;
120 return MemoryBuffer::getMemBuffer(StringRef(startPtr, length), "", false);
124 LTOModule *LTOModule::makeLTOModule(const void *mem, size_t length,
125 std::string &errMsg) {
126 OwningPtr<MemoryBuffer> buffer(makeBuffer(mem, length));
129 return makeLTOModule(buffer.take(), errMsg);
132 LTOModule *LTOModule::makeLTOModule(MemoryBuffer *buffer,
133 std::string &errMsg) {
134 static bool Initialized = false;
136 InitializeAllTargets();
137 InitializeAllAsmParsers();
141 // parse bitcode buffer
142 OwningPtr<Module> m(getLazyBitcodeModule(buffer, getGlobalContext(),
149 std::string Triple = m->getTargetTriple();
151 Triple = sys::getHostTriple();
153 // find machine architecture for this module
154 const Target *march = TargetRegistry::lookupTarget(Triple, errMsg);
158 // construct LTOModule, hand over ownership of module and target
159 SubtargetFeatures Features;
160 Features.getDefaultSubtargetFeatures(llvm::Triple(Triple));
161 std::string FeatureStr = Features.getString();
163 TargetMachine *target = march->createTargetMachine(Triple, CPU, FeatureStr);
164 LTOModule *Ret = new LTOModule(m.take(), target);
165 bool Err = Ret->ParseSymbols();
174 const char *LTOModule::getTargetTriple() {
175 return _module->getTargetTriple().c_str();
178 void LTOModule::setTargetTriple(const char *triple) {
179 _module->setTargetTriple(triple);
182 void LTOModule::addDefinedFunctionSymbol(Function *f, Mangler &mangler) {
183 // add to list of defined symbols
184 addDefinedSymbol(f, mangler, true);
187 // Get string that data pointer points to.
188 bool LTOModule::objcClassNameFromExpression(Constant *c, std::string &name) {
189 if (ConstantExpr *ce = dyn_cast<ConstantExpr>(c)) {
190 Constant *op = ce->getOperand(0);
191 if (GlobalVariable *gvn = dyn_cast<GlobalVariable>(op)) {
192 Constant *cn = gvn->getInitializer();
193 if (ConstantArray *ca = dyn_cast<ConstantArray>(cn)) {
194 if (ca->isCString()) {
195 name = ".objc_class_name_" + ca->getAsCString();
204 // Parse i386/ppc ObjC class data structure.
205 void LTOModule::addObjCClass(GlobalVariable *clgv) {
206 if (ConstantStruct *c = dyn_cast<ConstantStruct>(clgv->getInitializer())) {
207 // second slot in __OBJC,__class is pointer to superclass name
208 std::string superclassName;
209 if (objcClassNameFromExpression(c->getOperand(1), superclassName)) {
210 NameAndAttributes info;
211 StringMap<NameAndAttributes>::value_type &entry =
212 _undefines.GetOrCreateValue(superclassName);
213 if (!entry.getValue().name) {
214 const char *symbolName = entry.getKey().data();
215 info.name = symbolName;
216 info.attributes = LTO_SYMBOL_DEFINITION_UNDEFINED;
217 entry.setValue(info);
220 // third slot in __OBJC,__class is pointer to class name
221 std::string className;
222 if (objcClassNameFromExpression(c->getOperand(2), className)) {
223 StringSet::value_type &entry =
224 _defines.GetOrCreateValue(className);
226 NameAndAttributes info;
227 info.name = entry.getKey().data();
228 info.attributes = (lto_symbol_attributes)
229 (LTO_SYMBOL_PERMISSIONS_DATA |
230 LTO_SYMBOL_DEFINITION_REGULAR |
231 LTO_SYMBOL_SCOPE_DEFAULT);
232 _symbols.push_back(info);
238 // Parse i386/ppc ObjC category data structure.
239 void LTOModule::addObjCCategory(GlobalVariable *clgv) {
240 if (ConstantStruct *c = dyn_cast<ConstantStruct>(clgv->getInitializer())) {
241 // second slot in __OBJC,__category is pointer to target class name
242 std::string targetclassName;
243 if (objcClassNameFromExpression(c->getOperand(1), targetclassName)) {
244 NameAndAttributes info;
246 StringMap<NameAndAttributes>::value_type &entry =
247 _undefines.GetOrCreateValue(targetclassName);
249 if (entry.getValue().name)
252 const char *symbolName = entry.getKey().data();
253 info.name = symbolName;
254 info.attributes = LTO_SYMBOL_DEFINITION_UNDEFINED;
255 entry.setValue(info);
261 // Parse i386/ppc ObjC class list data structure.
262 void LTOModule::addObjCClassRef(GlobalVariable *clgv) {
263 std::string targetclassName;
264 if (objcClassNameFromExpression(clgv->getInitializer(), targetclassName)) {
265 NameAndAttributes info;
267 StringMap<NameAndAttributes>::value_type &entry =
268 _undefines.GetOrCreateValue(targetclassName);
269 if (entry.getValue().name)
272 const char *symbolName = entry.getKey().data();
273 info.name = symbolName;
274 info.attributes = LTO_SYMBOL_DEFINITION_UNDEFINED;
275 entry.setValue(info);
280 void LTOModule::addDefinedDataSymbol(GlobalValue *v, Mangler &mangler) {
281 // Add to list of defined symbols.
282 addDefinedSymbol(v, mangler, false);
284 // Special case i386/ppc ObjC data structures in magic sections:
285 // The issue is that the old ObjC object format did some strange
286 // contortions to avoid real linker symbols. For instance, the
287 // ObjC class data structure is allocated statically in the executable
288 // that defines that class. That data structures contains a pointer to
289 // its superclass. But instead of just initializing that part of the
290 // struct to the address of its superclass, and letting the static and
291 // dynamic linkers do the rest, the runtime works by having that field
292 // instead point to a C-string that is the name of the superclass.
293 // At runtime the objc initialization updates that pointer and sets
294 // it to point to the actual super class. As far as the linker
295 // knows it is just a pointer to a string. But then someone wanted the
296 // linker to issue errors at build time if the superclass was not found.
297 // So they figured out a way in mach-o object format to use an absolute
298 // symbols (.objc_class_name_Foo = 0) and a floating reference
299 // (.reference .objc_class_name_Bar) to cause the linker into erroring when
300 // a class was missing.
301 // The following synthesizes the implicit .objc_* symbols for the linker
302 // from the ObjC data structures generated by the front end.
303 if (v->hasSection() /* && isTargetDarwin */) {
304 // special case if this data blob is an ObjC class definition
305 if (v->getSection().compare(0, 15, "__OBJC,__class,") == 0) {
306 if (GlobalVariable *gv = dyn_cast<GlobalVariable>(v)) {
311 // special case if this data blob is an ObjC category definition
312 else if (v->getSection().compare(0, 18, "__OBJC,__category,") == 0) {
313 if (GlobalVariable *gv = dyn_cast<GlobalVariable>(v)) {
318 // special case if this data blob is the list of referenced classes
319 else if (v->getSection().compare(0, 18, "__OBJC,__cls_refs,") == 0) {
320 if (GlobalVariable *gv = dyn_cast<GlobalVariable>(v)) {
328 void LTOModule::addDefinedSymbol(GlobalValue *def, Mangler &mangler,
330 // ignore all llvm.* symbols
331 if (def->getName().startswith("llvm."))
334 // string is owned by _defines
335 SmallString<64> Buffer;
336 mangler.getNameWithPrefix(Buffer, def, false);
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;
342 // set permissions part
344 attr |= LTO_SYMBOL_PERMISSIONS_CODE;
346 GlobalVariable *gv = dyn_cast<GlobalVariable>(def);
347 if (gv && gv->isConstant())
348 attr |= LTO_SYMBOL_PERMISSIONS_RODATA;
350 attr |= LTO_SYMBOL_PERMISSIONS_DATA;
353 // set definition part
354 if (def->hasWeakLinkage() || def->hasLinkOnceLinkage() ||
355 def->hasLinkerPrivateWeakLinkage() ||
356 def->hasLinkerPrivateWeakDefAutoLinkage())
357 attr |= LTO_SYMBOL_DEFINITION_WEAK;
358 else if (def->hasCommonLinkage())
359 attr |= LTO_SYMBOL_DEFINITION_TENTATIVE;
361 attr |= LTO_SYMBOL_DEFINITION_REGULAR;
364 if (def->hasHiddenVisibility())
365 attr |= LTO_SYMBOL_SCOPE_HIDDEN;
366 else if (def->hasProtectedVisibility())
367 attr |= LTO_SYMBOL_SCOPE_PROTECTED;
368 else if (def->hasExternalLinkage() || def->hasWeakLinkage() ||
369 def->hasLinkOnceLinkage() || def->hasCommonLinkage() ||
370 def->hasLinkerPrivateWeakLinkage())
371 attr |= LTO_SYMBOL_SCOPE_DEFAULT;
372 else if (def->hasLinkerPrivateWeakDefAutoLinkage())
373 attr |= LTO_SYMBOL_SCOPE_DEFAULT_CAN_BE_HIDDEN;
375 attr |= LTO_SYMBOL_SCOPE_INTERNAL;
377 // add to table of symbols
378 NameAndAttributes info;
379 StringSet::value_type &entry = _defines.GetOrCreateValue(Buffer);
382 StringRef Name = entry.getKey();
383 info.name = Name.data();
384 assert(info.name[Name.size()] == '\0');
385 info.attributes = (lto_symbol_attributes)attr;
386 _symbols.push_back(info);
389 void LTOModule::addAsmGlobalSymbol(const char *name,
390 lto_symbol_attributes scope) {
391 StringSet::value_type &entry = _defines.GetOrCreateValue(name);
393 // only add new define if not already defined
394 if (entry.getValue())
398 const char *symbolName = entry.getKey().data();
399 uint32_t attr = LTO_SYMBOL_DEFINITION_REGULAR;
401 NameAndAttributes info;
402 info.name = symbolName;
403 info.attributes = (lto_symbol_attributes)attr;
404 _symbols.push_back(info);
407 void LTOModule::addAsmGlobalSymbolUndef(const char *name) {
408 StringMap<NameAndAttributes>::value_type &entry =
409 _undefines.GetOrCreateValue(name);
411 _asm_undefines.push_back(entry.getKey().data());
413 // we already have the symbol
414 if (entry.getValue().name)
417 uint32_t attr = LTO_SYMBOL_DEFINITION_UNDEFINED;;
418 attr |= LTO_SYMBOL_SCOPE_DEFAULT;
419 NameAndAttributes info;
420 info.name = entry.getKey().data();
421 info.attributes = (lto_symbol_attributes)attr;
423 entry.setValue(info);
426 void LTOModule::addPotentialUndefinedSymbol(GlobalValue *decl,
428 // ignore all llvm.* symbols
429 if (decl->getName().startswith("llvm."))
432 // ignore all aliases
433 if (isa<GlobalAlias>(decl))
436 SmallString<64> name;
437 mangler.getNameWithPrefix(name, decl, false);
439 StringMap<NameAndAttributes>::value_type &entry =
440 _undefines.GetOrCreateValue(name);
442 // we already have the symbol
443 if (entry.getValue().name)
446 NameAndAttributes info;
448 info.name = entry.getKey().data();
449 if (decl->hasExternalWeakLinkage())
450 info.attributes = LTO_SYMBOL_DEFINITION_WEAKUNDEF;
452 info.attributes = LTO_SYMBOL_DEFINITION_UNDEFINED;
454 entry.setValue(info);
459 class RecordStreamer : public MCStreamer {
461 enum State { NeverSeen, Global, Defined, DefinedGlobal, Used};
464 StringMap<State> Symbols;
466 void markDefined(const MCSymbol &Symbol) {
467 State &S = Symbols[Symbol.getName()];
480 void markGlobal(const MCSymbol &Symbol) {
481 State &S = Symbols[Symbol.getName()];
495 void markUsed(const MCSymbol &Symbol) {
496 State &S = Symbols[Symbol.getName()];
510 // FIXME: mostly copied for the obj streamer.
511 void AddValueSymbols(const MCExpr *Value) {
512 switch (Value->getKind()) {
514 // FIXME: What should we do in here?
517 case MCExpr::Constant:
520 case MCExpr::Binary: {
521 const MCBinaryExpr *BE = cast<MCBinaryExpr>(Value);
522 AddValueSymbols(BE->getLHS());
523 AddValueSymbols(BE->getRHS());
527 case MCExpr::SymbolRef:
528 markUsed(cast<MCSymbolRefExpr>(Value)->getSymbol());
532 AddValueSymbols(cast<MCUnaryExpr>(Value)->getSubExpr());
538 typedef StringMap<State>::const_iterator const_iterator;
540 const_iterator begin() {
541 return Symbols.begin();
544 const_iterator end() {
545 return Symbols.end();
548 RecordStreamer(MCContext &Context) : MCStreamer(Context) {}
550 virtual void ChangeSection(const MCSection *Section) {}
551 virtual void InitSections() {}
552 virtual void EmitLabel(MCSymbol *Symbol) {
553 Symbol->setSection(*getCurrentSection());
554 markDefined(*Symbol);
556 virtual void EmitAssemblerFlag(MCAssemblerFlag Flag) {}
557 virtual void EmitThumbFunc(MCSymbol *Func) {}
558 virtual void EmitAssignment(MCSymbol *Symbol, const MCExpr *Value) {
559 // FIXME: should we handle aliases?
560 markDefined(*Symbol);
562 virtual void EmitSymbolAttribute(MCSymbol *Symbol, MCSymbolAttr Attribute) {
563 if (Attribute == MCSA_Global)
566 virtual void EmitSymbolDesc(MCSymbol *Symbol, unsigned DescValue) {}
567 virtual void EmitWeakReference(MCSymbol *Alias, const MCSymbol *Symbol) {}
568 virtual void BeginCOFFSymbolDef(const MCSymbol *Symbol) {}
569 virtual void EmitCOFFSymbolStorageClass(int StorageClass) {}
570 virtual void EmitZerofill(const MCSection *Section, MCSymbol *Symbol,
571 unsigned Size , unsigned ByteAlignment) {
572 markDefined(*Symbol);
574 virtual void EmitCOFFSymbolType(int Type) {}
575 virtual void EndCOFFSymbolDef() {}
576 virtual void EmitCommonSymbol(MCSymbol *Symbol, uint64_t Size,
577 unsigned ByteAlignment) {
578 markDefined(*Symbol);
580 virtual void EmitELFSize(MCSymbol *Symbol, const MCExpr *Value) {}
581 virtual void EmitLocalCommonSymbol(MCSymbol *Symbol, uint64_t Size) {}
582 virtual void EmitTBSSSymbol(const MCSection *Section, MCSymbol *Symbol,
583 uint64_t Size, unsigned ByteAlignment) {}
584 virtual void EmitBytes(StringRef Data, unsigned AddrSpace) {}
585 virtual void EmitValueImpl(const MCExpr *Value, unsigned Size,
586 unsigned AddrSpace) {}
587 virtual void EmitULEB128Value(const MCExpr *Value) {}
588 virtual void EmitSLEB128Value(const MCExpr *Value) {}
589 virtual void EmitValueToAlignment(unsigned ByteAlignment, int64_t Value,
591 unsigned MaxBytesToEmit) {}
592 virtual void EmitCodeAlignment(unsigned ByteAlignment,
593 unsigned MaxBytesToEmit) {}
594 virtual void EmitValueToOffset(const MCExpr *Offset,
595 unsigned char Value ) {}
596 virtual void EmitFileDirective(StringRef Filename) {}
597 virtual void EmitDwarfAdvanceLineAddr(int64_t LineDelta,
598 const MCSymbol *LastLabel,
599 const MCSymbol *Label) {}
601 virtual void EmitInstruction(const MCInst &Inst) {
603 for (unsigned i = Inst.getNumOperands(); i--; )
604 if (Inst.getOperand(i).isExpr())
605 AddValueSymbols(Inst.getOperand(i).getExpr());
607 virtual void Finish() {}
611 bool LTOModule::addAsmGlobalSymbols(MCContext &Context) {
612 const std::string &inlineAsm = _module->getModuleInlineAsm();
614 OwningPtr<RecordStreamer> Streamer(new RecordStreamer(Context));
615 MemoryBuffer *Buffer = MemoryBuffer::getMemBuffer(inlineAsm);
617 SrcMgr.AddNewSourceBuffer(Buffer, SMLoc());
618 OwningPtr<MCAsmParser> Parser(createMCAsmParser(_target->getTarget(), SrcMgr,
620 *_target->getMCAsmInfo()));
621 OwningPtr<TargetAsmParser>
622 TAP(_target->getTarget().createAsmParser(*Parser.get(), *_target.get()));
623 Parser->setTargetParser(*TAP);
624 int Res = Parser->Run(false);
628 for (RecordStreamer::const_iterator i = Streamer->begin(),
629 e = Streamer->end(); i != e; ++i) {
630 StringRef Key = i->first();
631 RecordStreamer::State Value = i->second;
632 if (Value == RecordStreamer::DefinedGlobal)
633 addAsmGlobalSymbol(Key.data(), LTO_SYMBOL_SCOPE_DEFAULT);
634 else if (Value == RecordStreamer::Defined)
635 addAsmGlobalSymbol(Key.data(), LTO_SYMBOL_SCOPE_INTERNAL);
636 else if (Value == RecordStreamer::Global ||
637 Value == RecordStreamer::Used)
638 addAsmGlobalSymbolUndef(Key.data());
643 static bool isDeclaration(const GlobalValue &V) {
644 if (V.hasAvailableExternallyLinkage())
646 if (V.isMaterializable())
648 return V.isDeclaration();
651 static bool isAliasToDeclaration(const GlobalAlias &V) {
652 return isDeclaration(*V.getAliasedGlobal());
655 bool LTOModule::ParseSymbols() {
656 // Use mangler to add GlobalPrefix to names to match linker names.
657 MCContext Context(*_target->getMCAsmInfo(), NULL);
658 Mangler mangler(Context, *_target->getTargetData());
661 for (Module::iterator f = _module->begin(); f != _module->end(); ++f) {
662 if (isDeclaration(*f))
663 addPotentialUndefinedSymbol(f, mangler);
665 addDefinedFunctionSymbol(f, mangler);
669 for (Module::global_iterator v = _module->global_begin(),
670 e = _module->global_end(); v != e; ++v) {
671 if (isDeclaration(*v))
672 addPotentialUndefinedSymbol(v, mangler);
674 addDefinedDataSymbol(v, mangler);
678 if (addAsmGlobalSymbols(Context))
682 for (Module::alias_iterator i = _module->alias_begin(),
683 e = _module->alias_end(); i != e; ++i) {
684 if (isAliasToDeclaration(*i))
685 addPotentialUndefinedSymbol(i, mangler);
687 addDefinedDataSymbol(i, mangler);
690 // make symbols for all undefines
691 for (StringMap<NameAndAttributes>::iterator it=_undefines.begin();
692 it != _undefines.end(); ++it) {
693 // if this symbol also has a definition, then don't make an undefine
694 // because it is a tentative definition
695 if (_defines.count(it->getKey()) == 0) {
696 NameAndAttributes info = it->getValue();
697 _symbols.push_back(info);
704 uint32_t LTOModule::getSymbolCount() {
705 return _symbols.size();
709 lto_symbol_attributes LTOModule::getSymbolAttributes(uint32_t index) {
710 if (index < _symbols.size())
711 return _symbols[index].attributes;
713 return lto_symbol_attributes(0);
716 const char *LTOModule::getSymbolName(uint32_t index) {
717 if (index < _symbols.size())
718 return _symbols[index].name;