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"
16 #include "llvm/Constants.h"
17 #include "llvm/LLVMContext.h"
18 #include "llvm/Module.h"
19 #include "llvm/Bitcode/ReaderWriter.h"
20 #include "llvm/MC/MCExpr.h"
21 #include "llvm/MC/MCInst.h"
22 #include "llvm/MC/MCStreamer.h"
23 #include "llvm/MC/MCSubtargetInfo.h"
24 #include "llvm/MC/MCSymbol.h"
25 #include "llvm/MC/MCTargetAsmParser.h"
26 #include "llvm/MC/SubtargetFeature.h"
27 #include "llvm/MC/MCParser/MCAsmParser.h"
28 #include "llvm/Target/TargetRegisterInfo.h"
29 #include "llvm/Support/CommandLine.h"
30 #include "llvm/Support/Host.h"
31 #include "llvm/Support/MemoryBuffer.h"
32 #include "llvm/Support/Path.h"
33 #include "llvm/Support/SourceMgr.h"
34 #include "llvm/Support/TargetRegistry.h"
35 #include "llvm/Support/TargetSelect.h"
36 #include "llvm/Support/system_error.h"
37 #include "llvm/ADT/OwningPtr.h"
38 #include "llvm/ADT/Triple.h"
42 EnableFPMAD("enable-fp-mad",
43 cl::desc("Enable less precise MAD instructions to be generated"),
47 DisableFPElim("disable-fp-elim",
48 cl::desc("Disable frame pointer elimination optimization"),
52 DisableFPElimNonLeaf("disable-non-leaf-fp-elim",
53 cl::desc("Disable frame pointer elimination optimization for non-leaf funcs"),
57 EnableUnsafeFPMath("enable-unsafe-fp-math",
58 cl::desc("Enable optimizations that may decrease FP precision"),
62 EnableNoInfsFPMath("enable-no-infs-fp-math",
63 cl::desc("Enable FP math optimizations that assume no +-Infs"),
67 EnableNoNaNsFPMath("enable-no-nans-fp-math",
68 cl::desc("Enable FP math optimizations that assume no NaNs"),
72 EnableHonorSignDependentRoundingFPMath("enable-sign-dependent-rounding-fp-math",
74 cl::desc("Force codegen to assume rounding mode can change dynamically"),
78 GenerateSoftFloatCalls("soft-float",
79 cl::desc("Generate software floating point library calls"),
82 static cl::opt<llvm::FloatABI::ABIType>
83 FloatABIForCalls("float-abi",
84 cl::desc("Choose float ABI type"),
85 cl::init(FloatABI::Default),
87 clEnumValN(FloatABI::Default, "default",
88 "Target default float ABI type"),
89 clEnumValN(FloatABI::Soft, "soft",
90 "Soft float ABI (implied by -soft-float)"),
91 clEnumValN(FloatABI::Hard, "hard",
92 "Hard float ABI (uses FP registers)"),
95 static cl::opt<llvm::FPOpFusion::FPOpFusionMode>
96 FuseFPOps("fp-contract",
97 cl::desc("Enable aggresive formation of fused FP ops"),
98 cl::init(FPOpFusion::Standard),
100 clEnumValN(FPOpFusion::Fast, "fast",
101 "Fuse FP ops whenever profitable"),
102 clEnumValN(FPOpFusion::Standard, "on",
103 "Only fuse 'blessed' FP ops."),
104 clEnumValN(FPOpFusion::Strict, "off",
105 "Only fuse FP ops when the result won't be effected."),
109 DontPlaceZerosInBSS("nozero-initialized-in-bss",
110 cl::desc("Don't place zero-initialized symbols into bss section"),
114 EnableGuaranteedTailCallOpt("tailcallopt",
115 cl::desc("Turn fastcc calls into tail calls by (potentially) changing ABI."),
119 DisableTailCalls("disable-tail-calls",
120 cl::desc("Never emit tail calls"),
123 static cl::opt<unsigned>
124 OverrideStackAlignment("stack-alignment",
125 cl::desc("Override default stack alignment"),
129 EnableRealignStack("realign-stack",
130 cl::desc("Realign stack if needed"),
133 static cl::opt<std::string>
134 TrapFuncName("trap-func", cl::Hidden,
135 cl::desc("Emit a call to trap function rather than a trap instruction"),
139 EnablePIE("enable-pie",
140 cl::desc("Assume the creation of a position independent executable."),
144 SegmentedStacks("segmented-stacks",
145 cl::desc("Use segmented stacks if possible."),
149 UseInitArray("use-init-array",
150 cl::desc("Use .init_array instead of .ctors."),
153 LTOModule::LTOModule(llvm::Module *m, llvm::TargetMachine *t)
154 : _module(m), _target(t),
155 _context(*_target->getMCAsmInfo(), *_target->getRegisterInfo(), NULL),
156 _mangler(_context, *_target->getTargetData()) {}
158 /// isBitcodeFile - Returns 'true' if the file (or memory contents) is LLVM
160 bool LTOModule::isBitcodeFile(const void *mem, size_t length) {
161 return llvm::sys::IdentifyFileType((char*)mem, length)
162 == llvm::sys::Bitcode_FileType;
165 bool LTOModule::isBitcodeFile(const char *path) {
166 return llvm::sys::Path(path).isBitcodeFile();
169 /// isBitcodeFileForTarget - Returns 'true' if the file (or memory contents) is
170 /// LLVM bitcode for the specified triple.
171 bool LTOModule::isBitcodeFileForTarget(const void *mem, size_t length,
172 const char *triplePrefix) {
173 MemoryBuffer *buffer = makeBuffer(mem, length);
176 return isTargetMatch(buffer, triplePrefix);
179 bool LTOModule::isBitcodeFileForTarget(const char *path,
180 const char *triplePrefix) {
181 OwningPtr<MemoryBuffer> buffer;
182 if (MemoryBuffer::getFile(path, buffer))
184 return isTargetMatch(buffer.take(), triplePrefix);
187 /// isTargetMatch - Returns 'true' if the memory buffer is for the specified
189 bool LTOModule::isTargetMatch(MemoryBuffer *buffer, const char *triplePrefix) {
190 std::string Triple = getBitcodeTargetTriple(buffer, getGlobalContext());
192 return strncmp(Triple.c_str(), triplePrefix, strlen(triplePrefix)) == 0;
195 /// makeLTOModule - Create an LTOModule. N.B. These methods take ownership of
197 LTOModule *LTOModule::makeLTOModule(const char *path, std::string &errMsg) {
198 OwningPtr<MemoryBuffer> buffer;
199 if (error_code ec = MemoryBuffer::getFile(path, buffer)) {
200 errMsg = ec.message();
203 return makeLTOModule(buffer.take(), errMsg);
206 LTOModule *LTOModule::makeLTOModule(int fd, const char *path,
207 size_t size, std::string &errMsg) {
208 return makeLTOModule(fd, path, size, size, 0, errMsg);
211 LTOModule *LTOModule::makeLTOModule(int fd, const char *path,
215 std::string &errMsg) {
216 OwningPtr<MemoryBuffer> buffer;
217 if (error_code ec = MemoryBuffer::getOpenFile(fd, path, buffer, file_size,
218 map_size, offset, false)) {
219 errMsg = ec.message();
222 return makeLTOModule(buffer.take(), errMsg);
225 LTOModule *LTOModule::makeLTOModule(const void *mem, size_t length,
226 std::string &errMsg) {
227 OwningPtr<MemoryBuffer> buffer(makeBuffer(mem, length));
230 return makeLTOModule(buffer.take(), errMsg);
233 void LTOModule::getTargetOptions(TargetOptions &Options) {
234 Options.LessPreciseFPMADOption = EnableFPMAD;
235 Options.NoFramePointerElim = DisableFPElim;
236 Options.NoFramePointerElimNonLeaf = DisableFPElimNonLeaf;
237 Options.AllowFPOpFusion = FuseFPOps;
238 Options.UnsafeFPMath = EnableUnsafeFPMath;
239 Options.NoInfsFPMath = EnableNoInfsFPMath;
240 Options.NoNaNsFPMath = EnableNoNaNsFPMath;
241 Options.HonorSignDependentRoundingFPMathOption =
242 EnableHonorSignDependentRoundingFPMath;
243 Options.UseSoftFloat = GenerateSoftFloatCalls;
244 if (FloatABIForCalls != FloatABI::Default)
245 Options.FloatABIType = FloatABIForCalls;
246 Options.NoZerosInBSS = DontPlaceZerosInBSS;
247 Options.GuaranteedTailCallOpt = EnableGuaranteedTailCallOpt;
248 Options.DisableTailCalls = DisableTailCalls;
249 Options.StackAlignmentOverride = OverrideStackAlignment;
250 Options.RealignStack = EnableRealignStack;
251 Options.TrapFuncName = TrapFuncName;
252 Options.PositionIndependentExecutable = EnablePIE;
253 Options.EnableSegmentedStacks = SegmentedStacks;
254 Options.UseInitArray = UseInitArray;
257 LTOModule *LTOModule::makeLTOModule(MemoryBuffer *buffer,
258 std::string &errMsg) {
259 static bool Initialized = false;
261 InitializeAllTargets();
262 InitializeAllTargetMCs();
263 InitializeAllAsmParsers();
267 // parse bitcode buffer
268 OwningPtr<Module> m(getLazyBitcodeModule(buffer, getGlobalContext(),
275 std::string Triple = m->getTargetTriple();
277 Triple = sys::getDefaultTargetTriple();
279 // find machine architecture for this module
280 const Target *march = TargetRegistry::lookupTarget(Triple, errMsg);
284 // construct LTOModule, hand over ownership of module and target
285 SubtargetFeatures Features;
286 Features.getDefaultSubtargetFeatures(llvm::Triple(Triple));
287 std::string FeatureStr = Features.getString();
289 TargetOptions Options;
290 getTargetOptions(Options);
291 TargetMachine *target = march->createTargetMachine(Triple, CPU, FeatureStr,
293 LTOModule *Ret = new LTOModule(m.take(), target);
294 if (Ret->parseSymbols(errMsg)) {
302 /// makeBuffer - Create a MemoryBuffer from a memory range.
303 MemoryBuffer *LTOModule::makeBuffer(const void *mem, size_t length) {
304 const char *startPtr = (char*)mem;
305 return MemoryBuffer::getMemBuffer(StringRef(startPtr, length), "", false);
308 /// objcClassNameFromExpression - Get string that the data pointer points to.
309 bool LTOModule::objcClassNameFromExpression(Constant *c, std::string &name) {
310 if (ConstantExpr *ce = dyn_cast<ConstantExpr>(c)) {
311 Constant *op = ce->getOperand(0);
312 if (GlobalVariable *gvn = dyn_cast<GlobalVariable>(op)) {
313 Constant *cn = gvn->getInitializer();
314 if (ConstantDataArray *ca = dyn_cast<ConstantDataArray>(cn)) {
315 if (ca->isCString()) {
316 name = ".objc_class_name_" + ca->getAsCString().str();
325 /// addObjCClass - Parse i386/ppc ObjC class data structure.
326 void LTOModule::addObjCClass(GlobalVariable *clgv) {
327 ConstantStruct *c = dyn_cast<ConstantStruct>(clgv->getInitializer());
330 // second slot in __OBJC,__class is pointer to superclass name
331 std::string superclassName;
332 if (objcClassNameFromExpression(c->getOperand(1), superclassName)) {
333 NameAndAttributes info;
334 StringMap<NameAndAttributes>::value_type &entry =
335 _undefines.GetOrCreateValue(superclassName);
336 if (!entry.getValue().name) {
337 const char *symbolName = entry.getKey().data();
338 info.name = symbolName;
339 info.attributes = LTO_SYMBOL_DEFINITION_UNDEFINED;
340 info.isFunction = false;
342 entry.setValue(info);
346 // third slot in __OBJC,__class is pointer to class name
347 std::string className;
348 if (objcClassNameFromExpression(c->getOperand(2), className)) {
349 StringSet::value_type &entry = _defines.GetOrCreateValue(className);
352 NameAndAttributes info;
353 info.name = entry.getKey().data();
354 info.attributes = LTO_SYMBOL_PERMISSIONS_DATA |
355 LTO_SYMBOL_DEFINITION_REGULAR | LTO_SYMBOL_SCOPE_DEFAULT;
356 info.isFunction = false;
358 _symbols.push_back(info);
362 /// addObjCCategory - Parse i386/ppc ObjC category data structure.
363 void LTOModule::addObjCCategory(GlobalVariable *clgv) {
364 ConstantStruct *c = dyn_cast<ConstantStruct>(clgv->getInitializer());
367 // second slot in __OBJC,__category is pointer to target class name
368 std::string targetclassName;
369 if (!objcClassNameFromExpression(c->getOperand(1), targetclassName))
372 NameAndAttributes info;
373 StringMap<NameAndAttributes>::value_type &entry =
374 _undefines.GetOrCreateValue(targetclassName);
376 if (entry.getValue().name)
379 const char *symbolName = entry.getKey().data();
380 info.name = symbolName;
381 info.attributes = LTO_SYMBOL_DEFINITION_UNDEFINED;
382 info.isFunction = false;
384 entry.setValue(info);
387 /// addObjCClassRef - Parse i386/ppc ObjC class list data structure.
388 void LTOModule::addObjCClassRef(GlobalVariable *clgv) {
389 std::string targetclassName;
390 if (!objcClassNameFromExpression(clgv->getInitializer(), targetclassName))
393 NameAndAttributes info;
394 StringMap<NameAndAttributes>::value_type &entry =
395 _undefines.GetOrCreateValue(targetclassName);
396 if (entry.getValue().name)
399 const char *symbolName = entry.getKey().data();
400 info.name = symbolName;
401 info.attributes = LTO_SYMBOL_DEFINITION_UNDEFINED;
402 info.isFunction = false;
404 entry.setValue(info);
407 /// addDefinedDataSymbol - Add a data symbol as defined to the list.
408 void LTOModule::addDefinedDataSymbol(GlobalValue *v) {
409 // Add to list of defined symbols.
410 addDefinedSymbol(v, false);
412 if (!v->hasSection() /* || !isTargetDarwin */)
415 // Special case i386/ppc ObjC data structures in magic sections:
416 // The issue is that the old ObjC object format did some strange
417 // contortions to avoid real linker symbols. For instance, the
418 // ObjC class data structure is allocated statically in the executable
419 // that defines that class. That data structures contains a pointer to
420 // its superclass. But instead of just initializing that part of the
421 // struct to the address of its superclass, and letting the static and
422 // dynamic linkers do the rest, the runtime works by having that field
423 // instead point to a C-string that is the name of the superclass.
424 // At runtime the objc initialization updates that pointer and sets
425 // it to point to the actual super class. As far as the linker
426 // knows it is just a pointer to a string. But then someone wanted the
427 // linker to issue errors at build time if the superclass was not found.
428 // So they figured out a way in mach-o object format to use an absolute
429 // symbols (.objc_class_name_Foo = 0) and a floating reference
430 // (.reference .objc_class_name_Bar) to cause the linker into erroring when
431 // a class was missing.
432 // The following synthesizes the implicit .objc_* symbols for the linker
433 // from the ObjC data structures generated by the front end.
435 // special case if this data blob is an ObjC class definition
436 if (v->getSection().compare(0, 15, "__OBJC,__class,") == 0) {
437 if (GlobalVariable *gv = dyn_cast<GlobalVariable>(v)) {
442 // special case if this data blob is an ObjC category definition
443 else if (v->getSection().compare(0, 18, "__OBJC,__category,") == 0) {
444 if (GlobalVariable *gv = dyn_cast<GlobalVariable>(v)) {
449 // special case if this data blob is the list of referenced classes
450 else if (v->getSection().compare(0, 18, "__OBJC,__cls_refs,") == 0) {
451 if (GlobalVariable *gv = dyn_cast<GlobalVariable>(v)) {
457 /// addDefinedFunctionSymbol - Add a function symbol as defined to the list.
458 void LTOModule::addDefinedFunctionSymbol(Function *f) {
459 // add to list of defined symbols
460 addDefinedSymbol(f, true);
463 /// addDefinedSymbol - Add a defined symbol to the list.
464 void LTOModule::addDefinedSymbol(GlobalValue *def, bool isFunction) {
465 // ignore all llvm.* symbols
466 if (def->getName().startswith("llvm."))
469 // string is owned by _defines
470 SmallString<64> Buffer;
471 _mangler.getNameWithPrefix(Buffer, def, false);
473 // set alignment part log2() can have rounding errors
474 uint32_t align = def->getAlignment();
475 uint32_t attr = align ? CountTrailingZeros_32(def->getAlignment()) : 0;
477 // set permissions part
479 attr |= LTO_SYMBOL_PERMISSIONS_CODE;
481 GlobalVariable *gv = dyn_cast<GlobalVariable>(def);
482 if (gv && gv->isConstant())
483 attr |= LTO_SYMBOL_PERMISSIONS_RODATA;
485 attr |= LTO_SYMBOL_PERMISSIONS_DATA;
488 // set definition part
489 if (def->hasWeakLinkage() || def->hasLinkOnceLinkage() ||
490 def->hasLinkerPrivateWeakLinkage() ||
491 def->hasLinkerPrivateWeakDefAutoLinkage())
492 attr |= LTO_SYMBOL_DEFINITION_WEAK;
493 else if (def->hasCommonLinkage())
494 attr |= LTO_SYMBOL_DEFINITION_TENTATIVE;
496 attr |= LTO_SYMBOL_DEFINITION_REGULAR;
499 if (def->hasHiddenVisibility())
500 attr |= LTO_SYMBOL_SCOPE_HIDDEN;
501 else if (def->hasProtectedVisibility())
502 attr |= LTO_SYMBOL_SCOPE_PROTECTED;
503 else if (def->hasExternalLinkage() || def->hasWeakLinkage() ||
504 def->hasLinkOnceLinkage() || def->hasCommonLinkage() ||
505 def->hasLinkerPrivateWeakLinkage())
506 attr |= LTO_SYMBOL_SCOPE_DEFAULT;
507 else if (def->hasLinkerPrivateWeakDefAutoLinkage())
508 attr |= LTO_SYMBOL_SCOPE_DEFAULT_CAN_BE_HIDDEN;
510 attr |= LTO_SYMBOL_SCOPE_INTERNAL;
512 StringSet::value_type &entry = _defines.GetOrCreateValue(Buffer);
515 // fill information structure
516 NameAndAttributes info;
517 StringRef Name = entry.getKey();
518 info.name = Name.data();
519 assert(info.name[Name.size()] == '\0');
520 info.attributes = attr;
521 info.isFunction = isFunction;
524 // add to table of symbols
525 _symbols.push_back(info);
528 /// addAsmGlobalSymbol - Add a global symbol from module-level ASM to the
530 void LTOModule::addAsmGlobalSymbol(const char *name,
531 lto_symbol_attributes scope) {
532 StringSet::value_type &entry = _defines.GetOrCreateValue(name);
534 // only add new define if not already defined
535 if (entry.getValue())
540 NameAndAttributes &info = _undefines[entry.getKey().data()];
542 if (info.symbol == 0) {
543 // FIXME: This is trying to take care of module ASM like this:
545 // module asm ".zerofill __FOO, __foo, _bar_baz_qux, 0"
547 // but is gross and its mother dresses it funny. Have the ASM parser give us
548 // more details for this type of situation so that we're not guessing so
551 // fill information structure
552 info.name = entry.getKey().data();
554 LTO_SYMBOL_PERMISSIONS_DATA | LTO_SYMBOL_DEFINITION_REGULAR | scope;
555 info.isFunction = false;
558 // add to table of symbols
559 _symbols.push_back(info);
564 addDefinedFunctionSymbol(cast<Function>(info.symbol));
566 addDefinedDataSymbol(info.symbol);
568 _symbols.back().attributes &= ~LTO_SYMBOL_SCOPE_MASK;
569 _symbols.back().attributes |= scope;
572 /// addAsmGlobalSymbolUndef - Add a global symbol from module-level ASM to the
574 void LTOModule::addAsmGlobalSymbolUndef(const char *name) {
575 StringMap<NameAndAttributes>::value_type &entry =
576 _undefines.GetOrCreateValue(name);
578 _asm_undefines.push_back(entry.getKey().data());
580 // we already have the symbol
581 if (entry.getValue().name)
584 uint32_t attr = LTO_SYMBOL_DEFINITION_UNDEFINED;;
585 attr |= LTO_SYMBOL_SCOPE_DEFAULT;
586 NameAndAttributes info;
587 info.name = entry.getKey().data();
588 info.attributes = attr;
589 info.isFunction = false;
592 entry.setValue(info);
595 /// addPotentialUndefinedSymbol - Add a symbol which isn't defined just yet to a
596 /// list to be resolved later.
597 void LTOModule::addPotentialUndefinedSymbol(GlobalValue *decl, bool isFunc) {
598 // ignore all llvm.* symbols
599 if (decl->getName().startswith("llvm."))
602 // ignore all aliases
603 if (isa<GlobalAlias>(decl))
606 SmallString<64> name;
607 _mangler.getNameWithPrefix(name, decl, false);
609 StringMap<NameAndAttributes>::value_type &entry =
610 _undefines.GetOrCreateValue(name);
612 // we already have the symbol
613 if (entry.getValue().name)
616 NameAndAttributes info;
618 info.name = entry.getKey().data();
620 if (decl->hasExternalWeakLinkage())
621 info.attributes = LTO_SYMBOL_DEFINITION_WEAKUNDEF;
623 info.attributes = LTO_SYMBOL_DEFINITION_UNDEFINED;
625 info.isFunction = isFunc;
628 entry.setValue(info);
632 class RecordStreamer : public MCStreamer {
634 enum State { NeverSeen, Global, Defined, DefinedGlobal, Used };
637 StringMap<State> Symbols;
639 void markDefined(const MCSymbol &Symbol) {
640 State &S = Symbols[Symbol.getName()];
653 void markGlobal(const MCSymbol &Symbol) {
654 State &S = Symbols[Symbol.getName()];
668 void markUsed(const MCSymbol &Symbol) {
669 State &S = Symbols[Symbol.getName()];
683 // FIXME: mostly copied for the obj streamer.
684 void AddValueSymbols(const MCExpr *Value) {
685 switch (Value->getKind()) {
687 // FIXME: What should we do in here?
690 case MCExpr::Constant:
693 case MCExpr::Binary: {
694 const MCBinaryExpr *BE = cast<MCBinaryExpr>(Value);
695 AddValueSymbols(BE->getLHS());
696 AddValueSymbols(BE->getRHS());
700 case MCExpr::SymbolRef:
701 markUsed(cast<MCSymbolRefExpr>(Value)->getSymbol());
705 AddValueSymbols(cast<MCUnaryExpr>(Value)->getSubExpr());
711 typedef StringMap<State>::const_iterator const_iterator;
713 const_iterator begin() {
714 return Symbols.begin();
717 const_iterator end() {
718 return Symbols.end();
721 RecordStreamer(MCContext &Context) : MCStreamer(Context) {}
723 virtual void EmitInstruction(const MCInst &Inst) {
725 for (unsigned i = Inst.getNumOperands(); i--; )
726 if (Inst.getOperand(i).isExpr())
727 AddValueSymbols(Inst.getOperand(i).getExpr());
729 virtual void EmitLabel(MCSymbol *Symbol) {
730 Symbol->setSection(*getCurrentSection());
731 markDefined(*Symbol);
733 virtual void EmitAssignment(MCSymbol *Symbol, const MCExpr *Value) {
734 // FIXME: should we handle aliases?
735 markDefined(*Symbol);
737 virtual void EmitSymbolAttribute(MCSymbol *Symbol, MCSymbolAttr Attribute) {
738 if (Attribute == MCSA_Global)
741 virtual void EmitZerofill(const MCSection *Section, MCSymbol *Symbol,
742 uint64_t Size , unsigned ByteAlignment) {
743 markDefined(*Symbol);
745 virtual void EmitCommonSymbol(MCSymbol *Symbol, uint64_t Size,
746 unsigned ByteAlignment) {
747 markDefined(*Symbol);
751 virtual void ChangeSection(const MCSection *Section) {}
752 virtual void InitSections() {}
753 virtual void EmitAssemblerFlag(MCAssemblerFlag Flag) {}
754 virtual void EmitThumbFunc(MCSymbol *Func) {}
755 virtual void EmitSymbolDesc(MCSymbol *Symbol, unsigned DescValue) {}
756 virtual void EmitWeakReference(MCSymbol *Alias, const MCSymbol *Symbol) {}
757 virtual void BeginCOFFSymbolDef(const MCSymbol *Symbol) {}
758 virtual void EmitCOFFSymbolStorageClass(int StorageClass) {}
759 virtual void EmitCOFFSymbolType(int Type) {}
760 virtual void EndCOFFSymbolDef() {}
761 virtual void EmitELFSize(MCSymbol *Symbol, const MCExpr *Value) {}
762 virtual void EmitLocalCommonSymbol(MCSymbol *Symbol, uint64_t Size,
763 unsigned ByteAlignment) {}
764 virtual void EmitTBSSSymbol(const MCSection *Section, MCSymbol *Symbol,
765 uint64_t Size, unsigned ByteAlignment) {}
766 virtual void EmitBytes(StringRef Data, unsigned AddrSpace) {}
767 virtual void EmitValueImpl(const MCExpr *Value, unsigned Size,
768 unsigned AddrSpace) {}
769 virtual void EmitULEB128Value(const MCExpr *Value) {}
770 virtual void EmitSLEB128Value(const MCExpr *Value) {}
771 virtual void EmitValueToAlignment(unsigned ByteAlignment, int64_t Value,
773 unsigned MaxBytesToEmit) {}
774 virtual void EmitCodeAlignment(unsigned ByteAlignment,
775 unsigned MaxBytesToEmit) {}
776 virtual bool EmitValueToOffset(const MCExpr *Offset,
777 unsigned char Value ) { return false; }
778 virtual void EmitFileDirective(StringRef Filename) {}
779 virtual void EmitDwarfAdvanceLineAddr(int64_t LineDelta,
780 const MCSymbol *LastLabel,
781 const MCSymbol *Label,
782 unsigned PointerSize) {}
783 virtual void FinishImpl() {}
785 } // end anonymous namespace
787 /// addAsmGlobalSymbols - Add global symbols from module-level ASM to the
788 /// defined or undefined lists.
789 bool LTOModule::addAsmGlobalSymbols(std::string &errMsg) {
790 const std::string &inlineAsm = _module->getModuleInlineAsm();
791 if (inlineAsm.empty())
794 OwningPtr<RecordStreamer> Streamer(new RecordStreamer(_context));
795 MemoryBuffer *Buffer = MemoryBuffer::getMemBuffer(inlineAsm);
797 SrcMgr.AddNewSourceBuffer(Buffer, SMLoc());
798 OwningPtr<MCAsmParser> Parser(createMCAsmParser(SrcMgr,
800 *_target->getMCAsmInfo()));
801 const Target &T = _target->getTarget();
802 OwningPtr<MCSubtargetInfo>
803 STI(T.createMCSubtargetInfo(_target->getTargetTriple(),
804 _target->getTargetCPU(),
805 _target->getTargetFeatureString()));
806 OwningPtr<MCTargetAsmParser> TAP(T.createMCAsmParser(*STI, *Parser.get()));
808 errMsg = "target " + std::string(T.getName()) +
809 " does not define AsmParser.";
813 Parser->setTargetParser(*TAP);
814 if (Parser->Run(false))
817 for (RecordStreamer::const_iterator i = Streamer->begin(),
818 e = Streamer->end(); i != e; ++i) {
819 StringRef Key = i->first();
820 RecordStreamer::State Value = i->second;
821 if (Value == RecordStreamer::DefinedGlobal)
822 addAsmGlobalSymbol(Key.data(), LTO_SYMBOL_SCOPE_DEFAULT);
823 else if (Value == RecordStreamer::Defined)
824 addAsmGlobalSymbol(Key.data(), LTO_SYMBOL_SCOPE_INTERNAL);
825 else if (Value == RecordStreamer::Global ||
826 Value == RecordStreamer::Used)
827 addAsmGlobalSymbolUndef(Key.data());
833 /// isDeclaration - Return 'true' if the global value is a declaration.
834 static bool isDeclaration(const GlobalValue &V) {
835 if (V.hasAvailableExternallyLinkage())
838 if (V.isMaterializable())
841 return V.isDeclaration();
844 /// parseSymbols - Parse the symbols from the module and model-level ASM and add
845 /// them to either the defined or undefined lists.
846 bool LTOModule::parseSymbols(std::string &errMsg) {
848 for (Module::iterator f = _module->begin(), e = _module->end(); f != e; ++f) {
849 if (isDeclaration(*f))
850 addPotentialUndefinedSymbol(f, true);
852 addDefinedFunctionSymbol(f);
856 for (Module::global_iterator v = _module->global_begin(),
857 e = _module->global_end(); v != e; ++v) {
858 if (isDeclaration(*v))
859 addPotentialUndefinedSymbol(v, false);
861 addDefinedDataSymbol(v);
865 if (addAsmGlobalSymbols(errMsg))
869 for (Module::alias_iterator a = _module->alias_begin(),
870 e = _module->alias_end(); a != e; ++a) {
871 if (isDeclaration(*a->getAliasedGlobal()))
872 // Is an alias to a declaration.
873 addPotentialUndefinedSymbol(a, false);
875 addDefinedDataSymbol(a);
878 // make symbols for all undefines
879 for (StringMap<NameAndAttributes>::iterator u =_undefines.begin(),
880 e = _undefines.end(); u != e; ++u) {
881 // If this symbol also has a definition, then don't make an undefine because
882 // it is a tentative definition.
883 if (_defines.count(u->getKey())) continue;
884 NameAndAttributes info = u->getValue();
885 _symbols.push_back(info);