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/MCSubtargetInfo.h"
39 #include "llvm/MC/MCSymbol.h"
40 #include "llvm/MC/SubtargetFeature.h"
41 #include "llvm/Target/TargetAsmParser.h"
42 #include "llvm/Target/TargetMachine.h"
43 #include "llvm/Target/TargetRegisterInfo.h"
44 #include "llvm/Target/TargetRegistry.h"
45 #include "llvm/Target/TargetSelect.h"
49 bool LTOModule::isBitcodeFile(const void *mem, size_t length) {
50 return llvm::sys::IdentifyFileType((char*)mem, length)
51 == llvm::sys::Bitcode_FileType;
54 bool LTOModule::isBitcodeFile(const char *path) {
55 return llvm::sys::Path(path).isBitcodeFile();
58 bool LTOModule::isBitcodeFileForTarget(const void *mem, size_t length,
59 const char *triplePrefix) {
60 MemoryBuffer *buffer = makeBuffer(mem, length);
63 return isTargetMatch(buffer, triplePrefix);
67 bool LTOModule::isBitcodeFileForTarget(const char *path,
68 const char *triplePrefix) {
69 OwningPtr<MemoryBuffer> buffer;
70 if (MemoryBuffer::getFile(path, buffer))
72 return isTargetMatch(buffer.take(), triplePrefix);
75 // Takes ownership of buffer.
76 bool LTOModule::isTargetMatch(MemoryBuffer *buffer, const char *triplePrefix) {
77 std::string Triple = getBitcodeTargetTriple(buffer, getGlobalContext());
79 return (strncmp(Triple.c_str(), triplePrefix,
80 strlen(triplePrefix)) == 0);
84 LTOModule::LTOModule(Module *m, TargetMachine *t)
85 : _module(m), _target(t)
89 LTOModule *LTOModule::makeLTOModule(const char *path,
90 std::string &errMsg) {
91 OwningPtr<MemoryBuffer> buffer;
92 if (error_code ec = MemoryBuffer::getFile(path, buffer)) {
93 errMsg = ec.message();
96 return makeLTOModule(buffer.take(), errMsg);
99 LTOModule *LTOModule::makeLTOModule(int fd, const char *path,
101 std::string &errMsg) {
102 return makeLTOModule(fd, path, size, size, 0, errMsg);
105 LTOModule *LTOModule::makeLTOModule(int fd, const char *path,
109 std::string &errMsg) {
110 OwningPtr<MemoryBuffer> buffer;
111 if (error_code ec = MemoryBuffer::getOpenFile(fd, path, buffer, file_size,
112 map_size, offset, false)) {
113 errMsg = ec.message();
116 return makeLTOModule(buffer.take(), errMsg);
119 /// makeBuffer - Create a MemoryBuffer from a memory range.
120 MemoryBuffer *LTOModule::makeBuffer(const void *mem, size_t length) {
121 const char *startPtr = (char*)mem;
122 return MemoryBuffer::getMemBuffer(StringRef(startPtr, length), "", false);
126 LTOModule *LTOModule::makeLTOModule(const void *mem, size_t length,
127 std::string &errMsg) {
128 OwningPtr<MemoryBuffer> buffer(makeBuffer(mem, length));
131 return makeLTOModule(buffer.take(), errMsg);
134 LTOModule *LTOModule::makeLTOModule(MemoryBuffer *buffer,
135 std::string &errMsg) {
136 static bool Initialized = false;
138 InitializeAllTargets();
139 InitializeAllMCCodeGenInfos();
140 InitializeAllMCAsmInfos();
141 InitializeAllMCSubtargetInfos();
142 InitializeAllAsmParsers();
146 // parse bitcode buffer
147 OwningPtr<Module> m(getLazyBitcodeModule(buffer, getGlobalContext(),
154 std::string Triple = m->getTargetTriple();
156 Triple = sys::getHostTriple();
158 // find machine architecture for this module
159 const Target *march = TargetRegistry::lookupTarget(Triple, errMsg);
163 // construct LTOModule, hand over ownership of module and target
164 SubtargetFeatures Features;
165 Features.getDefaultSubtargetFeatures(llvm::Triple(Triple));
166 std::string FeatureStr = Features.getString();
168 TargetMachine *target = march->createTargetMachine(Triple, CPU, FeatureStr);
169 LTOModule *Ret = new LTOModule(m.take(), target);
170 bool Err = Ret->ParseSymbols();
179 const char *LTOModule::getTargetTriple() {
180 return _module->getTargetTriple().c_str();
183 void LTOModule::setTargetTriple(const char *triple) {
184 _module->setTargetTriple(triple);
187 void LTOModule::addDefinedFunctionSymbol(Function *f, Mangler &mangler) {
188 // add to list of defined symbols
189 addDefinedSymbol(f, mangler, true);
192 // Get string that data pointer points to.
193 bool LTOModule::objcClassNameFromExpression(Constant *c, std::string &name) {
194 if (ConstantExpr *ce = dyn_cast<ConstantExpr>(c)) {
195 Constant *op = ce->getOperand(0);
196 if (GlobalVariable *gvn = dyn_cast<GlobalVariable>(op)) {
197 Constant *cn = gvn->getInitializer();
198 if (ConstantArray *ca = dyn_cast<ConstantArray>(cn)) {
199 if (ca->isCString()) {
200 name = ".objc_class_name_" + ca->getAsCString();
209 // Parse i386/ppc ObjC class data structure.
210 void LTOModule::addObjCClass(GlobalVariable *clgv) {
211 if (ConstantStruct *c = dyn_cast<ConstantStruct>(clgv->getInitializer())) {
212 // second slot in __OBJC,__class is pointer to superclass name
213 std::string superclassName;
214 if (objcClassNameFromExpression(c->getOperand(1), superclassName)) {
215 NameAndAttributes info;
216 StringMap<NameAndAttributes>::value_type &entry =
217 _undefines.GetOrCreateValue(superclassName);
218 if (!entry.getValue().name) {
219 const char *symbolName = entry.getKey().data();
220 info.name = symbolName;
221 info.attributes = LTO_SYMBOL_DEFINITION_UNDEFINED;
222 entry.setValue(info);
225 // third slot in __OBJC,__class is pointer to class name
226 std::string className;
227 if (objcClassNameFromExpression(c->getOperand(2), className)) {
228 StringSet::value_type &entry =
229 _defines.GetOrCreateValue(className);
231 NameAndAttributes info;
232 info.name = entry.getKey().data();
233 info.attributes = (lto_symbol_attributes)
234 (LTO_SYMBOL_PERMISSIONS_DATA |
235 LTO_SYMBOL_DEFINITION_REGULAR |
236 LTO_SYMBOL_SCOPE_DEFAULT);
237 _symbols.push_back(info);
243 // Parse i386/ppc ObjC category data structure.
244 void LTOModule::addObjCCategory(GlobalVariable *clgv) {
245 if (ConstantStruct *c = dyn_cast<ConstantStruct>(clgv->getInitializer())) {
246 // second slot in __OBJC,__category is pointer to target class name
247 std::string targetclassName;
248 if (objcClassNameFromExpression(c->getOperand(1), targetclassName)) {
249 NameAndAttributes info;
251 StringMap<NameAndAttributes>::value_type &entry =
252 _undefines.GetOrCreateValue(targetclassName);
254 if (entry.getValue().name)
257 const char *symbolName = entry.getKey().data();
258 info.name = symbolName;
259 info.attributes = LTO_SYMBOL_DEFINITION_UNDEFINED;
260 entry.setValue(info);
266 // Parse i386/ppc ObjC class list data structure.
267 void LTOModule::addObjCClassRef(GlobalVariable *clgv) {
268 std::string targetclassName;
269 if (objcClassNameFromExpression(clgv->getInitializer(), targetclassName)) {
270 NameAndAttributes info;
272 StringMap<NameAndAttributes>::value_type &entry =
273 _undefines.GetOrCreateValue(targetclassName);
274 if (entry.getValue().name)
277 const char *symbolName = entry.getKey().data();
278 info.name = symbolName;
279 info.attributes = LTO_SYMBOL_DEFINITION_UNDEFINED;
280 entry.setValue(info);
285 void LTOModule::addDefinedDataSymbol(GlobalValue *v, Mangler &mangler) {
286 // Add to list of defined symbols.
287 addDefinedSymbol(v, mangler, false);
289 // Special case i386/ppc ObjC data structures in magic sections:
290 // The issue is that the old ObjC object format did some strange
291 // contortions to avoid real linker symbols. For instance, the
292 // ObjC class data structure is allocated statically in the executable
293 // that defines that class. That data structures contains a pointer to
294 // its superclass. But instead of just initializing that part of the
295 // struct to the address of its superclass, and letting the static and
296 // dynamic linkers do the rest, the runtime works by having that field
297 // instead point to a C-string that is the name of the superclass.
298 // At runtime the objc initialization updates that pointer and sets
299 // it to point to the actual super class. As far as the linker
300 // knows it is just a pointer to a string. But then someone wanted the
301 // linker to issue errors at build time if the superclass was not found.
302 // So they figured out a way in mach-o object format to use an absolute
303 // symbols (.objc_class_name_Foo = 0) and a floating reference
304 // (.reference .objc_class_name_Bar) to cause the linker into erroring when
305 // a class was missing.
306 // The following synthesizes the implicit .objc_* symbols for the linker
307 // from the ObjC data structures generated by the front end.
308 if (v->hasSection() /* && isTargetDarwin */) {
309 // special case if this data blob is an ObjC class definition
310 if (v->getSection().compare(0, 15, "__OBJC,__class,") == 0) {
311 if (GlobalVariable *gv = dyn_cast<GlobalVariable>(v)) {
316 // special case if this data blob is an ObjC category definition
317 else if (v->getSection().compare(0, 18, "__OBJC,__category,") == 0) {
318 if (GlobalVariable *gv = dyn_cast<GlobalVariable>(v)) {
323 // special case if this data blob is the list of referenced classes
324 else if (v->getSection().compare(0, 18, "__OBJC,__cls_refs,") == 0) {
325 if (GlobalVariable *gv = dyn_cast<GlobalVariable>(v)) {
333 void LTOModule::addDefinedSymbol(GlobalValue *def, Mangler &mangler,
335 // ignore all llvm.* symbols
336 if (def->getName().startswith("llvm."))
339 // string is owned by _defines
340 SmallString<64> Buffer;
341 mangler.getNameWithPrefix(Buffer, def, false);
343 // set alignment part log2() can have rounding errors
344 uint32_t align = def->getAlignment();
345 uint32_t attr = align ? CountTrailingZeros_32(def->getAlignment()) : 0;
347 // set permissions part
349 attr |= LTO_SYMBOL_PERMISSIONS_CODE;
351 GlobalVariable *gv = dyn_cast<GlobalVariable>(def);
352 if (gv && gv->isConstant())
353 attr |= LTO_SYMBOL_PERMISSIONS_RODATA;
355 attr |= LTO_SYMBOL_PERMISSIONS_DATA;
358 // set definition part
359 if (def->hasWeakLinkage() || def->hasLinkOnceLinkage() ||
360 def->hasLinkerPrivateWeakLinkage() ||
361 def->hasLinkerPrivateWeakDefAutoLinkage())
362 attr |= LTO_SYMBOL_DEFINITION_WEAK;
363 else if (def->hasCommonLinkage())
364 attr |= LTO_SYMBOL_DEFINITION_TENTATIVE;
366 attr |= LTO_SYMBOL_DEFINITION_REGULAR;
369 if (def->hasHiddenVisibility())
370 attr |= LTO_SYMBOL_SCOPE_HIDDEN;
371 else if (def->hasProtectedVisibility())
372 attr |= LTO_SYMBOL_SCOPE_PROTECTED;
373 else if (def->hasExternalLinkage() || def->hasWeakLinkage() ||
374 def->hasLinkOnceLinkage() || def->hasCommonLinkage() ||
375 def->hasLinkerPrivateWeakLinkage())
376 attr |= LTO_SYMBOL_SCOPE_DEFAULT;
377 else if (def->hasLinkerPrivateWeakDefAutoLinkage())
378 attr |= LTO_SYMBOL_SCOPE_DEFAULT_CAN_BE_HIDDEN;
380 attr |= LTO_SYMBOL_SCOPE_INTERNAL;
382 // add to table of symbols
383 NameAndAttributes info;
384 StringSet::value_type &entry = _defines.GetOrCreateValue(Buffer);
387 StringRef Name = entry.getKey();
388 info.name = Name.data();
389 assert(info.name[Name.size()] == '\0');
390 info.attributes = (lto_symbol_attributes)attr;
391 _symbols.push_back(info);
394 void LTOModule::addAsmGlobalSymbol(const char *name,
395 lto_symbol_attributes scope) {
396 StringSet::value_type &entry = _defines.GetOrCreateValue(name);
398 // only add new define if not already defined
399 if (entry.getValue())
403 const char *symbolName = entry.getKey().data();
404 uint32_t attr = LTO_SYMBOL_DEFINITION_REGULAR;
406 NameAndAttributes info;
407 info.name = symbolName;
408 info.attributes = (lto_symbol_attributes)attr;
409 _symbols.push_back(info);
412 void LTOModule::addAsmGlobalSymbolUndef(const char *name) {
413 StringMap<NameAndAttributes>::value_type &entry =
414 _undefines.GetOrCreateValue(name);
416 _asm_undefines.push_back(entry.getKey().data());
418 // we already have the symbol
419 if (entry.getValue().name)
422 uint32_t attr = LTO_SYMBOL_DEFINITION_UNDEFINED;;
423 attr |= LTO_SYMBOL_SCOPE_DEFAULT;
424 NameAndAttributes info;
425 info.name = entry.getKey().data();
426 info.attributes = (lto_symbol_attributes)attr;
428 entry.setValue(info);
431 void LTOModule::addPotentialUndefinedSymbol(GlobalValue *decl,
433 // ignore all llvm.* symbols
434 if (decl->getName().startswith("llvm."))
437 // ignore all aliases
438 if (isa<GlobalAlias>(decl))
441 SmallString<64> name;
442 mangler.getNameWithPrefix(name, decl, false);
444 StringMap<NameAndAttributes>::value_type &entry =
445 _undefines.GetOrCreateValue(name);
447 // we already have the symbol
448 if (entry.getValue().name)
451 NameAndAttributes info;
453 info.name = entry.getKey().data();
454 if (decl->hasExternalWeakLinkage())
455 info.attributes = LTO_SYMBOL_DEFINITION_WEAKUNDEF;
457 info.attributes = LTO_SYMBOL_DEFINITION_UNDEFINED;
459 entry.setValue(info);
464 class RecordStreamer : public MCStreamer {
466 enum State { NeverSeen, Global, Defined, DefinedGlobal, Used};
469 StringMap<State> Symbols;
471 void markDefined(const MCSymbol &Symbol) {
472 State &S = Symbols[Symbol.getName()];
485 void markGlobal(const MCSymbol &Symbol) {
486 State &S = Symbols[Symbol.getName()];
500 void markUsed(const MCSymbol &Symbol) {
501 State &S = Symbols[Symbol.getName()];
515 // FIXME: mostly copied for the obj streamer.
516 void AddValueSymbols(const MCExpr *Value) {
517 switch (Value->getKind()) {
519 // FIXME: What should we do in here?
522 case MCExpr::Constant:
525 case MCExpr::Binary: {
526 const MCBinaryExpr *BE = cast<MCBinaryExpr>(Value);
527 AddValueSymbols(BE->getLHS());
528 AddValueSymbols(BE->getRHS());
532 case MCExpr::SymbolRef:
533 markUsed(cast<MCSymbolRefExpr>(Value)->getSymbol());
537 AddValueSymbols(cast<MCUnaryExpr>(Value)->getSubExpr());
543 typedef StringMap<State>::const_iterator const_iterator;
545 const_iterator begin() {
546 return Symbols.begin();
549 const_iterator end() {
550 return Symbols.end();
553 RecordStreamer(MCContext &Context) : MCStreamer(Context) {}
555 virtual void ChangeSection(const MCSection *Section) {}
556 virtual void InitSections() {}
557 virtual void EmitLabel(MCSymbol *Symbol) {
558 Symbol->setSection(*getCurrentSection());
559 markDefined(*Symbol);
561 virtual void EmitAssemblerFlag(MCAssemblerFlag Flag) {}
562 virtual void EmitThumbFunc(MCSymbol *Func) {}
563 virtual void EmitAssignment(MCSymbol *Symbol, const MCExpr *Value) {
564 // FIXME: should we handle aliases?
565 markDefined(*Symbol);
567 virtual void EmitSymbolAttribute(MCSymbol *Symbol, MCSymbolAttr Attribute) {
568 if (Attribute == MCSA_Global)
571 virtual void EmitSymbolDesc(MCSymbol *Symbol, unsigned DescValue) {}
572 virtual void EmitWeakReference(MCSymbol *Alias, const MCSymbol *Symbol) {}
573 virtual void BeginCOFFSymbolDef(const MCSymbol *Symbol) {}
574 virtual void EmitCOFFSymbolStorageClass(int StorageClass) {}
575 virtual void EmitZerofill(const MCSection *Section, MCSymbol *Symbol,
576 unsigned Size , unsigned ByteAlignment) {
577 markDefined(*Symbol);
579 virtual void EmitCOFFSymbolType(int Type) {}
580 virtual void EndCOFFSymbolDef() {}
581 virtual void EmitCommonSymbol(MCSymbol *Symbol, uint64_t Size,
582 unsigned ByteAlignment) {
583 markDefined(*Symbol);
585 virtual void EmitELFSize(MCSymbol *Symbol, const MCExpr *Value) {}
586 virtual void EmitLocalCommonSymbol(MCSymbol *Symbol, uint64_t Size) {}
587 virtual void EmitTBSSSymbol(const MCSection *Section, MCSymbol *Symbol,
588 uint64_t Size, unsigned ByteAlignment) {}
589 virtual void EmitBytes(StringRef Data, unsigned AddrSpace) {}
590 virtual void EmitValueImpl(const MCExpr *Value, unsigned Size,
591 unsigned AddrSpace) {}
592 virtual void EmitULEB128Value(const MCExpr *Value) {}
593 virtual void EmitSLEB128Value(const MCExpr *Value) {}
594 virtual void EmitValueToAlignment(unsigned ByteAlignment, int64_t Value,
596 unsigned MaxBytesToEmit) {}
597 virtual void EmitCodeAlignment(unsigned ByteAlignment,
598 unsigned MaxBytesToEmit) {}
599 virtual void EmitValueToOffset(const MCExpr *Offset,
600 unsigned char Value ) {}
601 virtual void EmitFileDirective(StringRef Filename) {}
602 virtual void EmitDwarfAdvanceLineAddr(int64_t LineDelta,
603 const MCSymbol *LastLabel,
604 const MCSymbol *Label,
605 unsigned PointerSize) {}
607 virtual void EmitInstruction(const MCInst &Inst) {
609 for (unsigned i = Inst.getNumOperands(); i--; )
610 if (Inst.getOperand(i).isExpr())
611 AddValueSymbols(Inst.getOperand(i).getExpr());
613 virtual void Finish() {}
617 bool LTOModule::addAsmGlobalSymbols(MCContext &Context) {
618 const std::string &inlineAsm = _module->getModuleInlineAsm();
620 OwningPtr<RecordStreamer> Streamer(new RecordStreamer(Context));
621 MemoryBuffer *Buffer = MemoryBuffer::getMemBuffer(inlineAsm);
623 SrcMgr.AddNewSourceBuffer(Buffer, SMLoc());
624 OwningPtr<MCAsmParser> Parser(createMCAsmParser(_target->getTarget(), SrcMgr,
626 *_target->getMCAsmInfo()));
627 OwningPtr<MCSubtargetInfo> STI(_target->getTarget().
628 createMCSubtargetInfo(_target->getTargetTriple(),
629 _target->getTargetCPU(),
630 _target->getTargetFeatureString()));
631 OwningPtr<TargetAsmParser>
632 TAP(_target->getTarget().createAsmParser(*STI, *Parser.get()));
633 Parser->setTargetParser(*TAP);
634 int Res = Parser->Run(false);
638 for (RecordStreamer::const_iterator i = Streamer->begin(),
639 e = Streamer->end(); i != e; ++i) {
640 StringRef Key = i->first();
641 RecordStreamer::State Value = i->second;
642 if (Value == RecordStreamer::DefinedGlobal)
643 addAsmGlobalSymbol(Key.data(), LTO_SYMBOL_SCOPE_DEFAULT);
644 else if (Value == RecordStreamer::Defined)
645 addAsmGlobalSymbol(Key.data(), LTO_SYMBOL_SCOPE_INTERNAL);
646 else if (Value == RecordStreamer::Global ||
647 Value == RecordStreamer::Used)
648 addAsmGlobalSymbolUndef(Key.data());
653 static bool isDeclaration(const GlobalValue &V) {
654 if (V.hasAvailableExternallyLinkage())
656 if (V.isMaterializable())
658 return V.isDeclaration();
661 static bool isAliasToDeclaration(const GlobalAlias &V) {
662 return isDeclaration(*V.getAliasedGlobal());
665 bool LTOModule::ParseSymbols() {
666 // Use mangler to add GlobalPrefix to names to match linker names.
667 MCContext Context(*_target->getMCAsmInfo(), *_target->getRegisterInfo(),NULL);
668 Mangler mangler(Context, *_target->getTargetData());
671 for (Module::iterator f = _module->begin(); f != _module->end(); ++f) {
672 if (isDeclaration(*f))
673 addPotentialUndefinedSymbol(f, mangler);
675 addDefinedFunctionSymbol(f, mangler);
679 for (Module::global_iterator v = _module->global_begin(),
680 e = _module->global_end(); v != e; ++v) {
681 if (isDeclaration(*v))
682 addPotentialUndefinedSymbol(v, mangler);
684 addDefinedDataSymbol(v, mangler);
688 if (addAsmGlobalSymbols(Context))
692 for (Module::alias_iterator i = _module->alias_begin(),
693 e = _module->alias_end(); i != e; ++i) {
694 if (isAliasToDeclaration(*i))
695 addPotentialUndefinedSymbol(i, mangler);
697 addDefinedDataSymbol(i, mangler);
700 // make symbols for all undefines
701 for (StringMap<NameAndAttributes>::iterator it=_undefines.begin();
702 it != _undefines.end(); ++it) {
703 // if this symbol also has a definition, then don't make an undefine
704 // because it is a tentative definition
705 if (_defines.count(it->getKey()) == 0) {
706 NameAndAttributes info = it->getValue();
707 _symbols.push_back(info);
714 uint32_t LTOModule::getSymbolCount() {
715 return _symbols.size();
719 lto_symbol_attributes LTOModule::getSymbolAttributes(uint32_t index) {
720 if (index < _symbols.size())
721 return _symbols[index].attributes;
723 return lto_symbol_attributes(0);
726 const char *LTOModule::getSymbolName(uint32_t index) {
727 if (index < _symbols.size())
728 return _symbols[index].name;