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/Triple.h"
17 #include "llvm/Bitcode/ReaderWriter.h"
18 #include "llvm/IR/Constants.h"
19 #include "llvm/IR/LLVMContext.h"
20 #include "llvm/IR/Metadata.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/MCSection.h"
27 #include "llvm/MC/MCStreamer.h"
28 #include "llvm/MC/MCSubtargetInfo.h"
29 #include "llvm/MC/MCSymbol.h"
30 #include "llvm/MC/MCTargetAsmParser.h"
31 #include "llvm/MC/SubtargetFeature.h"
32 #include "llvm/Support/CommandLine.h"
33 #include "llvm/Support/FileSystem.h"
34 #include "llvm/Support/Host.h"
35 #include "llvm/Support/MemoryBuffer.h"
36 #include "llvm/Support/Path.h"
37 #include "llvm/Support/SourceMgr.h"
38 #include "llvm/Support/TargetRegistry.h"
39 #include "llvm/Support/TargetSelect.h"
40 #include "llvm/Support/system_error.h"
41 #include "llvm/Target/TargetLowering.h"
42 #include "llvm/Target/TargetLoweringObjectFile.h"
43 #include "llvm/Target/TargetRegisterInfo.h"
44 #include "llvm/Transforms/Utils/GlobalStatus.h"
47 LTOModule::LTOModule(llvm::Module *m, llvm::TargetMachine *t)
48 : _module(m), _target(t),
49 _context(_target->getMCAsmInfo(), _target->getRegisterInfo(), &ObjFileInfo),
50 _mangler(t->getDataLayout()) {
51 ObjFileInfo.InitMCObjectFileInfo(t->getTargetTriple(),
52 t->getRelocationModel(), t->getCodeModel(),
56 /// isBitcodeFile - Returns 'true' if the file (or memory contents) is LLVM
58 bool LTOModule::isBitcodeFile(const void *mem, size_t length) {
59 return sys::fs::identify_magic(StringRef((const char *)mem, length)) ==
60 sys::fs::file_magic::bitcode;
63 bool LTOModule::isBitcodeFile(const char *path) {
64 sys::fs::file_magic type;
65 if (sys::fs::identify_magic(path, type))
67 return type == sys::fs::file_magic::bitcode;
70 /// isBitcodeFileForTarget - Returns 'true' if the file (or memory contents) is
71 /// LLVM bitcode for the specified triple.
72 bool LTOModule::isBitcodeFileForTarget(const void *mem, size_t length,
73 const char *triplePrefix) {
74 MemoryBuffer *buffer = makeBuffer(mem, length);
77 return isTargetMatch(buffer, triplePrefix);
80 bool LTOModule::isBitcodeFileForTarget(const char *path,
81 const char *triplePrefix) {
82 std::unique_ptr<MemoryBuffer> buffer;
83 if (MemoryBuffer::getFile(path, buffer))
85 return isTargetMatch(buffer.release(), triplePrefix);
88 /// isTargetMatch - Returns 'true' if the memory buffer is for the specified
90 bool LTOModule::isTargetMatch(MemoryBuffer *buffer, const char *triplePrefix) {
91 std::string Triple = getBitcodeTargetTriple(buffer, getGlobalContext());
93 return strncmp(Triple.c_str(), triplePrefix, strlen(triplePrefix)) == 0;
96 /// makeLTOModule - Create an LTOModule. N.B. These methods take ownership of
98 LTOModule *LTOModule::makeLTOModule(const char *path, TargetOptions options,
99 std::string &errMsg) {
100 std::unique_ptr<MemoryBuffer> buffer;
101 if (error_code ec = MemoryBuffer::getFile(path, buffer)) {
102 errMsg = ec.message();
105 return makeLTOModule(buffer.release(), options, errMsg);
108 LTOModule *LTOModule::makeLTOModule(int fd, const char *path,
109 size_t size, TargetOptions options,
110 std::string &errMsg) {
111 return makeLTOModule(fd, path, size, 0, options, errMsg);
114 LTOModule *LTOModule::makeLTOModule(int fd, const char *path,
117 TargetOptions options,
118 std::string &errMsg) {
119 std::unique_ptr<MemoryBuffer> buffer;
121 MemoryBuffer::getOpenFileSlice(fd, path, buffer, map_size, offset)) {
122 errMsg = ec.message();
125 return makeLTOModule(buffer.release(), options, errMsg);
128 LTOModule *LTOModule::makeLTOModule(const void *mem, size_t length,
129 TargetOptions options,
130 std::string &errMsg, StringRef path) {
131 std::unique_ptr<MemoryBuffer> buffer(makeBuffer(mem, length, path));
134 return makeLTOModule(buffer.release(), options, errMsg);
137 LTOModule *LTOModule::makeLTOModule(MemoryBuffer *buffer,
138 TargetOptions options,
139 std::string &errMsg) {
140 // parse bitcode buffer
141 ErrorOr<Module *> ModuleOrErr =
142 getLazyBitcodeModule(buffer, getGlobalContext());
143 if (error_code EC = ModuleOrErr.getError()) {
144 errMsg = EC.message();
148 std::unique_ptr<Module> m(ModuleOrErr.get());
150 std::string TripleStr = m->getTargetTriple();
151 if (TripleStr.empty())
152 TripleStr = sys::getDefaultTargetTriple();
153 llvm::Triple Triple(TripleStr);
155 // find machine architecture for this module
156 const Target *march = TargetRegistry::lookupTarget(TripleStr, errMsg);
160 // construct LTOModule, hand over ownership of module and target
161 SubtargetFeatures Features;
162 Features.getDefaultSubtargetFeatures(Triple);
163 std::string FeatureStr = Features.getString();
164 // Set a default CPU for Darwin triples.
166 if (Triple.isOSDarwin()) {
167 if (Triple.getArch() == llvm::Triple::x86_64)
169 else if (Triple.getArch() == llvm::Triple::x86)
173 TargetMachine *target = march->createTargetMachine(TripleStr, CPU, FeatureStr,
175 m->materializeAllPermanently();
177 LTOModule *Ret = new LTOModule(m.release(), target);
179 // We need a MCContext set up in order to get mangled names of private
180 // symbols. It is a bit odd that we need to report uses and definitions
181 // of private symbols, but it does look like ld64 expects to be informed
182 // of at least the ones with an 'l' prefix.
183 MCContext &Context = Ret->_context;
184 const TargetLoweringObjectFile &TLOF =
185 target->getTargetLowering()->getObjFileLowering();
186 const_cast<TargetLoweringObjectFile &>(TLOF).Initialize(Context, *target);
188 if (Ret->parseSymbols(errMsg)) {
193 Ret->parseMetadata();
198 /// Create a MemoryBuffer from a memory range with an optional name.
199 MemoryBuffer *LTOModule::makeBuffer(const void *mem, size_t length,
201 const char *startPtr = (const char*)mem;
202 return MemoryBuffer::getMemBuffer(StringRef(startPtr, length), name, false);
205 /// objcClassNameFromExpression - Get string that the data pointer points to.
207 LTOModule::objcClassNameFromExpression(const Constant *c, std::string &name) {
208 if (const ConstantExpr *ce = dyn_cast<ConstantExpr>(c)) {
209 Constant *op = ce->getOperand(0);
210 if (GlobalVariable *gvn = dyn_cast<GlobalVariable>(op)) {
211 Constant *cn = gvn->getInitializer();
212 if (ConstantDataArray *ca = dyn_cast<ConstantDataArray>(cn)) {
213 if (ca->isCString()) {
214 name = ".objc_class_name_" + ca->getAsCString().str();
223 /// addObjCClass - Parse i386/ppc ObjC class data structure.
224 void LTOModule::addObjCClass(const GlobalVariable *clgv) {
225 const ConstantStruct *c = dyn_cast<ConstantStruct>(clgv->getInitializer());
228 // second slot in __OBJC,__class is pointer to superclass name
229 std::string superclassName;
230 if (objcClassNameFromExpression(c->getOperand(1), superclassName)) {
231 NameAndAttributes info;
232 StringMap<NameAndAttributes>::value_type &entry =
233 _undefines.GetOrCreateValue(superclassName);
234 if (!entry.getValue().name) {
235 const char *symbolName = entry.getKey().data();
236 info.name = symbolName;
237 info.attributes = LTO_SYMBOL_DEFINITION_UNDEFINED;
238 info.isFunction = false;
240 entry.setValue(info);
244 // third slot in __OBJC,__class is pointer to class name
245 std::string className;
246 if (objcClassNameFromExpression(c->getOperand(2), className)) {
247 StringSet::value_type &entry = _defines.GetOrCreateValue(className);
250 NameAndAttributes info;
251 info.name = entry.getKey().data();
252 info.attributes = LTO_SYMBOL_PERMISSIONS_DATA |
253 LTO_SYMBOL_DEFINITION_REGULAR | LTO_SYMBOL_SCOPE_DEFAULT;
254 info.isFunction = false;
256 _symbols.push_back(info);
260 /// addObjCCategory - Parse i386/ppc ObjC category data structure.
261 void LTOModule::addObjCCategory(const GlobalVariable *clgv) {
262 const ConstantStruct *c = dyn_cast<ConstantStruct>(clgv->getInitializer());
265 // second slot in __OBJC,__category is pointer to target class name
266 std::string targetclassName;
267 if (!objcClassNameFromExpression(c->getOperand(1), targetclassName))
270 NameAndAttributes info;
271 StringMap<NameAndAttributes>::value_type &entry =
272 _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 info.isFunction = false;
282 entry.setValue(info);
285 /// addObjCClassRef - Parse i386/ppc ObjC class list data structure.
286 void LTOModule::addObjCClassRef(const GlobalVariable *clgv) {
287 std::string targetclassName;
288 if (!objcClassNameFromExpression(clgv->getInitializer(), targetclassName))
291 NameAndAttributes info;
292 StringMap<NameAndAttributes>::value_type &entry =
293 _undefines.GetOrCreateValue(targetclassName);
294 if (entry.getValue().name)
297 const char *symbolName = entry.getKey().data();
298 info.name = symbolName;
299 info.attributes = LTO_SYMBOL_DEFINITION_UNDEFINED;
300 info.isFunction = false;
302 entry.setValue(info);
305 /// addDefinedDataSymbol - Add a data symbol as defined to the list.
306 void LTOModule::addDefinedDataSymbol(const GlobalValue *v) {
307 // Add to list of defined symbols.
308 addDefinedSymbol(v, false);
310 if (!v->hasSection() /* || !isTargetDarwin */)
313 // Special case i386/ppc ObjC data structures in magic sections:
314 // The issue is that the old ObjC object format did some strange
315 // contortions to avoid real linker symbols. For instance, the
316 // ObjC class data structure is allocated statically in the executable
317 // that defines that class. That data structures contains a pointer to
318 // its superclass. But instead of just initializing that part of the
319 // struct to the address of its superclass, and letting the static and
320 // dynamic linkers do the rest, the runtime works by having that field
321 // instead point to a C-string that is the name of the superclass.
322 // At runtime the objc initialization updates that pointer and sets
323 // it to point to the actual super class. As far as the linker
324 // knows it is just a pointer to a string. But then someone wanted the
325 // linker to issue errors at build time if the superclass was not found.
326 // So they figured out a way in mach-o object format to use an absolute
327 // symbols (.objc_class_name_Foo = 0) and a floating reference
328 // (.reference .objc_class_name_Bar) to cause the linker into erroring when
329 // a class was missing.
330 // The following synthesizes the implicit .objc_* symbols for the linker
331 // from the ObjC data structures generated by the front end.
333 // special case if this data blob is an ObjC class definition
334 if (v->getSection().compare(0, 15, "__OBJC,__class,") == 0) {
335 if (const GlobalVariable *gv = dyn_cast<GlobalVariable>(v)) {
340 // special case if this data blob is an ObjC category definition
341 else if (v->getSection().compare(0, 18, "__OBJC,__category,") == 0) {
342 if (const GlobalVariable *gv = dyn_cast<GlobalVariable>(v)) {
347 // special case if this data blob is the list of referenced classes
348 else if (v->getSection().compare(0, 18, "__OBJC,__cls_refs,") == 0) {
349 if (const GlobalVariable *gv = dyn_cast<GlobalVariable>(v)) {
355 /// addDefinedFunctionSymbol - Add a function symbol as defined to the list.
356 void LTOModule::addDefinedFunctionSymbol(const Function *f) {
357 // add to list of defined symbols
358 addDefinedSymbol(f, true);
361 static bool canBeHidden(const GlobalValue *GV) {
362 // FIXME: this is duplicated with another static function in AsmPrinter.cpp
363 GlobalValue::LinkageTypes L = GV->getLinkage();
365 if (L != GlobalValue::LinkOnceODRLinkage)
368 if (GV->hasUnnamedAddr())
371 // If it is a non constant variable, it needs to be uniqued across shared
373 if (const GlobalVariable *Var = dyn_cast<GlobalVariable>(GV)) {
374 if (!Var->isConstant())
379 if (GlobalStatus::analyzeGlobal(GV, GS))
382 return !GS.IsCompared;
385 /// addDefinedSymbol - Add a defined symbol to the list.
386 void LTOModule::addDefinedSymbol(const GlobalValue *def, bool isFunction) {
387 // ignore all llvm.* symbols
388 if (def->getName().startswith("llvm."))
391 // string is owned by _defines
392 SmallString<64> Buffer;
393 _target->getNameWithPrefix(Buffer, def, _mangler);
395 // set alignment part log2() can have rounding errors
396 uint32_t align = def->getAlignment();
397 uint32_t attr = align ? countTrailingZeros(def->getAlignment()) : 0;
399 // set permissions part
401 attr |= LTO_SYMBOL_PERMISSIONS_CODE;
403 const GlobalVariable *gv = dyn_cast<GlobalVariable>(def);
404 if (gv && gv->isConstant())
405 attr |= LTO_SYMBOL_PERMISSIONS_RODATA;
407 attr |= LTO_SYMBOL_PERMISSIONS_DATA;
410 // set definition part
411 if (def->hasWeakLinkage() || def->hasLinkOnceLinkage() ||
412 def->hasLinkerPrivateWeakLinkage())
413 attr |= LTO_SYMBOL_DEFINITION_WEAK;
414 else if (def->hasCommonLinkage())
415 attr |= LTO_SYMBOL_DEFINITION_TENTATIVE;
417 attr |= LTO_SYMBOL_DEFINITION_REGULAR;
420 if (def->hasHiddenVisibility())
421 attr |= LTO_SYMBOL_SCOPE_HIDDEN;
422 else if (def->hasProtectedVisibility())
423 attr |= LTO_SYMBOL_SCOPE_PROTECTED;
424 else if (canBeHidden(def))
425 attr |= LTO_SYMBOL_SCOPE_DEFAULT_CAN_BE_HIDDEN;
426 else if (def->hasExternalLinkage() || def->hasWeakLinkage() ||
427 def->hasLinkOnceLinkage() || def->hasCommonLinkage() ||
428 def->hasLinkerPrivateWeakLinkage())
429 attr |= LTO_SYMBOL_SCOPE_DEFAULT;
431 attr |= LTO_SYMBOL_SCOPE_INTERNAL;
433 StringSet::value_type &entry = _defines.GetOrCreateValue(Buffer);
436 // fill information structure
437 NameAndAttributes info;
438 StringRef Name = entry.getKey();
439 info.name = Name.data();
440 assert(info.name[Name.size()] == '\0');
441 info.attributes = attr;
442 info.isFunction = isFunction;
445 // add to table of symbols
446 _symbols.push_back(info);
449 /// addAsmGlobalSymbol - Add a global symbol from module-level ASM to the
451 void LTOModule::addAsmGlobalSymbol(const char *name,
452 lto_symbol_attributes scope) {
453 StringSet::value_type &entry = _defines.GetOrCreateValue(name);
455 // only add new define if not already defined
456 if (entry.getValue())
461 NameAndAttributes &info = _undefines[entry.getKey().data()];
463 if (info.symbol == 0) {
464 // FIXME: This is trying to take care of module ASM like this:
466 // module asm ".zerofill __FOO, __foo, _bar_baz_qux, 0"
468 // but is gross and its mother dresses it funny. Have the ASM parser give us
469 // more details for this type of situation so that we're not guessing so
472 // fill information structure
473 info.name = entry.getKey().data();
475 LTO_SYMBOL_PERMISSIONS_DATA | LTO_SYMBOL_DEFINITION_REGULAR | scope;
476 info.isFunction = false;
479 // add to table of symbols
480 _symbols.push_back(info);
485 addDefinedFunctionSymbol(cast<Function>(info.symbol));
487 addDefinedDataSymbol(info.symbol);
489 _symbols.back().attributes &= ~LTO_SYMBOL_SCOPE_MASK;
490 _symbols.back().attributes |= scope;
493 /// addAsmGlobalSymbolUndef - Add a global symbol from module-level ASM to the
495 void LTOModule::addAsmGlobalSymbolUndef(const char *name) {
496 StringMap<NameAndAttributes>::value_type &entry =
497 _undefines.GetOrCreateValue(name);
499 _asm_undefines.push_back(entry.getKey().data());
501 // we already have the symbol
502 if (entry.getValue().name)
505 uint32_t attr = LTO_SYMBOL_DEFINITION_UNDEFINED;;
506 attr |= LTO_SYMBOL_SCOPE_DEFAULT;
507 NameAndAttributes info;
508 info.name = entry.getKey().data();
509 info.attributes = attr;
510 info.isFunction = false;
513 entry.setValue(info);
516 /// addPotentialUndefinedSymbol - Add a symbol which isn't defined just yet to a
517 /// list to be resolved later.
519 LTOModule::addPotentialUndefinedSymbol(const GlobalValue *decl, bool isFunc) {
520 // ignore all llvm.* symbols
521 if (decl->getName().startswith("llvm."))
524 // ignore all aliases
525 if (isa<GlobalAlias>(decl))
528 SmallString<64> name;
529 _target->getNameWithPrefix(name, decl, _mangler);
531 StringMap<NameAndAttributes>::value_type &entry =
532 _undefines.GetOrCreateValue(name);
534 // we already have the symbol
535 if (entry.getValue().name)
538 NameAndAttributes info;
540 info.name = entry.getKey().data();
542 if (decl->hasExternalWeakLinkage())
543 info.attributes = LTO_SYMBOL_DEFINITION_WEAKUNDEF;
545 info.attributes = LTO_SYMBOL_DEFINITION_UNDEFINED;
547 info.isFunction = isFunc;
550 entry.setValue(info);
555 class RecordStreamer : public MCStreamer {
557 enum State { NeverSeen, Global, Defined, DefinedGlobal, Used };
560 StringMap<State> Symbols;
562 void markDefined(const MCSymbol &Symbol) {
563 State &S = Symbols[Symbol.getName()];
576 void markGlobal(const MCSymbol &Symbol) {
577 State &S = Symbols[Symbol.getName()];
591 void markUsed(const MCSymbol &Symbol) {
592 State &S = Symbols[Symbol.getName()];
606 // FIXME: mostly copied for the obj streamer.
607 void AddValueSymbols(const MCExpr *Value) {
608 switch (Value->getKind()) {
610 // FIXME: What should we do in here?
613 case MCExpr::Constant:
616 case MCExpr::Binary: {
617 const MCBinaryExpr *BE = cast<MCBinaryExpr>(Value);
618 AddValueSymbols(BE->getLHS());
619 AddValueSymbols(BE->getRHS());
623 case MCExpr::SymbolRef:
624 markUsed(cast<MCSymbolRefExpr>(Value)->getSymbol());
628 AddValueSymbols(cast<MCUnaryExpr>(Value)->getSubExpr());
634 typedef StringMap<State>::const_iterator const_iterator;
636 const_iterator begin() {
637 return Symbols.begin();
640 const_iterator end() {
641 return Symbols.end();
644 RecordStreamer(MCContext &Context) : MCStreamer(Context) {}
646 virtual void EmitInstruction(const MCInst &Inst, const MCSubtargetInfo &STI) {
648 for (unsigned i = Inst.getNumOperands(); i--; )
649 if (Inst.getOperand(i).isExpr())
650 AddValueSymbols(Inst.getOperand(i).getExpr());
652 virtual void EmitLabel(MCSymbol *Symbol) {
653 Symbol->setSection(*getCurrentSection().first);
654 markDefined(*Symbol);
656 virtual void EmitDebugLabel(MCSymbol *Symbol) {
659 virtual void EmitAssignment(MCSymbol *Symbol, const MCExpr *Value) {
660 // FIXME: should we handle aliases?
661 markDefined(*Symbol);
663 virtual bool EmitSymbolAttribute(MCSymbol *Symbol, MCSymbolAttr Attribute) {
664 if (Attribute == MCSA_Global)
668 virtual void EmitZerofill(const MCSection *Section, MCSymbol *Symbol,
669 uint64_t Size , unsigned ByteAlignment) {
670 markDefined(*Symbol);
672 virtual void EmitCommonSymbol(MCSymbol *Symbol, uint64_t Size,
673 unsigned ByteAlignment) {
674 markDefined(*Symbol);
677 virtual void EmitBundleAlignMode(unsigned AlignPow2) {}
678 virtual void EmitBundleLock(bool AlignToEnd) {}
679 virtual void EmitBundleUnlock() {}
682 virtual void ChangeSection(const MCSection *Section,
683 const MCExpr *Subsection) {}
684 virtual void EmitAssemblerFlag(MCAssemblerFlag Flag) {}
685 virtual void EmitThumbFunc(MCSymbol *Func) {}
686 virtual void EmitSymbolDesc(MCSymbol *Symbol, unsigned DescValue) {}
687 virtual void EmitWeakReference(MCSymbol *Alias, const MCSymbol *Symbol) {}
688 virtual void BeginCOFFSymbolDef(const MCSymbol *Symbol) {}
689 virtual void EmitCOFFSymbolStorageClass(int StorageClass) {}
690 virtual void EmitCOFFSymbolType(int Type) {}
691 virtual void EndCOFFSymbolDef() {}
692 virtual void EmitELFSize(MCSymbol *Symbol, const MCExpr *Value) {}
693 virtual void EmitLocalCommonSymbol(MCSymbol *Symbol, uint64_t Size,
694 unsigned ByteAlignment) {}
695 virtual void EmitTBSSSymbol(const MCSection *Section, MCSymbol *Symbol,
696 uint64_t Size, unsigned ByteAlignment) {}
697 virtual void EmitBytes(StringRef Data) {}
698 virtual void EmitValueImpl(const MCExpr *Value, unsigned Size) {}
699 virtual void EmitULEB128Value(const MCExpr *Value) {}
700 virtual void EmitSLEB128Value(const MCExpr *Value) {}
701 virtual void EmitValueToAlignment(unsigned ByteAlignment, int64_t Value,
703 unsigned MaxBytesToEmit) {}
704 virtual void EmitCodeAlignment(unsigned ByteAlignment,
705 unsigned MaxBytesToEmit) {}
706 virtual bool EmitValueToOffset(const MCExpr *Offset,
707 unsigned char Value ) { return false; }
708 virtual void EmitFileDirective(StringRef Filename) {}
709 virtual void EmitDwarfAdvanceLineAddr(int64_t LineDelta,
710 const MCSymbol *LastLabel,
711 const MCSymbol *Label,
712 unsigned PointerSize) {}
713 virtual void FinishImpl() {}
714 virtual void EmitCFIEndProcImpl(MCDwarfFrameInfo &Frame) {
715 RecordProcEnd(Frame);
718 } // end anonymous namespace
720 /// addAsmGlobalSymbols - Add global symbols from module-level ASM to the
721 /// defined or undefined lists.
722 bool LTOModule::addAsmGlobalSymbols(std::string &errMsg) {
723 const std::string &inlineAsm = _module->getModuleInlineAsm();
724 if (inlineAsm.empty())
727 std::unique_ptr<RecordStreamer> Streamer(new RecordStreamer(_context));
728 MemoryBuffer *Buffer = MemoryBuffer::getMemBuffer(inlineAsm);
730 SrcMgr.AddNewSourceBuffer(Buffer, SMLoc());
731 std::unique_ptr<MCAsmParser> Parser(
732 createMCAsmParser(SrcMgr, _context, *Streamer, *_target->getMCAsmInfo()));
733 const Target &T = _target->getTarget();
734 std::unique_ptr<MCInstrInfo> MCII(T.createMCInstrInfo());
735 std::unique_ptr<MCSubtargetInfo> STI(T.createMCSubtargetInfo(
736 _target->getTargetTriple(), _target->getTargetCPU(),
737 _target->getTargetFeatureString()));
738 std::unique_ptr<MCTargetAsmParser> TAP(
739 T.createMCAsmParser(*STI, *Parser.get(), *MCII));
741 errMsg = "target " + std::string(T.getName()) +
742 " does not define AsmParser.";
746 Parser->setTargetParser(*TAP);
747 if (Parser->Run(false))
750 for (RecordStreamer::const_iterator i = Streamer->begin(),
751 e = Streamer->end(); i != e; ++i) {
752 StringRef Key = i->first();
753 RecordStreamer::State Value = i->second;
754 if (Value == RecordStreamer::DefinedGlobal)
755 addAsmGlobalSymbol(Key.data(), LTO_SYMBOL_SCOPE_DEFAULT);
756 else if (Value == RecordStreamer::Defined)
757 addAsmGlobalSymbol(Key.data(), LTO_SYMBOL_SCOPE_INTERNAL);
758 else if (Value == RecordStreamer::Global ||
759 Value == RecordStreamer::Used)
760 addAsmGlobalSymbolUndef(Key.data());
766 /// isDeclaration - Return 'true' if the global value is a declaration.
767 static bool isDeclaration(const GlobalValue &V) {
768 if (V.hasAvailableExternallyLinkage())
771 if (V.isMaterializable())
774 return V.isDeclaration();
777 /// parseSymbols - Parse the symbols from the module and model-level ASM and add
778 /// them to either the defined or undefined lists.
779 bool LTOModule::parseSymbols(std::string &errMsg) {
781 for (Module::iterator f = _module->begin(), e = _module->end(); f != e; ++f) {
782 if (isDeclaration(*f))
783 addPotentialUndefinedSymbol(f, true);
785 addDefinedFunctionSymbol(f);
789 for (Module::global_iterator v = _module->global_begin(),
790 e = _module->global_end(); v != e; ++v) {
791 if (isDeclaration(*v))
792 addPotentialUndefinedSymbol(v, false);
794 addDefinedDataSymbol(v);
798 if (addAsmGlobalSymbols(errMsg))
802 for (Module::alias_iterator a = _module->alias_begin(),
803 e = _module->alias_end(); a != e; ++a) {
804 if (isDeclaration(*a->getAliasedGlobal()))
805 // Is an alias to a declaration.
806 addPotentialUndefinedSymbol(a, false);
808 addDefinedDataSymbol(a);
811 // make symbols for all undefines
812 for (StringMap<NameAndAttributes>::iterator u =_undefines.begin(),
813 e = _undefines.end(); u != e; ++u) {
814 // If this symbol also has a definition, then don't make an undefine because
815 // it is a tentative definition.
816 if (_defines.count(u->getKey())) continue;
817 NameAndAttributes info = u->getValue();
818 _symbols.push_back(info);
824 /// parseMetadata - Parse metadata from the module
825 void LTOModule::parseMetadata() {
827 if (Value *Val = _module->getModuleFlag("Linker Options")) {
828 MDNode *LinkerOptions = cast<MDNode>(Val);
829 for (unsigned i = 0, e = LinkerOptions->getNumOperands(); i != e; ++i) {
830 MDNode *MDOptions = cast<MDNode>(LinkerOptions->getOperand(i));
831 for (unsigned ii = 0, ie = MDOptions->getNumOperands(); ii != ie; ++ii) {
832 MDString *MDOption = cast<MDString>(MDOptions->getOperand(ii));
833 StringRef Op = _linkeropt_strings.
834 GetOrCreateValue(MDOption->getString()).getKey();
835 StringRef DepLibName = _target->getTargetLowering()->
836 getObjFileLowering().getDepLibFromLinkerOpt(Op);
837 if (!DepLibName.empty())
838 _deplibs.push_back(DepLibName.data());
839 else if (!Op.empty())
840 _linkeropts.push_back(Op.data());
845 // Add other interesting metadata here.