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/Target/TargetLowering.h"
41 #include "llvm/Target/TargetLoweringObjectFile.h"
42 #include "llvm/Target/TargetRegisterInfo.h"
43 #include "llvm/Transforms/Utils/GlobalStatus.h"
44 #include <system_error>
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 (std::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;
120 if (std::error_code ec =
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 (std::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)
171 else if (Triple.getArch() == llvm::Triple::arm64 ||
172 Triple.getArch() == llvm::Triple::aarch64)
176 TargetMachine *target = march->createTargetMachine(TripleStr, CPU, FeatureStr,
178 m->materializeAllPermanently();
180 LTOModule *Ret = new LTOModule(m.release(), target);
182 // We need a MCContext set up in order to get mangled names of private
183 // symbols. It is a bit odd that we need to report uses and definitions
184 // of private symbols, but it does look like ld64 expects to be informed
185 // of at least the ones with an 'l' prefix.
186 MCContext &Context = Ret->_context;
187 const TargetLoweringObjectFile &TLOF =
188 target->getTargetLowering()->getObjFileLowering();
189 const_cast<TargetLoweringObjectFile &>(TLOF).Initialize(Context, *target);
191 if (Ret->parseSymbols(errMsg)) {
196 Ret->parseMetadata();
201 /// Create a MemoryBuffer from a memory range with an optional name.
202 MemoryBuffer *LTOModule::makeBuffer(const void *mem, size_t length,
204 const char *startPtr = (const char*)mem;
205 return MemoryBuffer::getMemBuffer(StringRef(startPtr, length), name, false);
208 /// objcClassNameFromExpression - Get string that the data pointer points to.
210 LTOModule::objcClassNameFromExpression(const Constant *c, std::string &name) {
211 if (const ConstantExpr *ce = dyn_cast<ConstantExpr>(c)) {
212 Constant *op = ce->getOperand(0);
213 if (GlobalVariable *gvn = dyn_cast<GlobalVariable>(op)) {
214 Constant *cn = gvn->getInitializer();
215 if (ConstantDataArray *ca = dyn_cast<ConstantDataArray>(cn)) {
216 if (ca->isCString()) {
217 name = ".objc_class_name_" + ca->getAsCString().str();
226 /// addObjCClass - Parse i386/ppc ObjC class data structure.
227 void LTOModule::addObjCClass(const GlobalVariable *clgv) {
228 const ConstantStruct *c = dyn_cast<ConstantStruct>(clgv->getInitializer());
231 // second slot in __OBJC,__class is pointer to superclass name
232 std::string superclassName;
233 if (objcClassNameFromExpression(c->getOperand(1), superclassName)) {
234 NameAndAttributes info;
235 StringMap<NameAndAttributes>::value_type &entry =
236 _undefines.GetOrCreateValue(superclassName);
237 if (!entry.getValue().name) {
238 const char *symbolName = entry.getKey().data();
239 info.name = symbolName;
240 info.attributes = LTO_SYMBOL_DEFINITION_UNDEFINED;
241 info.isFunction = false;
243 entry.setValue(info);
247 // third slot in __OBJC,__class is pointer to class name
248 std::string className;
249 if (objcClassNameFromExpression(c->getOperand(2), className)) {
250 StringSet::value_type &entry = _defines.GetOrCreateValue(className);
253 NameAndAttributes info;
254 info.name = entry.getKey().data();
255 info.attributes = LTO_SYMBOL_PERMISSIONS_DATA |
256 LTO_SYMBOL_DEFINITION_REGULAR | LTO_SYMBOL_SCOPE_DEFAULT;
257 info.isFunction = false;
259 _symbols.push_back(info);
263 /// addObjCCategory - Parse i386/ppc ObjC category data structure.
264 void LTOModule::addObjCCategory(const GlobalVariable *clgv) {
265 const ConstantStruct *c = dyn_cast<ConstantStruct>(clgv->getInitializer());
268 // second slot in __OBJC,__category is pointer to target class name
269 std::string targetclassName;
270 if (!objcClassNameFromExpression(c->getOperand(1), targetclassName))
273 NameAndAttributes info;
274 StringMap<NameAndAttributes>::value_type &entry =
275 _undefines.GetOrCreateValue(targetclassName);
277 if (entry.getValue().name)
280 const char *symbolName = entry.getKey().data();
281 info.name = symbolName;
282 info.attributes = LTO_SYMBOL_DEFINITION_UNDEFINED;
283 info.isFunction = false;
285 entry.setValue(info);
288 /// addObjCClassRef - Parse i386/ppc ObjC class list data structure.
289 void LTOModule::addObjCClassRef(const GlobalVariable *clgv) {
290 std::string targetclassName;
291 if (!objcClassNameFromExpression(clgv->getInitializer(), targetclassName))
294 NameAndAttributes info;
295 StringMap<NameAndAttributes>::value_type &entry =
296 _undefines.GetOrCreateValue(targetclassName);
297 if (entry.getValue().name)
300 const char *symbolName = entry.getKey().data();
301 info.name = symbolName;
302 info.attributes = LTO_SYMBOL_DEFINITION_UNDEFINED;
303 info.isFunction = false;
305 entry.setValue(info);
308 /// addDefinedDataSymbol - Add a data symbol as defined to the list.
309 void LTOModule::addDefinedDataSymbol(const GlobalValue *v) {
310 // Add to list of defined symbols.
311 addDefinedSymbol(v, false);
313 if (!v->hasSection() /* || !isTargetDarwin */)
316 // Special case i386/ppc ObjC data structures in magic sections:
317 // The issue is that the old ObjC object format did some strange
318 // contortions to avoid real linker symbols. For instance, the
319 // ObjC class data structure is allocated statically in the executable
320 // that defines that class. That data structures contains a pointer to
321 // its superclass. But instead of just initializing that part of the
322 // struct to the address of its superclass, and letting the static and
323 // dynamic linkers do the rest, the runtime works by having that field
324 // instead point to a C-string that is the name of the superclass.
325 // At runtime the objc initialization updates that pointer and sets
326 // it to point to the actual super class. As far as the linker
327 // knows it is just a pointer to a string. But then someone wanted the
328 // linker to issue errors at build time if the superclass was not found.
329 // So they figured out a way in mach-o object format to use an absolute
330 // symbols (.objc_class_name_Foo = 0) and a floating reference
331 // (.reference .objc_class_name_Bar) to cause the linker into erroring when
332 // a class was missing.
333 // The following synthesizes the implicit .objc_* symbols for the linker
334 // from the ObjC data structures generated by the front end.
336 // special case if this data blob is an ObjC class definition
337 std::string Section = v->getSection();
338 if (Section.compare(0, 15, "__OBJC,__class,") == 0) {
339 if (const GlobalVariable *gv = dyn_cast<GlobalVariable>(v)) {
344 // special case if this data blob is an ObjC category definition
345 else if (Section.compare(0, 18, "__OBJC,__category,") == 0) {
346 if (const GlobalVariable *gv = dyn_cast<GlobalVariable>(v)) {
351 // special case if this data blob is the list of referenced classes
352 else if (Section.compare(0, 18, "__OBJC,__cls_refs,") == 0) {
353 if (const GlobalVariable *gv = dyn_cast<GlobalVariable>(v)) {
359 /// addDefinedFunctionSymbol - Add a function symbol as defined to the list.
360 void LTOModule::addDefinedFunctionSymbol(const Function *f) {
361 // add to list of defined symbols
362 addDefinedSymbol(f, true);
365 static bool canBeHidden(const GlobalValue *GV) {
366 // FIXME: this is duplicated with another static function in AsmPrinter.cpp
367 GlobalValue::LinkageTypes L = GV->getLinkage();
369 if (L != GlobalValue::LinkOnceODRLinkage)
372 if (GV->hasUnnamedAddr())
375 // If it is a non constant variable, it needs to be uniqued across shared
377 if (const GlobalVariable *Var = dyn_cast<GlobalVariable>(GV)) {
378 if (!Var->isConstant())
383 if (GlobalStatus::analyzeGlobal(GV, GS))
386 return !GS.IsCompared;
389 /// addDefinedSymbol - Add a defined symbol to the list.
390 void LTOModule::addDefinedSymbol(const GlobalValue *def, bool isFunction) {
391 // ignore all llvm.* symbols
392 if (def->getName().startswith("llvm."))
395 // string is owned by _defines
396 SmallString<64> Buffer;
397 _target->getNameWithPrefix(Buffer, def, _mangler);
399 // set alignment part log2() can have rounding errors
400 uint32_t align = def->getAlignment();
401 uint32_t attr = align ? countTrailingZeros(align) : 0;
403 // set permissions part
405 attr |= LTO_SYMBOL_PERMISSIONS_CODE;
407 const GlobalVariable *gv = dyn_cast<GlobalVariable>(def);
408 if (gv && gv->isConstant())
409 attr |= LTO_SYMBOL_PERMISSIONS_RODATA;
411 attr |= LTO_SYMBOL_PERMISSIONS_DATA;
414 // set definition part
415 if (def->hasWeakLinkage() || def->hasLinkOnceLinkage())
416 attr |= LTO_SYMBOL_DEFINITION_WEAK;
417 else if (def->hasCommonLinkage())
418 attr |= LTO_SYMBOL_DEFINITION_TENTATIVE;
420 attr |= LTO_SYMBOL_DEFINITION_REGULAR;
423 if (def->hasLocalLinkage())
424 // Ignore visibility if linkage is local.
425 attr |= LTO_SYMBOL_SCOPE_INTERNAL;
426 else if (def->hasHiddenVisibility())
427 attr |= LTO_SYMBOL_SCOPE_HIDDEN;
428 else if (def->hasProtectedVisibility())
429 attr |= LTO_SYMBOL_SCOPE_PROTECTED;
430 else if (canBeHidden(def))
431 attr |= LTO_SYMBOL_SCOPE_DEFAULT_CAN_BE_HIDDEN;
433 attr |= LTO_SYMBOL_SCOPE_DEFAULT;
435 StringSet::value_type &entry = _defines.GetOrCreateValue(Buffer);
438 // fill information structure
439 NameAndAttributes info;
440 StringRef Name = entry.getKey();
441 info.name = Name.data();
442 assert(info.name[Name.size()] == '\0');
443 info.attributes = attr;
444 info.isFunction = isFunction;
447 // add to table of symbols
448 _symbols.push_back(info);
451 /// addAsmGlobalSymbol - Add a global symbol from module-level ASM to the
453 void LTOModule::addAsmGlobalSymbol(const char *name,
454 lto_symbol_attributes scope) {
455 StringSet::value_type &entry = _defines.GetOrCreateValue(name);
457 // only add new define if not already defined
458 if (entry.getValue())
463 NameAndAttributes &info = _undefines[entry.getKey().data()];
465 if (info.symbol == nullptr) {
466 // FIXME: This is trying to take care of module ASM like this:
468 // module asm ".zerofill __FOO, __foo, _bar_baz_qux, 0"
470 // but is gross and its mother dresses it funny. Have the ASM parser give us
471 // more details for this type of situation so that we're not guessing so
474 // fill information structure
475 info.name = entry.getKey().data();
477 LTO_SYMBOL_PERMISSIONS_DATA | LTO_SYMBOL_DEFINITION_REGULAR | scope;
478 info.isFunction = false;
479 info.symbol = nullptr;
481 // add to table of symbols
482 _symbols.push_back(info);
487 addDefinedFunctionSymbol(cast<Function>(info.symbol));
489 addDefinedDataSymbol(info.symbol);
491 _symbols.back().attributes &= ~LTO_SYMBOL_SCOPE_MASK;
492 _symbols.back().attributes |= scope;
495 /// addAsmGlobalSymbolUndef - Add a global symbol from module-level ASM to the
497 void LTOModule::addAsmGlobalSymbolUndef(const char *name) {
498 StringMap<NameAndAttributes>::value_type &entry =
499 _undefines.GetOrCreateValue(name);
501 _asm_undefines.push_back(entry.getKey().data());
503 // we already have the symbol
504 if (entry.getValue().name)
507 uint32_t attr = LTO_SYMBOL_DEFINITION_UNDEFINED;
508 attr |= LTO_SYMBOL_SCOPE_DEFAULT;
509 NameAndAttributes info;
510 info.name = entry.getKey().data();
511 info.attributes = attr;
512 info.isFunction = false;
513 info.symbol = nullptr;
515 entry.setValue(info);
518 /// addPotentialUndefinedSymbol - Add a symbol which isn't defined just yet to a
519 /// list to be resolved later.
521 LTOModule::addPotentialUndefinedSymbol(const GlobalValue *decl, bool isFunc) {
522 // ignore all llvm.* symbols
523 if (decl->getName().startswith("llvm."))
526 // ignore all aliases
527 if (isa<GlobalAlias>(decl))
530 SmallString<64> name;
531 _target->getNameWithPrefix(name, decl, _mangler);
533 StringMap<NameAndAttributes>::value_type &entry =
534 _undefines.GetOrCreateValue(name);
536 // we already have the symbol
537 if (entry.getValue().name)
540 NameAndAttributes info;
542 info.name = entry.getKey().data();
544 if (decl->hasExternalWeakLinkage())
545 info.attributes = LTO_SYMBOL_DEFINITION_WEAKUNDEF;
547 info.attributes = LTO_SYMBOL_DEFINITION_UNDEFINED;
549 info.isFunction = isFunc;
552 entry.setValue(info);
557 class RecordStreamer : public MCStreamer {
559 enum State { NeverSeen, Global, Defined, DefinedGlobal, Used };
562 StringMap<State> Symbols;
564 void markDefined(const MCSymbol &Symbol) {
565 State &S = Symbols[Symbol.getName()];
578 void markGlobal(const MCSymbol &Symbol) {
579 State &S = Symbols[Symbol.getName()];
593 void markUsed(const MCSymbol &Symbol) {
594 State &S = Symbols[Symbol.getName()];
608 // FIXME: mostly copied for the obj streamer.
609 void AddValueSymbols(const MCExpr *Value) {
610 switch (Value->getKind()) {
612 // FIXME: What should we do in here?
615 case MCExpr::Constant:
618 case MCExpr::Binary: {
619 const MCBinaryExpr *BE = cast<MCBinaryExpr>(Value);
620 AddValueSymbols(BE->getLHS());
621 AddValueSymbols(BE->getRHS());
625 case MCExpr::SymbolRef:
626 markUsed(cast<MCSymbolRefExpr>(Value)->getSymbol());
630 AddValueSymbols(cast<MCUnaryExpr>(Value)->getSubExpr());
636 typedef StringMap<State>::const_iterator const_iterator;
638 const_iterator begin() {
639 return Symbols.begin();
642 const_iterator end() {
643 return Symbols.end();
646 RecordStreamer(MCContext &Context) : MCStreamer(Context) {}
648 void EmitInstruction(const MCInst &Inst,
649 const MCSubtargetInfo &STI) override {
651 for (unsigned i = Inst.getNumOperands(); i--; )
652 if (Inst.getOperand(i).isExpr())
653 AddValueSymbols(Inst.getOperand(i).getExpr());
655 void EmitLabel(MCSymbol *Symbol) override {
656 Symbol->setSection(*getCurrentSection().first);
657 markDefined(*Symbol);
659 void EmitDebugLabel(MCSymbol *Symbol) override {
662 void EmitAssignment(MCSymbol *Symbol, const MCExpr *Value) override {
663 // FIXME: should we handle aliases?
664 markDefined(*Symbol);
665 AddValueSymbols(Value);
667 bool EmitSymbolAttribute(MCSymbol *Symbol,
668 MCSymbolAttr Attribute) override {
669 if (Attribute == MCSA_Global)
673 void EmitZerofill(const MCSection *Section, MCSymbol *Symbol,
674 uint64_t Size , unsigned ByteAlignment) override {
675 markDefined(*Symbol);
677 void EmitCommonSymbol(MCSymbol *Symbol, uint64_t Size,
678 unsigned ByteAlignment) override {
679 markDefined(*Symbol);
682 void EmitBundleAlignMode(unsigned AlignPow2) override {}
683 void EmitBundleLock(bool AlignToEnd) override {}
684 void EmitBundleUnlock() override {}
687 void ChangeSection(const MCSection *Section,
688 const MCExpr *Subsection) override {}
689 void EmitAssemblerFlag(MCAssemblerFlag Flag) override {}
690 void EmitThumbFunc(MCSymbol *Func) override {}
691 void EmitSymbolDesc(MCSymbol *Symbol, unsigned DescValue) override {}
692 void EmitWeakReference(MCSymbol *Alias, const MCSymbol *Symbol) override {}
693 void BeginCOFFSymbolDef(const MCSymbol *Symbol) override {}
694 void EmitCOFFSymbolStorageClass(int StorageClass) override {}
695 void EmitCOFFSymbolType(int Type) override {}
696 void EndCOFFSymbolDef() override {}
697 void EmitELFSize(MCSymbol *Symbol, const MCExpr *Value) override {}
698 void EmitLocalCommonSymbol(MCSymbol *Symbol, uint64_t Size,
699 unsigned ByteAlignment) override {}
700 void EmitTBSSSymbol(const MCSection *Section, MCSymbol *Symbol,
701 uint64_t Size, unsigned ByteAlignment) override {}
702 void EmitBytes(StringRef Data) override {}
703 void EmitValueImpl(const MCExpr *Value, unsigned Size,
704 const SMLoc &Loc) override {}
705 void EmitULEB128Value(const MCExpr *Value) override {}
706 void EmitSLEB128Value(const MCExpr *Value) override {}
707 void EmitValueToAlignment(unsigned ByteAlignment, int64_t Value,
709 unsigned MaxBytesToEmit) override {}
710 void EmitCodeAlignment(unsigned ByteAlignment,
711 unsigned MaxBytesToEmit) override {}
712 bool EmitValueToOffset(const MCExpr *Offset,
713 unsigned char Value) override { return false; }
714 void EmitFileDirective(StringRef Filename) override {}
715 void FinishImpl() override {}
716 void EmitCFIEndProcImpl(MCDwarfFrameInfo &Frame) override {
717 RecordProcEnd(Frame);
720 } // end anonymous namespace
722 /// addAsmGlobalSymbols - Add global symbols from module-level ASM to the
723 /// defined or undefined lists.
724 bool LTOModule::addAsmGlobalSymbols(std::string &errMsg) {
725 const std::string &inlineAsm = _module->getModuleInlineAsm();
726 if (inlineAsm.empty())
729 std::unique_ptr<RecordStreamer> Streamer(new RecordStreamer(_context));
730 MemoryBuffer *Buffer = MemoryBuffer::getMemBuffer(inlineAsm);
732 SrcMgr.AddNewSourceBuffer(Buffer, SMLoc());
733 std::unique_ptr<MCAsmParser> Parser(
734 createMCAsmParser(SrcMgr, _context, *Streamer, *_target->getMCAsmInfo()));
735 const Target &T = _target->getTarget();
736 std::unique_ptr<MCInstrInfo> MCII(T.createMCInstrInfo());
737 std::unique_ptr<MCSubtargetInfo> STI(T.createMCSubtargetInfo(
738 _target->getTargetTriple(), _target->getTargetCPU(),
739 _target->getTargetFeatureString()));
740 std::unique_ptr<MCTargetAsmParser> TAP(
741 T.createMCAsmParser(*STI, *Parser.get(), *MCII,
742 _target->Options.MCOptions));
744 errMsg = "target " + std::string(T.getName()) +
745 " does not define AsmParser.";
749 Parser->setTargetParser(*TAP);
750 if (Parser->Run(false))
753 for (RecordStreamer::const_iterator i = Streamer->begin(),
754 e = Streamer->end(); i != e; ++i) {
755 StringRef Key = i->first();
756 RecordStreamer::State Value = i->second;
757 if (Value == RecordStreamer::DefinedGlobal)
758 addAsmGlobalSymbol(Key.data(), LTO_SYMBOL_SCOPE_DEFAULT);
759 else if (Value == RecordStreamer::Defined)
760 addAsmGlobalSymbol(Key.data(), LTO_SYMBOL_SCOPE_INTERNAL);
761 else if (Value == RecordStreamer::Global ||
762 Value == RecordStreamer::Used)
763 addAsmGlobalSymbolUndef(Key.data());
769 /// isDeclaration - Return 'true' if the global value is a declaration.
770 static bool isDeclaration(const GlobalValue &V) {
771 if (V.hasAvailableExternallyLinkage())
774 if (V.isMaterializable())
777 return V.isDeclaration();
780 /// parseSymbols - Parse the symbols from the module and model-level ASM and add
781 /// them to either the defined or undefined lists.
782 bool LTOModule::parseSymbols(std::string &errMsg) {
784 for (Module::iterator f = _module->begin(), e = _module->end(); f != e; ++f) {
785 if (isDeclaration(*f))
786 addPotentialUndefinedSymbol(f, true);
788 addDefinedFunctionSymbol(f);
792 for (Module::global_iterator v = _module->global_begin(),
793 e = _module->global_end(); v != e; ++v) {
794 if (isDeclaration(*v))
795 addPotentialUndefinedSymbol(v, false);
797 addDefinedDataSymbol(v);
801 if (addAsmGlobalSymbols(errMsg))
805 for (const auto &Alias : _module->aliases())
806 addDefinedDataSymbol(&Alias);
808 // make symbols for all undefines
809 for (StringMap<NameAndAttributes>::iterator u =_undefines.begin(),
810 e = _undefines.end(); u != e; ++u) {
811 // If this symbol also has a definition, then don't make an undefine because
812 // it is a tentative definition.
813 if (_defines.count(u->getKey())) continue;
814 NameAndAttributes info = u->getValue();
815 _symbols.push_back(info);
821 /// parseMetadata - Parse metadata from the module
822 void LTOModule::parseMetadata() {
824 if (Value *Val = _module->getModuleFlag("Linker Options")) {
825 MDNode *LinkerOptions = cast<MDNode>(Val);
826 for (unsigned i = 0, e = LinkerOptions->getNumOperands(); i != e; ++i) {
827 MDNode *MDOptions = cast<MDNode>(LinkerOptions->getOperand(i));
828 for (unsigned ii = 0, ie = MDOptions->getNumOperands(); ii != ie; ++ii) {
829 MDString *MDOption = cast<MDString>(MDOptions->getOperand(ii));
830 StringRef Op = _linkeropt_strings.
831 GetOrCreateValue(MDOption->getString()).getKey();
832 StringRef DepLibName = _target->getTargetLowering()->
833 getObjFileLowering().getDepLibFromLinkerOpt(Op);
834 if (!DepLibName.empty())
835 _deplibs.push_back(DepLibName.data());
836 else if (!Op.empty())
837 _linkeropts.push_back(Op.data());
842 // Add other interesting metadata here.