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 "llvm/LTO/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/MCInstrInfo.h"
25 #include "llvm/MC/MCParser/MCAsmParser.h"
26 #include "llvm/MC/MCStreamer.h"
27 #include "llvm/MC/MCSubtargetInfo.h"
28 #include "llvm/MC/MCSymbol.h"
29 #include "llvm/MC/MCTargetAsmParser.h"
30 #include "llvm/MC/SubtargetFeature.h"
31 #include "llvm/Support/CommandLine.h"
32 #include "llvm/Support/Host.h"
33 #include "llvm/Support/FileSystem.h"
34 #include "llvm/Support/MemoryBuffer.h"
35 #include "llvm/Support/Path.h"
36 #include "llvm/Support/SourceMgr.h"
37 #include "llvm/Support/TargetRegistry.h"
38 #include "llvm/Support/TargetSelect.h"
39 #include "llvm/Support/system_error.h"
40 #include "llvm/Target/TargetRegisterInfo.h"
44 EnableFPMAD("enable-fp-mad",
45 cl::desc("Enable less precise MAD instructions to be generated"),
49 DisableFPElim("disable-fp-elim",
50 cl::desc("Disable frame pointer elimination optimization"),
54 EnableUnsafeFPMath("enable-unsafe-fp-math",
55 cl::desc("Enable optimizations that may decrease FP precision"),
59 EnableNoInfsFPMath("enable-no-infs-fp-math",
60 cl::desc("Enable FP math optimizations that assume no +-Infs"),
64 EnableNoNaNsFPMath("enable-no-nans-fp-math",
65 cl::desc("Enable FP math optimizations that assume no NaNs"),
69 EnableHonorSignDependentRoundingFPMath("enable-sign-dependent-rounding-fp-math",
71 cl::desc("Force codegen to assume rounding mode can change dynamically"),
75 GenerateSoftFloatCalls("soft-float",
76 cl::desc("Generate software floating point library calls"),
79 static cl::opt<llvm::FloatABI::ABIType>
80 FloatABIForCalls("float-abi",
81 cl::desc("Choose float ABI type"),
82 cl::init(FloatABI::Default),
84 clEnumValN(FloatABI::Default, "default",
85 "Target default float ABI type"),
86 clEnumValN(FloatABI::Soft, "soft",
87 "Soft float ABI (implied by -soft-float)"),
88 clEnumValN(FloatABI::Hard, "hard",
89 "Hard float ABI (uses FP registers)"),
92 static cl::opt<llvm::FPOpFusion::FPOpFusionMode>
93 FuseFPOps("fp-contract",
94 cl::desc("Enable aggresive formation of fused FP ops"),
95 cl::init(FPOpFusion::Standard),
97 clEnumValN(FPOpFusion::Fast, "fast",
98 "Fuse FP ops whenever profitable"),
99 clEnumValN(FPOpFusion::Standard, "on",
100 "Only fuse 'blessed' FP ops."),
101 clEnumValN(FPOpFusion::Strict, "off",
102 "Only fuse FP ops when the result won't be effected."),
106 DontPlaceZerosInBSS("nozero-initialized-in-bss",
107 cl::desc("Don't place zero-initialized symbols into bss section"),
111 EnableGuaranteedTailCallOpt("tailcallopt",
112 cl::desc("Turn fastcc calls into tail calls by (potentially) changing ABI."),
116 DisableTailCalls("disable-tail-calls",
117 cl::desc("Never emit tail calls"),
120 static cl::opt<unsigned>
121 OverrideStackAlignment("stack-alignment",
122 cl::desc("Override default stack alignment"),
125 static cl::opt<std::string>
126 TrapFuncName("trap-func", cl::Hidden,
127 cl::desc("Emit a call to trap function rather than a trap instruction"),
131 EnablePIE("enable-pie",
132 cl::desc("Assume the creation of a position independent executable."),
136 SegmentedStacks("segmented-stacks",
137 cl::desc("Use segmented stacks if possible."),
141 UseInitArray("use-init-array",
142 cl::desc("Use .init_array instead of .ctors."),
145 LTOModule::LTOModule(llvm::Module *m, llvm::TargetMachine *t)
146 : _module(m), _target(t),
147 _context(_target->getMCAsmInfo(), _target->getRegisterInfo(), NULL),
148 _mangler(_context, t) {}
150 /// isBitcodeFile - Returns 'true' if the file (or memory contents) is LLVM
152 bool LTOModule::isBitcodeFile(const void *mem, size_t length) {
153 return sys::fs::identify_magic(StringRef((const char *)mem, length)) ==
154 sys::fs::file_magic::bitcode;
157 bool LTOModule::isBitcodeFile(const char *path) {
158 sys::fs::file_magic type;
159 if (sys::fs::identify_magic(path, type))
161 return type == sys::fs::file_magic::bitcode;
164 /// isBitcodeFileForTarget - Returns 'true' if the file (or memory contents) is
165 /// LLVM bitcode for the specified triple.
166 bool LTOModule::isBitcodeFileForTarget(const void *mem, size_t length,
167 const char *triplePrefix) {
168 MemoryBuffer *buffer = makeBuffer(mem, length);
171 return isTargetMatch(buffer, triplePrefix);
174 bool LTOModule::isBitcodeFileForTarget(const char *path,
175 const char *triplePrefix) {
176 OwningPtr<MemoryBuffer> buffer;
177 if (MemoryBuffer::getFile(path, buffer))
179 return isTargetMatch(buffer.take(), triplePrefix);
182 /// isTargetMatch - Returns 'true' if the memory buffer is for the specified
184 bool LTOModule::isTargetMatch(MemoryBuffer *buffer, const char *triplePrefix) {
185 std::string Triple = getBitcodeTargetTriple(buffer, getGlobalContext());
187 return strncmp(Triple.c_str(), triplePrefix, strlen(triplePrefix)) == 0;
190 /// makeLTOModule - Create an LTOModule. N.B. These methods take ownership of
192 LTOModule *LTOModule::makeLTOModule(const char *path, std::string &errMsg) {
193 OwningPtr<MemoryBuffer> buffer;
194 if (error_code ec = MemoryBuffer::getFile(path, buffer)) {
195 errMsg = ec.message();
198 return makeLTOModule(buffer.take(), errMsg);
201 LTOModule *LTOModule::makeLTOModule(int fd, const char *path,
202 size_t size, std::string &errMsg) {
203 return makeLTOModule(fd, path, size, 0, errMsg);
206 LTOModule *LTOModule::makeLTOModule(int fd, const char *path,
209 std::string &errMsg) {
210 OwningPtr<MemoryBuffer> buffer;
212 MemoryBuffer::getOpenFileSlice(fd, path, buffer, map_size, offset)) {
213 errMsg = ec.message();
216 return makeLTOModule(buffer.take(), errMsg);
219 LTOModule *LTOModule::makeLTOModule(const void *mem, size_t length,
220 std::string &errMsg) {
221 OwningPtr<MemoryBuffer> buffer(makeBuffer(mem, length));
224 return makeLTOModule(buffer.take(), errMsg);
227 void LTOModule::getTargetOptions(TargetOptions &Options) {
228 Options.LessPreciseFPMADOption = EnableFPMAD;
229 Options.NoFramePointerElim = DisableFPElim;
230 Options.AllowFPOpFusion = FuseFPOps;
231 Options.UnsafeFPMath = EnableUnsafeFPMath;
232 Options.NoInfsFPMath = EnableNoInfsFPMath;
233 Options.NoNaNsFPMath = EnableNoNaNsFPMath;
234 Options.HonorSignDependentRoundingFPMathOption =
235 EnableHonorSignDependentRoundingFPMath;
236 Options.UseSoftFloat = GenerateSoftFloatCalls;
237 if (FloatABIForCalls != FloatABI::Default)
238 Options.FloatABIType = FloatABIForCalls;
239 Options.NoZerosInBSS = DontPlaceZerosInBSS;
240 Options.GuaranteedTailCallOpt = EnableGuaranteedTailCallOpt;
241 Options.DisableTailCalls = DisableTailCalls;
242 Options.StackAlignmentOverride = OverrideStackAlignment;
243 Options.TrapFuncName = TrapFuncName;
244 Options.PositionIndependentExecutable = EnablePIE;
245 Options.EnableSegmentedStacks = SegmentedStacks;
246 Options.UseInitArray = UseInitArray;
249 LTOModule *LTOModule::makeLTOModule(MemoryBuffer *buffer,
250 std::string &errMsg) {
251 // parse bitcode buffer
252 OwningPtr<Module> m(getLazyBitcodeModule(buffer, getGlobalContext(),
259 std::string TripleStr = m->getTargetTriple();
260 if (TripleStr.empty())
261 TripleStr = sys::getDefaultTargetTriple();
262 llvm::Triple Triple(TripleStr);
264 // find machine architecture for this module
265 const Target *march = TargetRegistry::lookupTarget(TripleStr, errMsg);
269 // construct LTOModule, hand over ownership of module and target
270 SubtargetFeatures Features;
271 Features.getDefaultSubtargetFeatures(Triple);
272 std::string FeatureStr = Features.getString();
273 // Set a default CPU for Darwin triples.
275 if (Triple.isOSDarwin()) {
276 if (Triple.getArch() == llvm::Triple::x86_64)
278 else if (Triple.getArch() == llvm::Triple::x86)
281 TargetOptions Options;
282 getTargetOptions(Options);
283 TargetMachine *target = march->createTargetMachine(TripleStr, CPU, FeatureStr,
285 LTOModule *Ret = new LTOModule(m.take(), target);
286 if (Ret->parseSymbols(errMsg)) {
294 /// makeBuffer - Create a MemoryBuffer from a memory range.
295 MemoryBuffer *LTOModule::makeBuffer(const void *mem, size_t length) {
296 const char *startPtr = (const char*)mem;
297 return MemoryBuffer::getMemBuffer(StringRef(startPtr, length), "", false);
300 /// objcClassNameFromExpression - Get string that the data pointer points to.
302 LTOModule::objcClassNameFromExpression(const Constant *c, std::string &name) {
303 if (const ConstantExpr *ce = dyn_cast<ConstantExpr>(c)) {
304 Constant *op = ce->getOperand(0);
305 if (GlobalVariable *gvn = dyn_cast<GlobalVariable>(op)) {
306 Constant *cn = gvn->getInitializer();
307 if (ConstantDataArray *ca = dyn_cast<ConstantDataArray>(cn)) {
308 if (ca->isCString()) {
309 name = ".objc_class_name_" + ca->getAsCString().str();
318 /// addObjCClass - Parse i386/ppc ObjC class data structure.
319 void LTOModule::addObjCClass(const GlobalVariable *clgv) {
320 const ConstantStruct *c = dyn_cast<ConstantStruct>(clgv->getInitializer());
323 // second slot in __OBJC,__class is pointer to superclass name
324 std::string superclassName;
325 if (objcClassNameFromExpression(c->getOperand(1), superclassName)) {
326 NameAndAttributes info;
327 StringMap<NameAndAttributes>::value_type &entry =
328 _undefines.GetOrCreateValue(superclassName);
329 if (!entry.getValue().name) {
330 const char *symbolName = entry.getKey().data();
331 info.name = symbolName;
332 info.attributes = LTO_SYMBOL_DEFINITION_UNDEFINED;
333 info.isFunction = false;
335 entry.setValue(info);
339 // third slot in __OBJC,__class is pointer to class name
340 std::string className;
341 if (objcClassNameFromExpression(c->getOperand(2), className)) {
342 StringSet::value_type &entry = _defines.GetOrCreateValue(className);
345 NameAndAttributes info;
346 info.name = entry.getKey().data();
347 info.attributes = LTO_SYMBOL_PERMISSIONS_DATA |
348 LTO_SYMBOL_DEFINITION_REGULAR | LTO_SYMBOL_SCOPE_DEFAULT;
349 info.isFunction = false;
351 _symbols.push_back(info);
355 /// addObjCCategory - Parse i386/ppc ObjC category data structure.
356 void LTOModule::addObjCCategory(const GlobalVariable *clgv) {
357 const ConstantStruct *c = dyn_cast<ConstantStruct>(clgv->getInitializer());
360 // second slot in __OBJC,__category is pointer to target class name
361 std::string targetclassName;
362 if (!objcClassNameFromExpression(c->getOperand(1), targetclassName))
365 NameAndAttributes info;
366 StringMap<NameAndAttributes>::value_type &entry =
367 _undefines.GetOrCreateValue(targetclassName);
369 if (entry.getValue().name)
372 const char *symbolName = entry.getKey().data();
373 info.name = symbolName;
374 info.attributes = LTO_SYMBOL_DEFINITION_UNDEFINED;
375 info.isFunction = false;
377 entry.setValue(info);
380 /// addObjCClassRef - Parse i386/ppc ObjC class list data structure.
381 void LTOModule::addObjCClassRef(const GlobalVariable *clgv) {
382 std::string targetclassName;
383 if (!objcClassNameFromExpression(clgv->getInitializer(), targetclassName))
386 NameAndAttributes info;
387 StringMap<NameAndAttributes>::value_type &entry =
388 _undefines.GetOrCreateValue(targetclassName);
389 if (entry.getValue().name)
392 const char *symbolName = entry.getKey().data();
393 info.name = symbolName;
394 info.attributes = LTO_SYMBOL_DEFINITION_UNDEFINED;
395 info.isFunction = false;
397 entry.setValue(info);
400 /// addDefinedDataSymbol - Add a data symbol as defined to the list.
401 void LTOModule::addDefinedDataSymbol(const GlobalValue *v) {
402 // Add to list of defined symbols.
403 addDefinedSymbol(v, false);
405 if (!v->hasSection() /* || !isTargetDarwin */)
408 // Special case i386/ppc ObjC data structures in magic sections:
409 // The issue is that the old ObjC object format did some strange
410 // contortions to avoid real linker symbols. For instance, the
411 // ObjC class data structure is allocated statically in the executable
412 // that defines that class. That data structures contains a pointer to
413 // its superclass. But instead of just initializing that part of the
414 // struct to the address of its superclass, and letting the static and
415 // dynamic linkers do the rest, the runtime works by having that field
416 // instead point to a C-string that is the name of the superclass.
417 // At runtime the objc initialization updates that pointer and sets
418 // it to point to the actual super class. As far as the linker
419 // knows it is just a pointer to a string. But then someone wanted the
420 // linker to issue errors at build time if the superclass was not found.
421 // So they figured out a way in mach-o object format to use an absolute
422 // symbols (.objc_class_name_Foo = 0) and a floating reference
423 // (.reference .objc_class_name_Bar) to cause the linker into erroring when
424 // a class was missing.
425 // The following synthesizes the implicit .objc_* symbols for the linker
426 // from the ObjC data structures generated by the front end.
428 // special case if this data blob is an ObjC class definition
429 if (v->getSection().compare(0, 15, "__OBJC,__class,") == 0) {
430 if (const GlobalVariable *gv = dyn_cast<GlobalVariable>(v)) {
435 // special case if this data blob is an ObjC category definition
436 else if (v->getSection().compare(0, 18, "__OBJC,__category,") == 0) {
437 if (const GlobalVariable *gv = dyn_cast<GlobalVariable>(v)) {
442 // special case if this data blob is the list of referenced classes
443 else if (v->getSection().compare(0, 18, "__OBJC,__cls_refs,") == 0) {
444 if (const GlobalVariable *gv = dyn_cast<GlobalVariable>(v)) {
450 /// addDefinedFunctionSymbol - Add a function symbol as defined to the list.
451 void LTOModule::addDefinedFunctionSymbol(const Function *f) {
452 // add to list of defined symbols
453 addDefinedSymbol(f, true);
456 /// addDefinedSymbol - Add a defined symbol to the list.
457 void LTOModule::addDefinedSymbol(const GlobalValue *def, bool isFunction) {
458 // ignore all llvm.* symbols
459 if (def->getName().startswith("llvm."))
462 // string is owned by _defines
463 SmallString<64> Buffer;
464 _mangler.getNameWithPrefix(Buffer, def, false);
466 // set alignment part log2() can have rounding errors
467 uint32_t align = def->getAlignment();
468 uint32_t attr = align ? countTrailingZeros(def->getAlignment()) : 0;
470 // set permissions part
472 attr |= LTO_SYMBOL_PERMISSIONS_CODE;
474 const GlobalVariable *gv = dyn_cast<GlobalVariable>(def);
475 if (gv && gv->isConstant())
476 attr |= LTO_SYMBOL_PERMISSIONS_RODATA;
478 attr |= LTO_SYMBOL_PERMISSIONS_DATA;
481 // set definition part
482 if (def->hasWeakLinkage() || def->hasLinkOnceLinkage() ||
483 def->hasLinkerPrivateWeakLinkage())
484 attr |= LTO_SYMBOL_DEFINITION_WEAK;
485 else if (def->hasCommonLinkage())
486 attr |= LTO_SYMBOL_DEFINITION_TENTATIVE;
488 attr |= LTO_SYMBOL_DEFINITION_REGULAR;
491 if (def->hasHiddenVisibility())
492 attr |= LTO_SYMBOL_SCOPE_HIDDEN;
493 else if (def->hasProtectedVisibility())
494 attr |= LTO_SYMBOL_SCOPE_PROTECTED;
495 else if (def->hasExternalLinkage() || def->hasWeakLinkage() ||
496 def->hasLinkOnceLinkage() || def->hasCommonLinkage() ||
497 def->hasLinkerPrivateWeakLinkage())
498 attr |= LTO_SYMBOL_SCOPE_DEFAULT;
499 else if (def->hasLinkOnceODRAutoHideLinkage())
500 attr |= LTO_SYMBOL_SCOPE_DEFAULT_CAN_BE_HIDDEN;
502 attr |= LTO_SYMBOL_SCOPE_INTERNAL;
504 StringSet::value_type &entry = _defines.GetOrCreateValue(Buffer);
507 // fill information structure
508 NameAndAttributes info;
509 StringRef Name = entry.getKey();
510 info.name = Name.data();
511 assert(info.name[Name.size()] == '\0');
512 info.attributes = attr;
513 info.isFunction = isFunction;
516 // add to table of symbols
517 _symbols.push_back(info);
520 /// addAsmGlobalSymbol - Add a global symbol from module-level ASM to the
522 void LTOModule::addAsmGlobalSymbol(const char *name,
523 lto_symbol_attributes scope) {
524 StringSet::value_type &entry = _defines.GetOrCreateValue(name);
526 // only add new define if not already defined
527 if (entry.getValue())
532 NameAndAttributes &info = _undefines[entry.getKey().data()];
534 if (info.symbol == 0) {
535 // FIXME: This is trying to take care of module ASM like this:
537 // module asm ".zerofill __FOO, __foo, _bar_baz_qux, 0"
539 // but is gross and its mother dresses it funny. Have the ASM parser give us
540 // more details for this type of situation so that we're not guessing so
543 // fill information structure
544 info.name = entry.getKey().data();
546 LTO_SYMBOL_PERMISSIONS_DATA | LTO_SYMBOL_DEFINITION_REGULAR | scope;
547 info.isFunction = false;
550 // add to table of symbols
551 _symbols.push_back(info);
556 addDefinedFunctionSymbol(cast<Function>(info.symbol));
558 addDefinedDataSymbol(info.symbol);
560 _symbols.back().attributes &= ~LTO_SYMBOL_SCOPE_MASK;
561 _symbols.back().attributes |= scope;
564 /// addAsmGlobalSymbolUndef - Add a global symbol from module-level ASM to the
566 void LTOModule::addAsmGlobalSymbolUndef(const char *name) {
567 StringMap<NameAndAttributes>::value_type &entry =
568 _undefines.GetOrCreateValue(name);
570 _asm_undefines.push_back(entry.getKey().data());
572 // we already have the symbol
573 if (entry.getValue().name)
576 uint32_t attr = LTO_SYMBOL_DEFINITION_UNDEFINED;;
577 attr |= LTO_SYMBOL_SCOPE_DEFAULT;
578 NameAndAttributes info;
579 info.name = entry.getKey().data();
580 info.attributes = attr;
581 info.isFunction = false;
584 entry.setValue(info);
587 /// addPotentialUndefinedSymbol - Add a symbol which isn't defined just yet to a
588 /// list to be resolved later.
590 LTOModule::addPotentialUndefinedSymbol(const GlobalValue *decl, bool isFunc) {
591 // ignore all llvm.* symbols
592 if (decl->getName().startswith("llvm."))
595 // ignore all aliases
596 if (isa<GlobalAlias>(decl))
599 SmallString<64> name;
600 _mangler.getNameWithPrefix(name, decl, false);
602 StringMap<NameAndAttributes>::value_type &entry =
603 _undefines.GetOrCreateValue(name);
605 // we already have the symbol
606 if (entry.getValue().name)
609 NameAndAttributes info;
611 info.name = entry.getKey().data();
613 if (decl->hasExternalWeakLinkage())
614 info.attributes = LTO_SYMBOL_DEFINITION_WEAKUNDEF;
616 info.attributes = LTO_SYMBOL_DEFINITION_UNDEFINED;
618 info.isFunction = isFunc;
621 entry.setValue(info);
625 class RecordStreamer : public MCStreamer {
627 enum State { NeverSeen, Global, Defined, DefinedGlobal, Used };
630 StringMap<State> Symbols;
632 void markDefined(const MCSymbol &Symbol) {
633 State &S = Symbols[Symbol.getName()];
646 void markGlobal(const MCSymbol &Symbol) {
647 State &S = Symbols[Symbol.getName()];
661 void markUsed(const MCSymbol &Symbol) {
662 State &S = Symbols[Symbol.getName()];
676 // FIXME: mostly copied for the obj streamer.
677 void AddValueSymbols(const MCExpr *Value) {
678 switch (Value->getKind()) {
680 // FIXME: What should we do in here?
683 case MCExpr::Constant:
686 case MCExpr::Binary: {
687 const MCBinaryExpr *BE = cast<MCBinaryExpr>(Value);
688 AddValueSymbols(BE->getLHS());
689 AddValueSymbols(BE->getRHS());
693 case MCExpr::SymbolRef:
694 markUsed(cast<MCSymbolRefExpr>(Value)->getSymbol());
698 AddValueSymbols(cast<MCUnaryExpr>(Value)->getSubExpr());
704 typedef StringMap<State>::const_iterator const_iterator;
706 const_iterator begin() {
707 return Symbols.begin();
710 const_iterator end() {
711 return Symbols.end();
714 RecordStreamer(MCContext &Context)
715 : MCStreamer(SK_RecordStreamer, Context) {}
717 virtual void EmitInstruction(const MCInst &Inst) {
719 for (unsigned i = Inst.getNumOperands(); i--; )
720 if (Inst.getOperand(i).isExpr())
721 AddValueSymbols(Inst.getOperand(i).getExpr());
723 virtual void EmitLabel(MCSymbol *Symbol) {
724 Symbol->setSection(*getCurrentSection().first);
725 markDefined(*Symbol);
727 virtual void EmitDebugLabel(MCSymbol *Symbol) {
730 virtual void EmitAssignment(MCSymbol *Symbol, const MCExpr *Value) {
731 // FIXME: should we handle aliases?
732 markDefined(*Symbol);
734 virtual bool EmitSymbolAttribute(MCSymbol *Symbol, MCSymbolAttr Attribute) {
735 if (Attribute == MCSA_Global)
739 virtual void EmitZerofill(const MCSection *Section, MCSymbol *Symbol,
740 uint64_t Size , unsigned ByteAlignment) {
741 markDefined(*Symbol);
743 virtual void EmitCommonSymbol(MCSymbol *Symbol, uint64_t Size,
744 unsigned ByteAlignment) {
745 markDefined(*Symbol);
748 virtual void EmitBundleAlignMode(unsigned AlignPow2) {}
749 virtual void EmitBundleLock(bool AlignToEnd) {}
750 virtual void EmitBundleUnlock() {}
753 virtual void ChangeSection(const MCSection *Section,
754 const MCExpr *Subsection) {}
755 virtual void InitToTextSection() {}
756 virtual void InitSections() {}
757 virtual void EmitAssemblerFlag(MCAssemblerFlag Flag) {}
758 virtual void EmitThumbFunc(MCSymbol *Func) {}
759 virtual void EmitSymbolDesc(MCSymbol *Symbol, unsigned DescValue) {}
760 virtual void EmitWeakReference(MCSymbol *Alias, const MCSymbol *Symbol) {}
761 virtual void BeginCOFFSymbolDef(const MCSymbol *Symbol) {}
762 virtual void EmitCOFFSymbolStorageClass(int StorageClass) {}
763 virtual void EmitCOFFSymbolType(int Type) {}
764 virtual void EndCOFFSymbolDef() {}
765 virtual void EmitELFSize(MCSymbol *Symbol, const MCExpr *Value) {}
766 virtual void EmitLocalCommonSymbol(MCSymbol *Symbol, uint64_t Size,
767 unsigned ByteAlignment) {}
768 virtual void EmitTBSSSymbol(const MCSection *Section, MCSymbol *Symbol,
769 uint64_t Size, unsigned ByteAlignment) {}
770 virtual void EmitBytes(StringRef Data) {}
771 virtual void EmitValueImpl(const MCExpr *Value, unsigned Size) {}
772 virtual void EmitULEB128Value(const MCExpr *Value) {}
773 virtual void EmitSLEB128Value(const MCExpr *Value) {}
774 virtual void EmitValueToAlignment(unsigned ByteAlignment, int64_t Value,
776 unsigned MaxBytesToEmit) {}
777 virtual void EmitCodeAlignment(unsigned ByteAlignment,
778 unsigned MaxBytesToEmit) {}
779 virtual bool EmitValueToOffset(const MCExpr *Offset,
780 unsigned char Value ) { return false; }
781 virtual void EmitFileDirective(StringRef Filename) {}
782 virtual void EmitDwarfAdvanceLineAddr(int64_t LineDelta,
783 const MCSymbol *LastLabel,
784 const MCSymbol *Label,
785 unsigned PointerSize) {}
786 virtual void FinishImpl() {}
787 virtual void EmitCFIEndProcImpl(MCDwarfFrameInfo &Frame) {
788 RecordProcEnd(Frame);
791 static bool classof(const MCStreamer *S) {
792 return S->getKind() == SK_RecordStreamer;
795 } // end anonymous namespace
797 /// addAsmGlobalSymbols - Add global symbols from module-level ASM to the
798 /// defined or undefined lists.
799 bool LTOModule::addAsmGlobalSymbols(std::string &errMsg) {
800 const std::string &inlineAsm = _module->getModuleInlineAsm();
801 if (inlineAsm.empty())
804 OwningPtr<RecordStreamer> Streamer(new RecordStreamer(_context));
805 MemoryBuffer *Buffer = MemoryBuffer::getMemBuffer(inlineAsm);
807 SrcMgr.AddNewSourceBuffer(Buffer, SMLoc());
808 OwningPtr<MCAsmParser> Parser(createMCAsmParser(SrcMgr,
810 *_target->getMCAsmInfo()));
811 const Target &T = _target->getTarget();
812 OwningPtr<MCInstrInfo> MCII(T.createMCInstrInfo());
813 OwningPtr<MCSubtargetInfo>
814 STI(T.createMCSubtargetInfo(_target->getTargetTriple(),
815 _target->getTargetCPU(),
816 _target->getTargetFeatureString()));
817 OwningPtr<MCTargetAsmParser> TAP(T.createMCAsmParser(*STI, *Parser.get(), *MCII));
819 errMsg = "target " + std::string(T.getName()) +
820 " does not define AsmParser.";
824 Parser->setTargetParser(*TAP);
825 if (Parser->Run(false))
828 for (RecordStreamer::const_iterator i = Streamer->begin(),
829 e = Streamer->end(); i != e; ++i) {
830 StringRef Key = i->first();
831 RecordStreamer::State Value = i->second;
832 if (Value == RecordStreamer::DefinedGlobal)
833 addAsmGlobalSymbol(Key.data(), LTO_SYMBOL_SCOPE_DEFAULT);
834 else if (Value == RecordStreamer::Defined)
835 addAsmGlobalSymbol(Key.data(), LTO_SYMBOL_SCOPE_INTERNAL);
836 else if (Value == RecordStreamer::Global ||
837 Value == RecordStreamer::Used)
838 addAsmGlobalSymbolUndef(Key.data());
844 /// isDeclaration - Return 'true' if the global value is a declaration.
845 static bool isDeclaration(const GlobalValue &V) {
846 if (V.hasAvailableExternallyLinkage())
849 if (V.isMaterializable())
852 return V.isDeclaration();
855 /// parseSymbols - Parse the symbols from the module and model-level ASM and add
856 /// them to either the defined or undefined lists.
857 bool LTOModule::parseSymbols(std::string &errMsg) {
859 for (Module::iterator f = _module->begin(), e = _module->end(); f != e; ++f) {
860 if (isDeclaration(*f))
861 addPotentialUndefinedSymbol(f, true);
863 addDefinedFunctionSymbol(f);
867 for (Module::global_iterator v = _module->global_begin(),
868 e = _module->global_end(); v != e; ++v) {
869 if (isDeclaration(*v))
870 addPotentialUndefinedSymbol(v, false);
872 addDefinedDataSymbol(v);
876 if (addAsmGlobalSymbols(errMsg))
880 for (Module::alias_iterator a = _module->alias_begin(),
881 e = _module->alias_end(); a != e; ++a) {
882 if (isDeclaration(*a->getAliasedGlobal()))
883 // Is an alias to a declaration.
884 addPotentialUndefinedSymbol(a, false);
886 addDefinedDataSymbol(a);
889 // make symbols for all undefines
890 for (StringMap<NameAndAttributes>::iterator u =_undefines.begin(),
891 e = _undefines.end(); u != e; ++u) {
892 // If this symbol also has a definition, then don't make an undefine because
893 // it is a tentative definition.
894 if (_defines.count(u->getKey())) continue;
895 NameAndAttributes info = u->getValue();
896 _symbols.push_back(info);