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/ADT/OwningPtr.h"
17 #include "llvm/ADT/Triple.h"
18 #include "llvm/Bitcode/ReaderWriter.h"
19 #include "llvm/IR/Constants.h"
20 #include "llvm/IR/LLVMContext.h"
21 #include "llvm/IR/Module.h"
22 #include "llvm/MC/MCExpr.h"
23 #include "llvm/MC/MCInst.h"
24 #include "llvm/MC/MCParser/MCAsmParser.h"
25 #include "llvm/MC/MCStreamer.h"
26 #include "llvm/MC/MCSubtargetInfo.h"
27 #include "llvm/MC/MCSymbol.h"
28 #include "llvm/MC/MCTargetAsmParser.h"
29 #include "llvm/MC/SubtargetFeature.h"
30 #include "llvm/Support/CommandLine.h"
31 #include "llvm/Support/Host.h"
32 #include "llvm/Support/FileSystem.h"
33 #include "llvm/Support/MemoryBuffer.h"
34 #include "llvm/Support/Path.h"
35 #include "llvm/Support/SourceMgr.h"
36 #include "llvm/Support/TargetRegistry.h"
37 #include "llvm/Support/TargetSelect.h"
38 #include "llvm/Support/system_error.h"
39 #include "llvm/Target/TargetRegisterInfo.h"
43 EnableFPMAD("enable-fp-mad",
44 cl::desc("Enable less precise MAD instructions to be generated"),
48 DisableFPElim("disable-fp-elim",
49 cl::desc("Disable frame pointer elimination optimization"),
53 DisableFPElimNonLeaf("disable-non-leaf-fp-elim",
54 cl::desc("Disable frame pointer elimination optimization for non-leaf funcs"),
58 EnableUnsafeFPMath("enable-unsafe-fp-math",
59 cl::desc("Enable optimizations that may decrease FP precision"),
63 EnableNoInfsFPMath("enable-no-infs-fp-math",
64 cl::desc("Enable FP math optimizations that assume no +-Infs"),
68 EnableNoNaNsFPMath("enable-no-nans-fp-math",
69 cl::desc("Enable FP math optimizations that assume no NaNs"),
73 EnableHonorSignDependentRoundingFPMath("enable-sign-dependent-rounding-fp-math",
75 cl::desc("Force codegen to assume rounding mode can change dynamically"),
79 GenerateSoftFloatCalls("soft-float",
80 cl::desc("Generate software floating point library calls"),
83 static cl::opt<llvm::FloatABI::ABIType>
84 FloatABIForCalls("float-abi",
85 cl::desc("Choose float ABI type"),
86 cl::init(FloatABI::Default),
88 clEnumValN(FloatABI::Default, "default",
89 "Target default float ABI type"),
90 clEnumValN(FloatABI::Soft, "soft",
91 "Soft float ABI (implied by -soft-float)"),
92 clEnumValN(FloatABI::Hard, "hard",
93 "Hard float ABI (uses FP registers)"),
96 static cl::opt<llvm::FPOpFusion::FPOpFusionMode>
97 FuseFPOps("fp-contract",
98 cl::desc("Enable aggresive formation of fused FP ops"),
99 cl::init(FPOpFusion::Standard),
101 clEnumValN(FPOpFusion::Fast, "fast",
102 "Fuse FP ops whenever profitable"),
103 clEnumValN(FPOpFusion::Standard, "on",
104 "Only fuse 'blessed' FP ops."),
105 clEnumValN(FPOpFusion::Strict, "off",
106 "Only fuse FP ops when the result won't be effected."),
110 DontPlaceZerosInBSS("nozero-initialized-in-bss",
111 cl::desc("Don't place zero-initialized symbols into bss section"),
115 EnableGuaranteedTailCallOpt("tailcallopt",
116 cl::desc("Turn fastcc calls into tail calls by (potentially) changing ABI."),
120 DisableTailCalls("disable-tail-calls",
121 cl::desc("Never emit tail calls"),
124 static cl::opt<unsigned>
125 OverrideStackAlignment("stack-alignment",
126 cl::desc("Override default stack alignment"),
130 EnableRealignStack("realign-stack",
131 cl::desc("Realign stack if needed"),
134 static cl::opt<std::string>
135 TrapFuncName("trap-func", cl::Hidden,
136 cl::desc("Emit a call to trap function rather than a trap instruction"),
140 EnablePIE("enable-pie",
141 cl::desc("Assume the creation of a position independent executable."),
145 SegmentedStacks("segmented-stacks",
146 cl::desc("Use segmented stacks if possible."),
150 UseInitArray("use-init-array",
151 cl::desc("Use .init_array instead of .ctors."),
154 static cl::opt<unsigned>
155 SSPBufferSize("stack-protector-buffer-size", cl::init(8),
156 cl::desc("Lower bound for a buffer to be considered for "
157 "stack protection"));
159 LTOModule::LTOModule(llvm::Module *m, llvm::TargetMachine *t)
160 : _module(m), _target(t),
161 _context(*_target->getMCAsmInfo(), *_target->getRegisterInfo(), NULL),
162 _mangler(_context, t) {}
164 /// isBitcodeFile - Returns 'true' if the file (or memory contents) is LLVM
166 bool LTOModule::isBitcodeFile(const void *mem, size_t length) {
167 return sys::fs::identify_magic(StringRef((const char *)mem, length)) ==
168 sys::fs::file_magic::bitcode;
171 bool LTOModule::isBitcodeFile(const char *path) {
172 return llvm::sys::Path(path).isBitcodeFile();
175 /// isBitcodeFileForTarget - Returns 'true' if the file (or memory contents) is
176 /// LLVM bitcode for the specified triple.
177 bool LTOModule::isBitcodeFileForTarget(const void *mem, size_t length,
178 const char *triplePrefix) {
179 MemoryBuffer *buffer = makeBuffer(mem, length);
182 return isTargetMatch(buffer, triplePrefix);
185 bool LTOModule::isBitcodeFileForTarget(const char *path,
186 const char *triplePrefix) {
187 OwningPtr<MemoryBuffer> buffer;
188 if (MemoryBuffer::getFile(path, buffer))
190 return isTargetMatch(buffer.take(), triplePrefix);
193 /// isTargetMatch - Returns 'true' if the memory buffer is for the specified
195 bool LTOModule::isTargetMatch(MemoryBuffer *buffer, const char *triplePrefix) {
196 std::string Triple = getBitcodeTargetTriple(buffer, getGlobalContext());
198 return strncmp(Triple.c_str(), triplePrefix, strlen(triplePrefix)) == 0;
201 /// makeLTOModule - Create an LTOModule. N.B. These methods take ownership of
203 LTOModule *LTOModule::makeLTOModule(const char *path, std::string &errMsg) {
204 OwningPtr<MemoryBuffer> buffer;
205 if (error_code ec = MemoryBuffer::getFile(path, buffer)) {
206 errMsg = ec.message();
209 return makeLTOModule(buffer.take(), errMsg);
212 LTOModule *LTOModule::makeLTOModule(int fd, const char *path,
213 size_t size, std::string &errMsg) {
214 return makeLTOModule(fd, path, size, size, 0, errMsg);
217 LTOModule *LTOModule::makeLTOModule(int fd, const char *path,
221 std::string &errMsg) {
222 OwningPtr<MemoryBuffer> buffer;
223 if (error_code ec = MemoryBuffer::getOpenFile(fd, path, buffer, file_size,
224 map_size, offset, false)) {
225 errMsg = ec.message();
228 return makeLTOModule(buffer.take(), errMsg);
231 LTOModule *LTOModule::makeLTOModule(const void *mem, size_t length,
232 std::string &errMsg) {
233 OwningPtr<MemoryBuffer> buffer(makeBuffer(mem, length));
236 return makeLTOModule(buffer.take(), errMsg);
239 void LTOModule::getTargetOptions(TargetOptions &Options) {
240 Options.LessPreciseFPMADOption = EnableFPMAD;
241 Options.NoFramePointerElim = DisableFPElim;
242 Options.NoFramePointerElimNonLeaf = DisableFPElimNonLeaf;
243 Options.AllowFPOpFusion = FuseFPOps;
244 Options.UnsafeFPMath = EnableUnsafeFPMath;
245 Options.NoInfsFPMath = EnableNoInfsFPMath;
246 Options.NoNaNsFPMath = EnableNoNaNsFPMath;
247 Options.HonorSignDependentRoundingFPMathOption =
248 EnableHonorSignDependentRoundingFPMath;
249 Options.UseSoftFloat = GenerateSoftFloatCalls;
250 if (FloatABIForCalls != FloatABI::Default)
251 Options.FloatABIType = FloatABIForCalls;
252 Options.NoZerosInBSS = DontPlaceZerosInBSS;
253 Options.GuaranteedTailCallOpt = EnableGuaranteedTailCallOpt;
254 Options.DisableTailCalls = DisableTailCalls;
255 Options.StackAlignmentOverride = OverrideStackAlignment;
256 Options.RealignStack = EnableRealignStack;
257 Options.TrapFuncName = TrapFuncName;
258 Options.PositionIndependentExecutable = EnablePIE;
259 Options.EnableSegmentedStacks = SegmentedStacks;
260 Options.UseInitArray = UseInitArray;
261 Options.SSPBufferSize = SSPBufferSize;
264 LTOModule *LTOModule::makeLTOModule(MemoryBuffer *buffer,
265 std::string &errMsg) {
266 static bool Initialized = false;
268 InitializeAllTargets();
269 InitializeAllTargetMCs();
270 InitializeAllAsmParsers();
274 // parse bitcode buffer
275 OwningPtr<Module> m(getLazyBitcodeModule(buffer, getGlobalContext(),
282 std::string TripleStr = m->getTargetTriple();
283 if (TripleStr.empty())
284 TripleStr = sys::getDefaultTargetTriple();
285 llvm::Triple Triple(TripleStr);
287 // find machine architecture for this module
288 const Target *march = TargetRegistry::lookupTarget(TripleStr, errMsg);
292 // construct LTOModule, hand over ownership of module and target
293 SubtargetFeatures Features;
294 Features.getDefaultSubtargetFeatures(Triple);
295 std::string FeatureStr = Features.getString();
296 // Set a default CPU for Darwin triples.
298 if (Triple.isOSDarwin()) {
299 if (Triple.getArch() == llvm::Triple::x86_64)
301 else if (Triple.getArch() == llvm::Triple::x86)
304 TargetOptions Options;
305 getTargetOptions(Options);
306 TargetMachine *target = march->createTargetMachine(TripleStr, CPU, FeatureStr,
308 LTOModule *Ret = new LTOModule(m.take(), target);
309 if (Ret->parseSymbols(errMsg)) {
317 /// makeBuffer - Create a MemoryBuffer from a memory range.
318 MemoryBuffer *LTOModule::makeBuffer(const void *mem, size_t length) {
319 const char *startPtr = (const char*)mem;
320 return MemoryBuffer::getMemBuffer(StringRef(startPtr, length), "", false);
323 /// objcClassNameFromExpression - Get string that the data pointer points to.
325 LTOModule::objcClassNameFromExpression(const Constant *c, std::string &name) {
326 if (const ConstantExpr *ce = dyn_cast<ConstantExpr>(c)) {
327 Constant *op = ce->getOperand(0);
328 if (GlobalVariable *gvn = dyn_cast<GlobalVariable>(op)) {
329 Constant *cn = gvn->getInitializer();
330 if (ConstantDataArray *ca = dyn_cast<ConstantDataArray>(cn)) {
331 if (ca->isCString()) {
332 name = ".objc_class_name_" + ca->getAsCString().str();
341 /// addObjCClass - Parse i386/ppc ObjC class data structure.
342 void LTOModule::addObjCClass(const GlobalVariable *clgv) {
343 const ConstantStruct *c = dyn_cast<ConstantStruct>(clgv->getInitializer());
346 // second slot in __OBJC,__class is pointer to superclass name
347 std::string superclassName;
348 if (objcClassNameFromExpression(c->getOperand(1), superclassName)) {
349 NameAndAttributes info;
350 StringMap<NameAndAttributes>::value_type &entry =
351 _undefines.GetOrCreateValue(superclassName);
352 if (!entry.getValue().name) {
353 const char *symbolName = entry.getKey().data();
354 info.name = symbolName;
355 info.attributes = LTO_SYMBOL_DEFINITION_UNDEFINED;
356 info.isFunction = false;
358 entry.setValue(info);
362 // third slot in __OBJC,__class is pointer to class name
363 std::string className;
364 if (objcClassNameFromExpression(c->getOperand(2), className)) {
365 StringSet::value_type &entry = _defines.GetOrCreateValue(className);
368 NameAndAttributes info;
369 info.name = entry.getKey().data();
370 info.attributes = LTO_SYMBOL_PERMISSIONS_DATA |
371 LTO_SYMBOL_DEFINITION_REGULAR | LTO_SYMBOL_SCOPE_DEFAULT;
372 info.isFunction = false;
374 _symbols.push_back(info);
378 /// addObjCCategory - Parse i386/ppc ObjC category data structure.
379 void LTOModule::addObjCCategory(const GlobalVariable *clgv) {
380 const ConstantStruct *c = dyn_cast<ConstantStruct>(clgv->getInitializer());
383 // second slot in __OBJC,__category is pointer to target class name
384 std::string targetclassName;
385 if (!objcClassNameFromExpression(c->getOperand(1), targetclassName))
388 NameAndAttributes info;
389 StringMap<NameAndAttributes>::value_type &entry =
390 _undefines.GetOrCreateValue(targetclassName);
392 if (entry.getValue().name)
395 const char *symbolName = entry.getKey().data();
396 info.name = symbolName;
397 info.attributes = LTO_SYMBOL_DEFINITION_UNDEFINED;
398 info.isFunction = false;
400 entry.setValue(info);
403 /// addObjCClassRef - Parse i386/ppc ObjC class list data structure.
404 void LTOModule::addObjCClassRef(const GlobalVariable *clgv) {
405 std::string targetclassName;
406 if (!objcClassNameFromExpression(clgv->getInitializer(), targetclassName))
409 NameAndAttributes info;
410 StringMap<NameAndAttributes>::value_type &entry =
411 _undefines.GetOrCreateValue(targetclassName);
412 if (entry.getValue().name)
415 const char *symbolName = entry.getKey().data();
416 info.name = symbolName;
417 info.attributes = LTO_SYMBOL_DEFINITION_UNDEFINED;
418 info.isFunction = false;
420 entry.setValue(info);
423 /// addDefinedDataSymbol - Add a data symbol as defined to the list.
424 void LTOModule::addDefinedDataSymbol(const GlobalValue *v) {
425 // Add to list of defined symbols.
426 addDefinedSymbol(v, false);
428 if (!v->hasSection() /* || !isTargetDarwin */)
431 // Special case i386/ppc ObjC data structures in magic sections:
432 // The issue is that the old ObjC object format did some strange
433 // contortions to avoid real linker symbols. For instance, the
434 // ObjC class data structure is allocated statically in the executable
435 // that defines that class. That data structures contains a pointer to
436 // its superclass. But instead of just initializing that part of the
437 // struct to the address of its superclass, and letting the static and
438 // dynamic linkers do the rest, the runtime works by having that field
439 // instead point to a C-string that is the name of the superclass.
440 // At runtime the objc initialization updates that pointer and sets
441 // it to point to the actual super class. As far as the linker
442 // knows it is just a pointer to a string. But then someone wanted the
443 // linker to issue errors at build time if the superclass was not found.
444 // So they figured out a way in mach-o object format to use an absolute
445 // symbols (.objc_class_name_Foo = 0) and a floating reference
446 // (.reference .objc_class_name_Bar) to cause the linker into erroring when
447 // a class was missing.
448 // The following synthesizes the implicit .objc_* symbols for the linker
449 // from the ObjC data structures generated by the front end.
451 // special case if this data blob is an ObjC class definition
452 if (v->getSection().compare(0, 15, "__OBJC,__class,") == 0) {
453 if (const GlobalVariable *gv = dyn_cast<GlobalVariable>(v)) {
458 // special case if this data blob is an ObjC category definition
459 else if (v->getSection().compare(0, 18, "__OBJC,__category,") == 0) {
460 if (const GlobalVariable *gv = dyn_cast<GlobalVariable>(v)) {
465 // special case if this data blob is the list of referenced classes
466 else if (v->getSection().compare(0, 18, "__OBJC,__cls_refs,") == 0) {
467 if (const GlobalVariable *gv = dyn_cast<GlobalVariable>(v)) {
473 /// addDefinedFunctionSymbol - Add a function symbol as defined to the list.
474 void LTOModule::addDefinedFunctionSymbol(const Function *f) {
475 // add to list of defined symbols
476 addDefinedSymbol(f, true);
479 /// addDefinedSymbol - Add a defined symbol to the list.
480 void LTOModule::addDefinedSymbol(const GlobalValue *def, bool isFunction) {
481 // ignore all llvm.* symbols
482 if (def->getName().startswith("llvm."))
485 // string is owned by _defines
486 SmallString<64> Buffer;
487 _mangler.getNameWithPrefix(Buffer, def, false);
489 // set alignment part log2() can have rounding errors
490 uint32_t align = def->getAlignment();
491 uint32_t attr = align ? countTrailingZeros(def->getAlignment()) : 0;
493 // set permissions part
495 attr |= LTO_SYMBOL_PERMISSIONS_CODE;
497 const GlobalVariable *gv = dyn_cast<GlobalVariable>(def);
498 if (gv && gv->isConstant())
499 attr |= LTO_SYMBOL_PERMISSIONS_RODATA;
501 attr |= LTO_SYMBOL_PERMISSIONS_DATA;
504 // set definition part
505 if (def->hasWeakLinkage() || def->hasLinkOnceLinkage() ||
506 def->hasLinkerPrivateWeakLinkage())
507 attr |= LTO_SYMBOL_DEFINITION_WEAK;
508 else if (def->hasCommonLinkage())
509 attr |= LTO_SYMBOL_DEFINITION_TENTATIVE;
511 attr |= LTO_SYMBOL_DEFINITION_REGULAR;
514 if (def->hasHiddenVisibility())
515 attr |= LTO_SYMBOL_SCOPE_HIDDEN;
516 else if (def->hasProtectedVisibility())
517 attr |= LTO_SYMBOL_SCOPE_PROTECTED;
518 else if (def->hasExternalLinkage() || def->hasWeakLinkage() ||
519 def->hasLinkOnceLinkage() || def->hasCommonLinkage() ||
520 def->hasLinkerPrivateWeakLinkage())
521 attr |= LTO_SYMBOL_SCOPE_DEFAULT;
522 else if (def->hasLinkOnceODRAutoHideLinkage())
523 attr |= LTO_SYMBOL_SCOPE_DEFAULT_CAN_BE_HIDDEN;
525 attr |= LTO_SYMBOL_SCOPE_INTERNAL;
527 StringSet::value_type &entry = _defines.GetOrCreateValue(Buffer);
530 // fill information structure
531 NameAndAttributes info;
532 StringRef Name = entry.getKey();
533 info.name = Name.data();
534 assert(info.name[Name.size()] == '\0');
535 info.attributes = attr;
536 info.isFunction = isFunction;
539 // add to table of symbols
540 _symbols.push_back(info);
543 /// addAsmGlobalSymbol - Add a global symbol from module-level ASM to the
545 void LTOModule::addAsmGlobalSymbol(const char *name,
546 lto_symbol_attributes scope) {
547 StringSet::value_type &entry = _defines.GetOrCreateValue(name);
549 // only add new define if not already defined
550 if (entry.getValue())
555 NameAndAttributes &info = _undefines[entry.getKey().data()];
557 if (info.symbol == 0) {
558 // FIXME: This is trying to take care of module ASM like this:
560 // module asm ".zerofill __FOO, __foo, _bar_baz_qux, 0"
562 // but is gross and its mother dresses it funny. Have the ASM parser give us
563 // more details for this type of situation so that we're not guessing so
566 // fill information structure
567 info.name = entry.getKey().data();
569 LTO_SYMBOL_PERMISSIONS_DATA | LTO_SYMBOL_DEFINITION_REGULAR | scope;
570 info.isFunction = false;
573 // add to table of symbols
574 _symbols.push_back(info);
579 addDefinedFunctionSymbol(cast<Function>(info.symbol));
581 addDefinedDataSymbol(info.symbol);
583 _symbols.back().attributes &= ~LTO_SYMBOL_SCOPE_MASK;
584 _symbols.back().attributes |= scope;
587 /// addAsmGlobalSymbolUndef - Add a global symbol from module-level ASM to the
589 void LTOModule::addAsmGlobalSymbolUndef(const char *name) {
590 StringMap<NameAndAttributes>::value_type &entry =
591 _undefines.GetOrCreateValue(name);
593 _asm_undefines.push_back(entry.getKey().data());
595 // we already have the symbol
596 if (entry.getValue().name)
599 uint32_t attr = LTO_SYMBOL_DEFINITION_UNDEFINED;;
600 attr |= LTO_SYMBOL_SCOPE_DEFAULT;
601 NameAndAttributes info;
602 info.name = entry.getKey().data();
603 info.attributes = attr;
604 info.isFunction = false;
607 entry.setValue(info);
610 /// addPotentialUndefinedSymbol - Add a symbol which isn't defined just yet to a
611 /// list to be resolved later.
613 LTOModule::addPotentialUndefinedSymbol(const GlobalValue *decl, bool isFunc) {
614 // ignore all llvm.* symbols
615 if (decl->getName().startswith("llvm."))
618 // ignore all aliases
619 if (isa<GlobalAlias>(decl))
622 SmallString<64> name;
623 _mangler.getNameWithPrefix(name, decl, false);
625 StringMap<NameAndAttributes>::value_type &entry =
626 _undefines.GetOrCreateValue(name);
628 // we already have the symbol
629 if (entry.getValue().name)
632 NameAndAttributes info;
634 info.name = entry.getKey().data();
636 if (decl->hasExternalWeakLinkage())
637 info.attributes = LTO_SYMBOL_DEFINITION_WEAKUNDEF;
639 info.attributes = LTO_SYMBOL_DEFINITION_UNDEFINED;
641 info.isFunction = isFunc;
644 entry.setValue(info);
648 class RecordStreamer : public MCStreamer {
650 enum State { NeverSeen, Global, Defined, DefinedGlobal, Used };
653 StringMap<State> Symbols;
655 void markDefined(const MCSymbol &Symbol) {
656 State &S = Symbols[Symbol.getName()];
669 void markGlobal(const MCSymbol &Symbol) {
670 State &S = Symbols[Symbol.getName()];
684 void markUsed(const MCSymbol &Symbol) {
685 State &S = Symbols[Symbol.getName()];
699 // FIXME: mostly copied for the obj streamer.
700 void AddValueSymbols(const MCExpr *Value) {
701 switch (Value->getKind()) {
703 // FIXME: What should we do in here?
706 case MCExpr::Constant:
709 case MCExpr::Binary: {
710 const MCBinaryExpr *BE = cast<MCBinaryExpr>(Value);
711 AddValueSymbols(BE->getLHS());
712 AddValueSymbols(BE->getRHS());
716 case MCExpr::SymbolRef:
717 markUsed(cast<MCSymbolRefExpr>(Value)->getSymbol());
721 AddValueSymbols(cast<MCUnaryExpr>(Value)->getSubExpr());
727 typedef StringMap<State>::const_iterator const_iterator;
729 const_iterator begin() {
730 return Symbols.begin();
733 const_iterator end() {
734 return Symbols.end();
737 RecordStreamer(MCContext &Context)
738 : MCStreamer(SK_RecordStreamer, Context) {}
740 virtual void EmitInstruction(const MCInst &Inst) {
742 for (unsigned i = Inst.getNumOperands(); i--; )
743 if (Inst.getOperand(i).isExpr())
744 AddValueSymbols(Inst.getOperand(i).getExpr());
746 virtual void EmitLabel(MCSymbol *Symbol) {
747 Symbol->setSection(*getCurrentSection().first);
748 markDefined(*Symbol);
750 virtual void EmitDebugLabel(MCSymbol *Symbol) {
753 virtual void EmitAssignment(MCSymbol *Symbol, const MCExpr *Value) {
754 // FIXME: should we handle aliases?
755 markDefined(*Symbol);
757 virtual void EmitSymbolAttribute(MCSymbol *Symbol, MCSymbolAttr Attribute) {
758 if (Attribute == MCSA_Global)
761 virtual void EmitZerofill(const MCSection *Section, MCSymbol *Symbol,
762 uint64_t Size , unsigned ByteAlignment) {
763 markDefined(*Symbol);
765 virtual void EmitCommonSymbol(MCSymbol *Symbol, uint64_t Size,
766 unsigned ByteAlignment) {
767 markDefined(*Symbol);
770 virtual void EmitBundleAlignMode(unsigned AlignPow2) {}
771 virtual void EmitBundleLock(bool AlignToEnd) {}
772 virtual void EmitBundleUnlock() {}
775 virtual void ChangeSection(const MCSection *Section,
776 const MCExpr *Subsection) {}
777 virtual void InitToTextSection() {}
778 virtual void InitSections() {}
779 virtual void EmitAssemblerFlag(MCAssemblerFlag Flag) {}
780 virtual void EmitThumbFunc(MCSymbol *Func) {}
781 virtual void EmitSymbolDesc(MCSymbol *Symbol, unsigned DescValue) {}
782 virtual void EmitWeakReference(MCSymbol *Alias, const MCSymbol *Symbol) {}
783 virtual void BeginCOFFSymbolDef(const MCSymbol *Symbol) {}
784 virtual void EmitCOFFSymbolStorageClass(int StorageClass) {}
785 virtual void EmitCOFFSymbolType(int Type) {}
786 virtual void EndCOFFSymbolDef() {}
787 virtual void EmitELFSize(MCSymbol *Symbol, const MCExpr *Value) {}
788 virtual void EmitLocalCommonSymbol(MCSymbol *Symbol, uint64_t Size,
789 unsigned ByteAlignment) {}
790 virtual void EmitTBSSSymbol(const MCSection *Section, MCSymbol *Symbol,
791 uint64_t Size, unsigned ByteAlignment) {}
792 virtual void EmitBytes(StringRef Data, unsigned AddrSpace) {}
793 virtual void EmitValueImpl(const MCExpr *Value, unsigned Size,
794 unsigned AddrSpace) {}
795 virtual void EmitULEB128Value(const MCExpr *Value) {}
796 virtual void EmitSLEB128Value(const MCExpr *Value) {}
797 virtual void EmitValueToAlignment(unsigned ByteAlignment, int64_t Value,
799 unsigned MaxBytesToEmit) {}
800 virtual void EmitCodeAlignment(unsigned ByteAlignment,
801 unsigned MaxBytesToEmit) {}
802 virtual bool EmitValueToOffset(const MCExpr *Offset,
803 unsigned char Value ) { return false; }
804 virtual void EmitFileDirective(StringRef Filename) {}
805 virtual void EmitDwarfAdvanceLineAddr(int64_t LineDelta,
806 const MCSymbol *LastLabel,
807 const MCSymbol *Label,
808 unsigned PointerSize) {}
809 virtual void FinishImpl() {}
811 static bool classof(const MCStreamer *S) {
812 return S->getKind() == SK_RecordStreamer;
815 } // end anonymous namespace
817 /// addAsmGlobalSymbols - Add global symbols from module-level ASM to the
818 /// defined or undefined lists.
819 bool LTOModule::addAsmGlobalSymbols(std::string &errMsg) {
820 const std::string &inlineAsm = _module->getModuleInlineAsm();
821 if (inlineAsm.empty())
824 OwningPtr<RecordStreamer> Streamer(new RecordStreamer(_context));
825 MemoryBuffer *Buffer = MemoryBuffer::getMemBuffer(inlineAsm);
827 SrcMgr.AddNewSourceBuffer(Buffer, SMLoc());
828 OwningPtr<MCAsmParser> Parser(createMCAsmParser(SrcMgr,
830 *_target->getMCAsmInfo()));
831 const Target &T = _target->getTarget();
832 OwningPtr<MCSubtargetInfo>
833 STI(T.createMCSubtargetInfo(_target->getTargetTriple(),
834 _target->getTargetCPU(),
835 _target->getTargetFeatureString()));
836 OwningPtr<MCTargetAsmParser> TAP(T.createMCAsmParser(*STI, *Parser.get()));
838 errMsg = "target " + std::string(T.getName()) +
839 " does not define AsmParser.";
843 Parser->setTargetParser(*TAP);
844 if (Parser->Run(false))
847 for (RecordStreamer::const_iterator i = Streamer->begin(),
848 e = Streamer->end(); i != e; ++i) {
849 StringRef Key = i->first();
850 RecordStreamer::State Value = i->second;
851 if (Value == RecordStreamer::DefinedGlobal)
852 addAsmGlobalSymbol(Key.data(), LTO_SYMBOL_SCOPE_DEFAULT);
853 else if (Value == RecordStreamer::Defined)
854 addAsmGlobalSymbol(Key.data(), LTO_SYMBOL_SCOPE_INTERNAL);
855 else if (Value == RecordStreamer::Global ||
856 Value == RecordStreamer::Used)
857 addAsmGlobalSymbolUndef(Key.data());
863 /// isDeclaration - Return 'true' if the global value is a declaration.
864 static bool isDeclaration(const GlobalValue &V) {
865 if (V.hasAvailableExternallyLinkage())
868 if (V.isMaterializable())
871 return V.isDeclaration();
874 /// parseSymbols - Parse the symbols from the module and model-level ASM and add
875 /// them to either the defined or undefined lists.
876 bool LTOModule::parseSymbols(std::string &errMsg) {
878 for (Module::iterator f = _module->begin(), e = _module->end(); f != e; ++f) {
879 if (isDeclaration(*f))
880 addPotentialUndefinedSymbol(f, true);
882 addDefinedFunctionSymbol(f);
886 for (Module::global_iterator v = _module->global_begin(),
887 e = _module->global_end(); v != e; ++v) {
888 if (isDeclaration(*v))
889 addPotentialUndefinedSymbol(v, false);
891 addDefinedDataSymbol(v);
895 if (addAsmGlobalSymbols(errMsg))
899 for (Module::alias_iterator a = _module->alias_begin(),
900 e = _module->alias_end(); a != e; ++a) {
901 if (isDeclaration(*a->getAliasedGlobal()))
902 // Is an alias to a declaration.
903 addPotentialUndefinedSymbol(a, false);
905 addDefinedDataSymbol(a);
908 // make symbols for all undefines
909 for (StringMap<NameAndAttributes>::iterator u =_undefines.begin(),
910 e = _undefines.end(); u != e; ++u) {
911 // If this symbol also has a definition, then don't make an undefine because
912 // it is a tentative definition.
913 if (_defines.count(u->getKey())) continue;
914 NameAndAttributes info = u->getValue();
915 _symbols.push_back(info);