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/TargetRegistry.h"
31 #include "llvm/Support/TargetSelect.h"
32 #include "llvm/Support/system_error.h"
33 #include "llvm/MC/MCAsmInfo.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/MCSubtargetInfo.h"
39 #include "llvm/MC/MCSymbol.h"
40 #include "llvm/MC/SubtargetFeature.h"
41 #include "llvm/MC/MCTargetAsmParser.h"
42 #include "llvm/Target/TargetMachine.h"
43 #include "llvm/Target/TargetRegisterInfo.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);
64 bool LTOModule::isBitcodeFileForTarget(const char *path,
65 const char *triplePrefix) {
66 OwningPtr<MemoryBuffer> buffer;
67 if (MemoryBuffer::getFile(path, buffer))
69 return isTargetMatch(buffer.take(), triplePrefix);
72 // Takes ownership of buffer.
73 bool LTOModule::isTargetMatch(MemoryBuffer *buffer, const char *triplePrefix) {
74 std::string Triple = getBitcodeTargetTriple(buffer, getGlobalContext());
76 return strncmp(Triple.c_str(), triplePrefix, strlen(triplePrefix)) == 0;
80 LTOModule::LTOModule(Module *m, TargetMachine *t)
81 : _module(m), _target(t),
82 _context(*_target->getMCAsmInfo(), *_target->getRegisterInfo(), NULL),
83 _mangler(_context, *_target->getTargetData())
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,
98 size_t size, std::string &errMsg) {
99 return makeLTOModule(fd, path, size, size, 0, errMsg);
102 LTOModule *LTOModule::makeLTOModule(int fd, const char *path,
106 std::string &errMsg) {
107 OwningPtr<MemoryBuffer> buffer;
108 if (error_code ec = MemoryBuffer::getOpenFile(fd, path, buffer, file_size,
109 map_size, offset, false)) {
110 errMsg = ec.message();
113 return makeLTOModule(buffer.take(), errMsg);
116 /// makeBuffer - Create a MemoryBuffer from a memory range.
117 MemoryBuffer *LTOModule::makeBuffer(const void *mem, size_t length) {
118 const char *startPtr = (char*)mem;
119 return MemoryBuffer::getMemBuffer(StringRef(startPtr, length), "", false);
122 LTOModule *LTOModule::makeLTOModule(const void *mem, size_t length,
123 std::string &errMsg) {
124 OwningPtr<MemoryBuffer> buffer(makeBuffer(mem, length));
127 return makeLTOModule(buffer.take(), errMsg);
130 LTOModule *LTOModule::makeLTOModule(MemoryBuffer *buffer,
131 std::string &errMsg) {
132 static bool Initialized = false;
134 InitializeAllTargets();
135 InitializeAllTargetMCs();
136 InitializeAllAsmParsers();
140 // parse bitcode buffer
141 OwningPtr<Module> m(getLazyBitcodeModule(buffer, getGlobalContext(),
148 std::string Triple = m->getTargetTriple();
150 Triple = sys::getDefaultTargetTriple();
152 // find machine architecture for this module
153 const Target *march = TargetRegistry::lookupTarget(Triple, errMsg);
157 // construct LTOModule, hand over ownership of module and target
158 SubtargetFeatures Features;
159 Features.getDefaultSubtargetFeatures(llvm::Triple(Triple));
160 std::string FeatureStr = Features.getString();
162 TargetOptions Options;
163 TargetMachine *target = march->createTargetMachine(Triple, CPU, FeatureStr,
165 LTOModule *Ret = new LTOModule(m.take(), target);
166 if (Ret->ParseSymbols(errMsg)) {
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) {
183 // add to list of defined symbols
184 addDefinedSymbol(f, 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 (ConstantDataArray *ca = dyn_cast<ConstantDataArray>(cn)) {
194 if (ca->isCString()) {
195 name = ".objc_class_name_" + ca->getAsCString().str();
204 // Parse i386/ppc ObjC class data structure.
205 void LTOModule::addObjCClass(GlobalVariable *clgv) {
206 ConstantStruct *c = dyn_cast<ConstantStruct>(clgv->getInitializer());
209 // second slot in __OBJC,__class is pointer to superclass name
210 std::string superclassName;
211 if (objcClassNameFromExpression(c->getOperand(1), superclassName)) {
212 NameAndAttributes info;
213 StringMap<NameAndAttributes>::value_type &entry =
214 _undefines.GetOrCreateValue(superclassName);
215 if (!entry.getValue().name) {
216 const char *symbolName = entry.getKey().data();
217 info.name = symbolName;
218 info.attributes = LTO_SYMBOL_DEFINITION_UNDEFINED;
219 entry.setValue(info);
223 // third slot in __OBJC,__class is pointer to class name
224 std::string className;
225 if (objcClassNameFromExpression(c->getOperand(2), className)) {
226 StringSet::value_type &entry = _defines.GetOrCreateValue(className);
228 NameAndAttributes info;
229 info.name = entry.getKey().data();
230 info.attributes = lto_symbol_attributes(LTO_SYMBOL_PERMISSIONS_DATA |
231 LTO_SYMBOL_DEFINITION_REGULAR |
232 LTO_SYMBOL_SCOPE_DEFAULT);
233 _symbols.push_back(info);
238 // Parse i386/ppc ObjC category data structure.
239 void LTOModule::addObjCCategory(GlobalVariable *clgv) {
240 ConstantStruct *c = dyn_cast<ConstantStruct>(clgv->getInitializer());
243 // second slot in __OBJC,__category is pointer to target class name
244 std::string targetclassName;
245 if (!objcClassNameFromExpression(c->getOperand(1), targetclassName))
248 NameAndAttributes info;
249 StringMap<NameAndAttributes>::value_type &entry =
250 _undefines.GetOrCreateValue(targetclassName);
252 if (entry.getValue().name)
255 const char *symbolName = entry.getKey().data();
256 info.name = symbolName;
257 info.attributes = LTO_SYMBOL_DEFINITION_UNDEFINED;
258 entry.setValue(info);
262 // Parse i386/ppc ObjC class list data structure.
263 void LTOModule::addObjCClassRef(GlobalVariable *clgv) {
264 std::string targetclassName;
265 if (!objcClassNameFromExpression(clgv->getInitializer(), targetclassName))
268 NameAndAttributes info;
269 StringMap<NameAndAttributes>::value_type &entry =
270 _undefines.GetOrCreateValue(targetclassName);
271 if (entry.getValue().name)
274 const char *symbolName = entry.getKey().data();
275 info.name = symbolName;
276 info.attributes = LTO_SYMBOL_DEFINITION_UNDEFINED;
277 entry.setValue(info);
281 void LTOModule::addDefinedDataSymbol(GlobalValue *v) {
282 // Add to list of defined symbols.
283 addDefinedSymbol(v, false);
285 // Special case i386/ppc ObjC data structures in magic sections:
286 // The issue is that the old ObjC object format did some strange
287 // contortions to avoid real linker symbols. For instance, the
288 // ObjC class data structure is allocated statically in the executable
289 // that defines that class. That data structures contains a pointer to
290 // its superclass. But instead of just initializing that part of the
291 // struct to the address of its superclass, and letting the static and
292 // dynamic linkers do the rest, the runtime works by having that field
293 // instead point to a C-string that is the name of the superclass.
294 // At runtime the objc initialization updates that pointer and sets
295 // it to point to the actual super class. As far as the linker
296 // knows it is just a pointer to a string. But then someone wanted the
297 // linker to issue errors at build time if the superclass was not found.
298 // So they figured out a way in mach-o object format to use an absolute
299 // symbols (.objc_class_name_Foo = 0) and a floating reference
300 // (.reference .objc_class_name_Bar) to cause the linker into erroring when
301 // a class was missing.
302 // The following synthesizes the implicit .objc_* symbols for the linker
303 // from the ObjC data structures generated by the front end.
304 if (v->hasSection() /* && isTargetDarwin */) {
305 // special case if this data blob is an ObjC class definition
306 if (v->getSection().compare(0, 15, "__OBJC,__class,") == 0) {
307 if (GlobalVariable *gv = dyn_cast<GlobalVariable>(v)) {
312 // special case if this data blob is an ObjC category definition
313 else if (v->getSection().compare(0, 18, "__OBJC,__category,") == 0) {
314 if (GlobalVariable *gv = dyn_cast<GlobalVariable>(v)) {
319 // special case if this data blob is the list of referenced classes
320 else if (v->getSection().compare(0, 18, "__OBJC,__cls_refs,") == 0) {
321 if (GlobalVariable *gv = dyn_cast<GlobalVariable>(v)) {
328 void LTOModule::addDefinedSymbol(GlobalValue *def, bool isFunction) {
329 // ignore all llvm.* symbols
330 if (def->getName().startswith("llvm."))
333 // string is owned by _defines
334 SmallString<64> Buffer;
335 _mangler.getNameWithPrefix(Buffer, def, false);
337 // set alignment part log2() can have rounding errors
338 uint32_t align = def->getAlignment();
339 uint32_t attr = align ? CountTrailingZeros_32(def->getAlignment()) : 0;
341 // set permissions part
343 attr |= LTO_SYMBOL_PERMISSIONS_CODE;
345 GlobalVariable *gv = dyn_cast<GlobalVariable>(def);
346 if (gv && gv->isConstant())
347 attr |= LTO_SYMBOL_PERMISSIONS_RODATA;
349 attr |= LTO_SYMBOL_PERMISSIONS_DATA;
352 // set definition part
353 if (def->hasWeakLinkage() || def->hasLinkOnceLinkage() ||
354 def->hasLinkerPrivateWeakLinkage() ||
355 def->hasLinkerPrivateWeakDefAutoLinkage())
356 attr |= LTO_SYMBOL_DEFINITION_WEAK;
357 else if (def->hasCommonLinkage())
358 attr |= LTO_SYMBOL_DEFINITION_TENTATIVE;
360 attr |= LTO_SYMBOL_DEFINITION_REGULAR;
363 if (def->hasHiddenVisibility())
364 attr |= LTO_SYMBOL_SCOPE_HIDDEN;
365 else if (def->hasProtectedVisibility())
366 attr |= LTO_SYMBOL_SCOPE_PROTECTED;
367 else if (def->hasExternalLinkage() || def->hasWeakLinkage() ||
368 def->hasLinkOnceLinkage() || def->hasCommonLinkage() ||
369 def->hasLinkerPrivateWeakLinkage())
370 attr |= LTO_SYMBOL_SCOPE_DEFAULT;
371 else if (def->hasLinkerPrivateWeakDefAutoLinkage())
372 attr |= LTO_SYMBOL_SCOPE_DEFAULT_CAN_BE_HIDDEN;
374 attr |= LTO_SYMBOL_SCOPE_INTERNAL;
376 // add to table of symbols
377 NameAndAttributes info;
378 StringSet::value_type &entry = _defines.GetOrCreateValue(Buffer);
381 StringRef Name = entry.getKey();
382 info.name = Name.data();
383 assert(info.name[Name.size()] == '\0');
384 info.attributes = (lto_symbol_attributes)attr;
385 _symbols.push_back(info);
388 void LTOModule::addAsmGlobalSymbol(const char *name,
389 lto_symbol_attributes scope) {
390 StringSet::value_type &entry = _defines.GetOrCreateValue(name);
392 // only add new define if not already defined
393 if (entry.getValue())
397 const char *symbolName = entry.getKey().data();
398 uint32_t attr = LTO_SYMBOL_DEFINITION_REGULAR;
400 NameAndAttributes info;
401 info.name = symbolName;
402 info.attributes = (lto_symbol_attributes)attr;
403 _symbols.push_back(info);
406 void LTOModule::addAsmGlobalSymbolUndef(const char *name) {
407 StringMap<NameAndAttributes>::value_type &entry =
408 _undefines.GetOrCreateValue(name);
410 _asm_undefines.push_back(entry.getKey().data());
412 // we already have the symbol
413 if (entry.getValue().name)
416 uint32_t attr = LTO_SYMBOL_DEFINITION_UNDEFINED;;
417 attr |= LTO_SYMBOL_SCOPE_DEFAULT;
418 NameAndAttributes info;
419 info.name = entry.getKey().data();
420 info.attributes = (lto_symbol_attributes)attr;
422 entry.setValue(info);
425 void LTOModule::addPotentialUndefinedSymbol(GlobalValue *decl) {
426 // ignore all llvm.* symbols
427 if (decl->getName().startswith("llvm."))
430 // ignore all aliases
431 if (isa<GlobalAlias>(decl))
434 SmallString<64> name;
435 _mangler.getNameWithPrefix(name, decl, false);
437 StringMap<NameAndAttributes>::value_type &entry =
438 _undefines.GetOrCreateValue(name);
440 // we already have the symbol
441 if (entry.getValue().name)
444 NameAndAttributes info;
446 info.name = entry.getKey().data();
447 if (decl->hasExternalWeakLinkage())
448 info.attributes = LTO_SYMBOL_DEFINITION_WEAKUNDEF;
450 info.attributes = LTO_SYMBOL_DEFINITION_UNDEFINED;
452 entry.setValue(info);
456 class RecordStreamer : public MCStreamer {
458 enum State { NeverSeen, Global, Defined, DefinedGlobal, Used};
461 StringMap<State> Symbols;
463 void markDefined(const MCSymbol &Symbol) {
464 State &S = Symbols[Symbol.getName()];
477 void markGlobal(const MCSymbol &Symbol) {
478 State &S = Symbols[Symbol.getName()];
492 void markUsed(const MCSymbol &Symbol) {
493 State &S = Symbols[Symbol.getName()];
507 // FIXME: mostly copied for the obj streamer.
508 void AddValueSymbols(const MCExpr *Value) {
509 switch (Value->getKind()) {
511 // FIXME: What should we do in here?
514 case MCExpr::Constant:
517 case MCExpr::Binary: {
518 const MCBinaryExpr *BE = cast<MCBinaryExpr>(Value);
519 AddValueSymbols(BE->getLHS());
520 AddValueSymbols(BE->getRHS());
524 case MCExpr::SymbolRef:
525 markUsed(cast<MCSymbolRefExpr>(Value)->getSymbol());
529 AddValueSymbols(cast<MCUnaryExpr>(Value)->getSubExpr());
535 typedef StringMap<State>::const_iterator const_iterator;
537 const_iterator begin() {
538 return Symbols.begin();
541 const_iterator end() {
542 return Symbols.end();
545 RecordStreamer(MCContext &Context) : MCStreamer(Context) {}
547 virtual void ChangeSection(const MCSection *Section) {}
548 virtual void InitSections() {}
549 virtual void EmitLabel(MCSymbol *Symbol) {
550 Symbol->setSection(*getCurrentSection());
551 markDefined(*Symbol);
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);
559 virtual void EmitSymbolAttribute(MCSymbol *Symbol, MCSymbolAttr Attribute) {
560 if (Attribute == MCSA_Global)
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);
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);
577 virtual void EmitELFSize(MCSymbol *Symbol, const MCExpr *Value) {}
578 virtual void EmitLocalCommonSymbol(MCSymbol *Symbol, uint64_t Size,
579 unsigned ByteAlignment) {}
580 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,
584 unsigned AddrSpace) {}
585 virtual void EmitULEB128Value(const MCExpr *Value) {}
586 virtual void EmitSLEB128Value(const MCExpr *Value) {}
587 virtual void EmitValueToAlignment(unsigned ByteAlignment, int64_t Value,
589 unsigned MaxBytesToEmit) {}
590 virtual void EmitCodeAlignment(unsigned ByteAlignment,
591 unsigned MaxBytesToEmit) {}
592 virtual bool EmitValueToOffset(const MCExpr *Offset,
593 unsigned char Value ) { return false; }
594 virtual void EmitFileDirective(StringRef Filename) {}
595 virtual void EmitDwarfAdvanceLineAddr(int64_t LineDelta,
596 const MCSymbol *LastLabel,
597 const MCSymbol *Label,
598 unsigned PointerSize) {}
600 virtual void EmitInstruction(const MCInst &Inst) {
602 for (unsigned i = Inst.getNumOperands(); i--; )
603 if (Inst.getOperand(i).isExpr())
604 AddValueSymbols(Inst.getOperand(i).getExpr());
606 virtual void FinishImpl() {}
610 bool LTOModule::addAsmGlobalSymbols(std::string &errMsg) {
611 const std::string &inlineAsm = _module->getModuleInlineAsm();
612 if (inlineAsm.empty())
615 OwningPtr<RecordStreamer> Streamer(new RecordStreamer(_context));
616 MemoryBuffer *Buffer = MemoryBuffer::getMemBuffer(inlineAsm);
618 SrcMgr.AddNewSourceBuffer(Buffer, SMLoc());
619 OwningPtr<MCAsmParser> Parser(createMCAsmParser(SrcMgr,
621 *_target->getMCAsmInfo()));
622 OwningPtr<MCSubtargetInfo> STI(_target->getTarget().
623 createMCSubtargetInfo(_target->getTargetTriple(),
624 _target->getTargetCPU(),
625 _target->getTargetFeatureString()));
626 OwningPtr<MCTargetAsmParser>
627 TAP(_target->getTarget().createMCAsmParser(*STI, *Parser.get()));
629 errMsg = "target " + std::string(_target->getTarget().getName()) +
630 " does not define AsmParser.";
634 Parser->setTargetParser(*TAP);
635 int Res = Parser->Run(false);
639 for (RecordStreamer::const_iterator i = Streamer->begin(),
640 e = Streamer->end(); i != e; ++i) {
641 StringRef Key = i->first();
642 RecordStreamer::State Value = i->second;
643 if (Value == RecordStreamer::DefinedGlobal)
644 addAsmGlobalSymbol(Key.data(), LTO_SYMBOL_SCOPE_DEFAULT);
645 else if (Value == RecordStreamer::Defined)
646 addAsmGlobalSymbol(Key.data(), LTO_SYMBOL_SCOPE_INTERNAL);
647 else if (Value == RecordStreamer::Global ||
648 Value == RecordStreamer::Used)
649 addAsmGlobalSymbolUndef(Key.data());
654 static bool isDeclaration(const GlobalValue &V) {
655 if (V.hasAvailableExternallyLinkage())
657 if (V.isMaterializable())
659 return V.isDeclaration();
662 static bool isAliasToDeclaration(const GlobalAlias &V) {
663 return isDeclaration(*V.getAliasedGlobal());
666 bool LTOModule::ParseSymbols(std::string &errMsg) {
668 for (Module::iterator f = _module->begin(); f != _module->end(); ++f) {
669 if (isDeclaration(*f))
670 addPotentialUndefinedSymbol(f);
672 addDefinedFunctionSymbol(f);
676 for (Module::global_iterator v = _module->global_begin(),
677 e = _module->global_end(); v != e; ++v) {
678 if (isDeclaration(*v))
679 addPotentialUndefinedSymbol(v);
681 addDefinedDataSymbol(v);
685 if (addAsmGlobalSymbols(errMsg))
689 for (Module::alias_iterator i = _module->alias_begin(),
690 e = _module->alias_end(); i != e; ++i) {
691 if (isAliasToDeclaration(*i))
692 addPotentialUndefinedSymbol(i);
694 addDefinedDataSymbol(i);
697 // make symbols for all undefines
698 for (StringMap<NameAndAttributes>::iterator it=_undefines.begin();
699 it != _undefines.end(); ++it) {
700 // if this symbol also has a definition, then don't make an undefine
701 // because it is a tentative definition
702 if (_defines.count(it->getKey()) == 0) {
703 NameAndAttributes info = it->getValue();
704 _symbols.push_back(info);
710 uint32_t LTOModule::getSymbolCount() {
711 return _symbols.size();
714 lto_symbol_attributes LTOModule::getSymbolAttributes(uint32_t index) {
715 if (index < _symbols.size())
716 return _symbols[index].attributes;
718 return lto_symbol_attributes(0);
721 const char *LTOModule::getSymbolName(uint32_t index) {
722 if (index < _symbols.size())
723 return _symbols[index].name;