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>
46 using std::error_code;
48 LTOModule::LTOModule(llvm::Module *m, llvm::TargetMachine *t)
49 : _module(m), _target(t),
50 _context(_target->getMCAsmInfo(), _target->getRegisterInfo(), &ObjFileInfo),
51 _mangler(t->getDataLayout()) {
52 ObjFileInfo.InitMCObjectFileInfo(t->getTargetTriple(),
53 t->getRelocationModel(), t->getCodeModel(),
57 /// isBitcodeFile - Returns 'true' if the file (or memory contents) is LLVM
59 bool LTOModule::isBitcodeFile(const void *mem, size_t length) {
60 return sys::fs::identify_magic(StringRef((const char *)mem, length)) ==
61 sys::fs::file_magic::bitcode;
64 bool LTOModule::isBitcodeFile(const char *path) {
65 sys::fs::file_magic type;
66 if (sys::fs::identify_magic(path, type))
68 return type == sys::fs::file_magic::bitcode;
71 /// isBitcodeFileForTarget - Returns 'true' if the file (or memory contents) is
72 /// LLVM bitcode for the specified triple.
73 bool LTOModule::isBitcodeFileForTarget(const void *mem, size_t length,
74 const char *triplePrefix) {
75 MemoryBuffer *buffer = makeBuffer(mem, length);
78 return isTargetMatch(buffer, triplePrefix);
81 bool LTOModule::isBitcodeFileForTarget(const char *path,
82 const char *triplePrefix) {
83 std::unique_ptr<MemoryBuffer> buffer;
84 if (MemoryBuffer::getFile(path, buffer))
86 return isTargetMatch(buffer.release(), triplePrefix);
89 /// isTargetMatch - Returns 'true' if the memory buffer is for the specified
91 bool LTOModule::isTargetMatch(MemoryBuffer *buffer, const char *triplePrefix) {
92 std::string Triple = getBitcodeTargetTriple(buffer, getGlobalContext());
94 return strncmp(Triple.c_str(), triplePrefix, strlen(triplePrefix)) == 0;
97 /// makeLTOModule - Create an LTOModule. N.B. These methods take ownership of
99 LTOModule *LTOModule::makeLTOModule(const char *path, TargetOptions options,
100 std::string &errMsg) {
101 std::unique_ptr<MemoryBuffer> buffer;
102 if (error_code ec = MemoryBuffer::getFile(path, buffer)) {
103 errMsg = ec.message();
106 return makeLTOModule(buffer.release(), options, errMsg);
109 LTOModule *LTOModule::makeLTOModule(int fd, const char *path,
110 size_t size, TargetOptions options,
111 std::string &errMsg) {
112 return makeLTOModule(fd, path, size, 0, options, errMsg);
115 LTOModule *LTOModule::makeLTOModule(int fd, const char *path,
118 TargetOptions options,
119 std::string &errMsg) {
120 std::unique_ptr<MemoryBuffer> buffer;
122 MemoryBuffer::getOpenFileSlice(fd, path, buffer, map_size, offset)) {
123 errMsg = ec.message();
126 return makeLTOModule(buffer.release(), options, errMsg);
129 LTOModule *LTOModule::makeLTOModule(const void *mem, size_t length,
130 TargetOptions options,
131 std::string &errMsg, StringRef path) {
132 std::unique_ptr<MemoryBuffer> buffer(makeBuffer(mem, length, path));
135 return makeLTOModule(buffer.release(), options, errMsg);
138 LTOModule *LTOModule::makeLTOModule(MemoryBuffer *buffer,
139 TargetOptions options,
140 std::string &errMsg) {
141 // parse bitcode buffer
142 ErrorOr<Module *> ModuleOrErr =
143 getLazyBitcodeModule(buffer, getGlobalContext());
144 if (error_code EC = ModuleOrErr.getError()) {
145 errMsg = EC.message();
149 std::unique_ptr<Module> m(ModuleOrErr.get());
151 std::string TripleStr = m->getTargetTriple();
152 if (TripleStr.empty())
153 TripleStr = sys::getDefaultTargetTriple();
154 llvm::Triple Triple(TripleStr);
156 // find machine architecture for this module
157 const Target *march = TargetRegistry::lookupTarget(TripleStr, errMsg);
161 // construct LTOModule, hand over ownership of module and target
162 SubtargetFeatures Features;
163 Features.getDefaultSubtargetFeatures(Triple);
164 std::string FeatureStr = Features.getString();
165 // Set a default CPU for Darwin triples.
167 if (Triple.isOSDarwin()) {
168 if (Triple.getArch() == llvm::Triple::x86_64)
170 else if (Triple.getArch() == llvm::Triple::x86)
172 else if (Triple.getArch() == llvm::Triple::arm64 ||
173 Triple.getArch() == llvm::Triple::aarch64)
177 TargetMachine *target = march->createTargetMachine(TripleStr, CPU, FeatureStr,
179 m->materializeAllPermanently();
181 LTOModule *Ret = new LTOModule(m.release(), target);
183 // We need a MCContext set up in order to get mangled names of private
184 // symbols. It is a bit odd that we need to report uses and definitions
185 // of private symbols, but it does look like ld64 expects to be informed
186 // of at least the ones with an 'l' prefix.
187 MCContext &Context = Ret->_context;
188 const TargetLoweringObjectFile &TLOF =
189 target->getTargetLowering()->getObjFileLowering();
190 const_cast<TargetLoweringObjectFile &>(TLOF).Initialize(Context, *target);
192 if (Ret->parseSymbols(errMsg)) {
197 Ret->parseMetadata();
202 /// Create a MemoryBuffer from a memory range with an optional name.
203 MemoryBuffer *LTOModule::makeBuffer(const void *mem, size_t length,
205 const char *startPtr = (const char*)mem;
206 return MemoryBuffer::getMemBuffer(StringRef(startPtr, length), name, false);
209 /// objcClassNameFromExpression - Get string that the data pointer points to.
211 LTOModule::objcClassNameFromExpression(const Constant *c, std::string &name) {
212 if (const ConstantExpr *ce = dyn_cast<ConstantExpr>(c)) {
213 Constant *op = ce->getOperand(0);
214 if (GlobalVariable *gvn = dyn_cast<GlobalVariable>(op)) {
215 Constant *cn = gvn->getInitializer();
216 if (ConstantDataArray *ca = dyn_cast<ConstantDataArray>(cn)) {
217 if (ca->isCString()) {
218 name = ".objc_class_name_" + ca->getAsCString().str();
227 /// addObjCClass - Parse i386/ppc ObjC class data structure.
228 void LTOModule::addObjCClass(const GlobalVariable *clgv) {
229 const ConstantStruct *c = dyn_cast<ConstantStruct>(clgv->getInitializer());
232 // second slot in __OBJC,__class is pointer to superclass name
233 std::string superclassName;
234 if (objcClassNameFromExpression(c->getOperand(1), superclassName)) {
235 NameAndAttributes info;
236 StringMap<NameAndAttributes>::value_type &entry =
237 _undefines.GetOrCreateValue(superclassName);
238 if (!entry.getValue().name) {
239 const char *symbolName = entry.getKey().data();
240 info.name = symbolName;
241 info.attributes = LTO_SYMBOL_DEFINITION_UNDEFINED;
242 info.isFunction = false;
244 entry.setValue(info);
248 // third slot in __OBJC,__class is pointer to class name
249 std::string className;
250 if (objcClassNameFromExpression(c->getOperand(2), className)) {
251 StringSet::value_type &entry = _defines.GetOrCreateValue(className);
254 NameAndAttributes info;
255 info.name = entry.getKey().data();
256 info.attributes = LTO_SYMBOL_PERMISSIONS_DATA |
257 LTO_SYMBOL_DEFINITION_REGULAR | LTO_SYMBOL_SCOPE_DEFAULT;
258 info.isFunction = false;
260 _symbols.push_back(info);
264 /// addObjCCategory - Parse i386/ppc ObjC category data structure.
265 void LTOModule::addObjCCategory(const GlobalVariable *clgv) {
266 const ConstantStruct *c = dyn_cast<ConstantStruct>(clgv->getInitializer());
269 // second slot in __OBJC,__category is pointer to target class name
270 std::string targetclassName;
271 if (!objcClassNameFromExpression(c->getOperand(1), targetclassName))
274 NameAndAttributes info;
275 StringMap<NameAndAttributes>::value_type &entry =
276 _undefines.GetOrCreateValue(targetclassName);
278 if (entry.getValue().name)
281 const char *symbolName = entry.getKey().data();
282 info.name = symbolName;
283 info.attributes = LTO_SYMBOL_DEFINITION_UNDEFINED;
284 info.isFunction = false;
286 entry.setValue(info);
289 /// addObjCClassRef - Parse i386/ppc ObjC class list data structure.
290 void LTOModule::addObjCClassRef(const GlobalVariable *clgv) {
291 std::string targetclassName;
292 if (!objcClassNameFromExpression(clgv->getInitializer(), targetclassName))
295 NameAndAttributes info;
296 StringMap<NameAndAttributes>::value_type &entry =
297 _undefines.GetOrCreateValue(targetclassName);
298 if (entry.getValue().name)
301 const char *symbolName = entry.getKey().data();
302 info.name = symbolName;
303 info.attributes = LTO_SYMBOL_DEFINITION_UNDEFINED;
304 info.isFunction = false;
306 entry.setValue(info);
309 /// addDefinedDataSymbol - Add a data symbol as defined to the list.
310 void LTOModule::addDefinedDataSymbol(const GlobalValue *v) {
311 // Add to list of defined symbols.
312 addDefinedSymbol(v, false);
314 if (!v->hasSection() /* || !isTargetDarwin */)
317 // Special case i386/ppc ObjC data structures in magic sections:
318 // The issue is that the old ObjC object format did some strange
319 // contortions to avoid real linker symbols. For instance, the
320 // ObjC class data structure is allocated statically in the executable
321 // that defines that class. That data structures contains a pointer to
322 // its superclass. But instead of just initializing that part of the
323 // struct to the address of its superclass, and letting the static and
324 // dynamic linkers do the rest, the runtime works by having that field
325 // instead point to a C-string that is the name of the superclass.
326 // At runtime the objc initialization updates that pointer and sets
327 // it to point to the actual super class. As far as the linker
328 // knows it is just a pointer to a string. But then someone wanted the
329 // linker to issue errors at build time if the superclass was not found.
330 // So they figured out a way in mach-o object format to use an absolute
331 // symbols (.objc_class_name_Foo = 0) and a floating reference
332 // (.reference .objc_class_name_Bar) to cause the linker into erroring when
333 // a class was missing.
334 // The following synthesizes the implicit .objc_* symbols for the linker
335 // from the ObjC data structures generated by the front end.
337 // special case if this data blob is an ObjC class definition
338 std::string Section = v->getSection();
339 if (Section.compare(0, 15, "__OBJC,__class,") == 0) {
340 if (const GlobalVariable *gv = dyn_cast<GlobalVariable>(v)) {
345 // special case if this data blob is an ObjC category definition
346 else if (Section.compare(0, 18, "__OBJC,__category,") == 0) {
347 if (const GlobalVariable *gv = dyn_cast<GlobalVariable>(v)) {
352 // special case if this data blob is the list of referenced classes
353 else if (Section.compare(0, 18, "__OBJC,__cls_refs,") == 0) {
354 if (const GlobalVariable *gv = dyn_cast<GlobalVariable>(v)) {
360 /// addDefinedFunctionSymbol - Add a function symbol as defined to the list.
361 void LTOModule::addDefinedFunctionSymbol(const Function *f) {
362 // add to list of defined symbols
363 addDefinedSymbol(f, true);
366 static bool canBeHidden(const GlobalValue *GV) {
367 // FIXME: this is duplicated with another static function in AsmPrinter.cpp
368 GlobalValue::LinkageTypes L = GV->getLinkage();
370 if (L != GlobalValue::LinkOnceODRLinkage)
373 if (GV->hasUnnamedAddr())
376 // If it is a non constant variable, it needs to be uniqued across shared
378 if (const GlobalVariable *Var = dyn_cast<GlobalVariable>(GV)) {
379 if (!Var->isConstant())
384 if (GlobalStatus::analyzeGlobal(GV, GS))
387 return !GS.IsCompared;
390 /// addDefinedSymbol - Add a defined symbol to the list.
391 void LTOModule::addDefinedSymbol(const GlobalValue *def, bool isFunction) {
392 // ignore all llvm.* symbols
393 if (def->getName().startswith("llvm."))
396 // string is owned by _defines
397 SmallString<64> Buffer;
398 _target->getNameWithPrefix(Buffer, def, _mangler);
400 // set alignment part log2() can have rounding errors
401 uint32_t align = def->getAlignment();
402 uint32_t attr = align ? countTrailingZeros(align) : 0;
404 // set permissions part
406 attr |= LTO_SYMBOL_PERMISSIONS_CODE;
408 const GlobalVariable *gv = dyn_cast<GlobalVariable>(def);
409 if (gv && gv->isConstant())
410 attr |= LTO_SYMBOL_PERMISSIONS_RODATA;
412 attr |= LTO_SYMBOL_PERMISSIONS_DATA;
415 // set definition part
416 if (def->hasWeakLinkage() || def->hasLinkOnceLinkage())
417 attr |= LTO_SYMBOL_DEFINITION_WEAK;
418 else if (def->hasCommonLinkage())
419 attr |= LTO_SYMBOL_DEFINITION_TENTATIVE;
421 attr |= LTO_SYMBOL_DEFINITION_REGULAR;
424 if (def->hasLocalLinkage())
425 // Ignore visibility if linkage is local.
426 attr |= LTO_SYMBOL_SCOPE_INTERNAL;
427 else if (def->hasHiddenVisibility())
428 attr |= LTO_SYMBOL_SCOPE_HIDDEN;
429 else if (def->hasProtectedVisibility())
430 attr |= LTO_SYMBOL_SCOPE_PROTECTED;
431 else if (canBeHidden(def))
432 attr |= LTO_SYMBOL_SCOPE_DEFAULT_CAN_BE_HIDDEN;
434 attr |= LTO_SYMBOL_SCOPE_DEFAULT;
436 StringSet::value_type &entry = _defines.GetOrCreateValue(Buffer);
439 // fill information structure
440 NameAndAttributes info;
441 StringRef Name = entry.getKey();
442 info.name = Name.data();
443 assert(info.name[Name.size()] == '\0');
444 info.attributes = attr;
445 info.isFunction = isFunction;
448 // add to table of symbols
449 _symbols.push_back(info);
452 /// addAsmGlobalSymbol - Add a global symbol from module-level ASM to the
454 void LTOModule::addAsmGlobalSymbol(const char *name,
455 lto_symbol_attributes scope) {
456 StringSet::value_type &entry = _defines.GetOrCreateValue(name);
458 // only add new define if not already defined
459 if (entry.getValue())
464 NameAndAttributes &info = _undefines[entry.getKey().data()];
466 if (info.symbol == nullptr) {
467 // FIXME: This is trying to take care of module ASM like this:
469 // module asm ".zerofill __FOO, __foo, _bar_baz_qux, 0"
471 // but is gross and its mother dresses it funny. Have the ASM parser give us
472 // more details for this type of situation so that we're not guessing so
475 // fill information structure
476 info.name = entry.getKey().data();
478 LTO_SYMBOL_PERMISSIONS_DATA | LTO_SYMBOL_DEFINITION_REGULAR | scope;
479 info.isFunction = false;
480 info.symbol = nullptr;
482 // add to table of symbols
483 _symbols.push_back(info);
488 addDefinedFunctionSymbol(cast<Function>(info.symbol));
490 addDefinedDataSymbol(info.symbol);
492 _symbols.back().attributes &= ~LTO_SYMBOL_SCOPE_MASK;
493 _symbols.back().attributes |= scope;
496 /// addAsmGlobalSymbolUndef - Add a global symbol from module-level ASM to the
498 void LTOModule::addAsmGlobalSymbolUndef(const char *name) {
499 StringMap<NameAndAttributes>::value_type &entry =
500 _undefines.GetOrCreateValue(name);
502 _asm_undefines.push_back(entry.getKey().data());
504 // we already have the symbol
505 if (entry.getValue().name)
508 uint32_t attr = LTO_SYMBOL_DEFINITION_UNDEFINED;
509 attr |= LTO_SYMBOL_SCOPE_DEFAULT;
510 NameAndAttributes info;
511 info.name = entry.getKey().data();
512 info.attributes = attr;
513 info.isFunction = false;
514 info.symbol = nullptr;
516 entry.setValue(info);
519 /// addPotentialUndefinedSymbol - Add a symbol which isn't defined just yet to a
520 /// list to be resolved later.
522 LTOModule::addPotentialUndefinedSymbol(const GlobalValue *decl, bool isFunc) {
523 // ignore all llvm.* symbols
524 if (decl->getName().startswith("llvm."))
527 // ignore all aliases
528 if (isa<GlobalAlias>(decl))
531 SmallString<64> name;
532 _target->getNameWithPrefix(name, decl, _mangler);
534 StringMap<NameAndAttributes>::value_type &entry =
535 _undefines.GetOrCreateValue(name);
537 // we already have the symbol
538 if (entry.getValue().name)
541 NameAndAttributes info;
543 info.name = entry.getKey().data();
545 if (decl->hasExternalWeakLinkage())
546 info.attributes = LTO_SYMBOL_DEFINITION_WEAKUNDEF;
548 info.attributes = LTO_SYMBOL_DEFINITION_UNDEFINED;
550 info.isFunction = isFunc;
553 entry.setValue(info);
558 class RecordStreamer : public MCStreamer {
560 enum State { NeverSeen, Global, Defined, DefinedGlobal, Used };
563 StringMap<State> Symbols;
565 void markDefined(const MCSymbol &Symbol) {
566 State &S = Symbols[Symbol.getName()];
579 void markGlobal(const MCSymbol &Symbol) {
580 State &S = Symbols[Symbol.getName()];
594 void markUsed(const MCSymbol &Symbol) {
595 State &S = Symbols[Symbol.getName()];
609 // FIXME: mostly copied for the obj streamer.
610 void AddValueSymbols(const MCExpr *Value) {
611 switch (Value->getKind()) {
613 // FIXME: What should we do in here?
616 case MCExpr::Constant:
619 case MCExpr::Binary: {
620 const MCBinaryExpr *BE = cast<MCBinaryExpr>(Value);
621 AddValueSymbols(BE->getLHS());
622 AddValueSymbols(BE->getRHS());
626 case MCExpr::SymbolRef:
627 markUsed(cast<MCSymbolRefExpr>(Value)->getSymbol());
631 AddValueSymbols(cast<MCUnaryExpr>(Value)->getSubExpr());
637 typedef StringMap<State>::const_iterator const_iterator;
639 const_iterator begin() {
640 return Symbols.begin();
643 const_iterator end() {
644 return Symbols.end();
647 RecordStreamer(MCContext &Context) : MCStreamer(Context) {}
649 void EmitInstruction(const MCInst &Inst,
650 const MCSubtargetInfo &STI) override {
652 for (unsigned i = Inst.getNumOperands(); i--; )
653 if (Inst.getOperand(i).isExpr())
654 AddValueSymbols(Inst.getOperand(i).getExpr());
656 void EmitLabel(MCSymbol *Symbol) override {
657 Symbol->setSection(*getCurrentSection().first);
658 markDefined(*Symbol);
660 void EmitDebugLabel(MCSymbol *Symbol) override {
663 void EmitAssignment(MCSymbol *Symbol, const MCExpr *Value) override {
664 // FIXME: should we handle aliases?
665 markDefined(*Symbol);
666 AddValueSymbols(Value);
668 bool EmitSymbolAttribute(MCSymbol *Symbol,
669 MCSymbolAttr Attribute) override {
670 if (Attribute == MCSA_Global)
674 void EmitZerofill(const MCSection *Section, MCSymbol *Symbol,
675 uint64_t Size , unsigned ByteAlignment) override {
676 markDefined(*Symbol);
678 void EmitCommonSymbol(MCSymbol *Symbol, uint64_t Size,
679 unsigned ByteAlignment) override {
680 markDefined(*Symbol);
683 void EmitBundleAlignMode(unsigned AlignPow2) override {}
684 void EmitBundleLock(bool AlignToEnd) override {}
685 void EmitBundleUnlock() override {}
688 void ChangeSection(const MCSection *Section,
689 const MCExpr *Subsection) override {}
690 void EmitAssemblerFlag(MCAssemblerFlag Flag) override {}
691 void EmitThumbFunc(MCSymbol *Func) override {}
692 void EmitSymbolDesc(MCSymbol *Symbol, unsigned DescValue) override {}
693 void EmitWeakReference(MCSymbol *Alias, const MCSymbol *Symbol) override {}
694 void BeginCOFFSymbolDef(const MCSymbol *Symbol) override {}
695 void EmitCOFFSymbolStorageClass(int StorageClass) override {}
696 void EmitCOFFSymbolType(int Type) override {}
697 void EndCOFFSymbolDef() override {}
698 void EmitELFSize(MCSymbol *Symbol, const MCExpr *Value) override {}
699 void EmitLocalCommonSymbol(MCSymbol *Symbol, uint64_t Size,
700 unsigned ByteAlignment) override {}
701 void EmitTBSSSymbol(const MCSection *Section, MCSymbol *Symbol,
702 uint64_t Size, unsigned ByteAlignment) override {}
703 void EmitBytes(StringRef Data) override {}
704 void EmitValueImpl(const MCExpr *Value, unsigned Size,
705 const SMLoc &Loc) override {}
706 void EmitULEB128Value(const MCExpr *Value) override {}
707 void EmitSLEB128Value(const MCExpr *Value) override {}
708 void EmitValueToAlignment(unsigned ByteAlignment, int64_t Value,
710 unsigned MaxBytesToEmit) override {}
711 void EmitCodeAlignment(unsigned ByteAlignment,
712 unsigned MaxBytesToEmit) override {}
713 bool EmitValueToOffset(const MCExpr *Offset,
714 unsigned char Value) override { return false; }
715 void EmitFileDirective(StringRef Filename) override {}
716 void FinishImpl() override {}
717 void EmitCFIEndProcImpl(MCDwarfFrameInfo &Frame) override {
718 RecordProcEnd(Frame);
721 } // end anonymous namespace
723 /// addAsmGlobalSymbols - Add global symbols from module-level ASM to the
724 /// defined or undefined lists.
725 bool LTOModule::addAsmGlobalSymbols(std::string &errMsg) {
726 const std::string &inlineAsm = _module->getModuleInlineAsm();
727 if (inlineAsm.empty())
730 std::unique_ptr<RecordStreamer> Streamer(new RecordStreamer(_context));
731 MemoryBuffer *Buffer = MemoryBuffer::getMemBuffer(inlineAsm);
733 SrcMgr.AddNewSourceBuffer(Buffer, SMLoc());
734 std::unique_ptr<MCAsmParser> Parser(
735 createMCAsmParser(SrcMgr, _context, *Streamer, *_target->getMCAsmInfo()));
736 const Target &T = _target->getTarget();
737 std::unique_ptr<MCInstrInfo> MCII(T.createMCInstrInfo());
738 std::unique_ptr<MCSubtargetInfo> STI(T.createMCSubtargetInfo(
739 _target->getTargetTriple(), _target->getTargetCPU(),
740 _target->getTargetFeatureString()));
741 std::unique_ptr<MCTargetAsmParser> TAP(
742 T.createMCAsmParser(*STI, *Parser.get(), *MCII,
743 _target->Options.MCOptions));
745 errMsg = "target " + std::string(T.getName()) +
746 " does not define AsmParser.";
750 Parser->setTargetParser(*TAP);
751 if (Parser->Run(false))
754 for (RecordStreamer::const_iterator i = Streamer->begin(),
755 e = Streamer->end(); i != e; ++i) {
756 StringRef Key = i->first();
757 RecordStreamer::State Value = i->second;
758 if (Value == RecordStreamer::DefinedGlobal)
759 addAsmGlobalSymbol(Key.data(), LTO_SYMBOL_SCOPE_DEFAULT);
760 else if (Value == RecordStreamer::Defined)
761 addAsmGlobalSymbol(Key.data(), LTO_SYMBOL_SCOPE_INTERNAL);
762 else if (Value == RecordStreamer::Global ||
763 Value == RecordStreamer::Used)
764 addAsmGlobalSymbolUndef(Key.data());
770 /// isDeclaration - Return 'true' if the global value is a declaration.
771 static bool isDeclaration(const GlobalValue &V) {
772 if (V.hasAvailableExternallyLinkage())
775 if (V.isMaterializable())
778 return V.isDeclaration();
781 /// parseSymbols - Parse the symbols from the module and model-level ASM and add
782 /// them to either the defined or undefined lists.
783 bool LTOModule::parseSymbols(std::string &errMsg) {
785 for (Module::iterator f = _module->begin(), e = _module->end(); f != e; ++f) {
786 if (isDeclaration(*f))
787 addPotentialUndefinedSymbol(f, true);
789 addDefinedFunctionSymbol(f);
793 for (Module::global_iterator v = _module->global_begin(),
794 e = _module->global_end(); v != e; ++v) {
795 if (isDeclaration(*v))
796 addPotentialUndefinedSymbol(v, false);
798 addDefinedDataSymbol(v);
802 if (addAsmGlobalSymbols(errMsg))
806 for (const auto &Alias : _module->aliases())
807 addDefinedDataSymbol(&Alias);
809 // make symbols for all undefines
810 for (StringMap<NameAndAttributes>::iterator u =_undefines.begin(),
811 e = _undefines.end(); u != e; ++u) {
812 // If this symbol also has a definition, then don't make an undefine because
813 // it is a tentative definition.
814 if (_defines.count(u->getKey())) continue;
815 NameAndAttributes info = u->getValue();
816 _symbols.push_back(info);
822 /// parseMetadata - Parse metadata from the module
823 void LTOModule::parseMetadata() {
825 if (Value *Val = _module->getModuleFlag("Linker Options")) {
826 MDNode *LinkerOptions = cast<MDNode>(Val);
827 for (unsigned i = 0, e = LinkerOptions->getNumOperands(); i != e; ++i) {
828 MDNode *MDOptions = cast<MDNode>(LinkerOptions->getOperand(i));
829 for (unsigned ii = 0, ie = MDOptions->getNumOperands(); ii != ie; ++ii) {
830 MDString *MDOption = cast<MDString>(MDOptions->getOperand(ii));
831 StringRef Op = _linkeropt_strings.
832 GetOrCreateValue(MDOption->getString()).getKey();
833 StringRef DepLibName = _target->getTargetLowering()->
834 getObjFileLowering().getDepLibFromLinkerOpt(Op);
835 if (!DepLibName.empty())
836 _deplibs.push_back(DepLibName.data());
837 else if (!Op.empty())
838 _linkeropts.push_back(Op.data());
843 // Add other interesting metadata here.