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/FileSystem.h"
33 #include "llvm/Support/Host.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"
41 #include "llvm/Transforms/Utils/GlobalStatus.h"
44 LTOModule::LTOModule(llvm::Module *m, llvm::TargetMachine *t)
45 : _module(m), _target(t),
46 _context(_target->getMCAsmInfo(), _target->getRegisterInfo(), &ObjFileInfo),
47 _mangler(t->getDataLayout()) {
48 ObjFileInfo.InitMCObjectFileInfo(t->getTargetTriple(),
49 t->getRelocationModel(), t->getCodeModel(),
53 /// isBitcodeFile - Returns 'true' if the file (or memory contents) is LLVM
55 bool LTOModule::isBitcodeFile(const void *mem, size_t length) {
56 return sys::fs::identify_magic(StringRef((const char *)mem, length)) ==
57 sys::fs::file_magic::bitcode;
60 bool LTOModule::isBitcodeFile(const char *path) {
61 sys::fs::file_magic type;
62 if (sys::fs::identify_magic(path, type))
64 return type == sys::fs::file_magic::bitcode;
67 /// isBitcodeFileForTarget - Returns 'true' if the file (or memory contents) is
68 /// LLVM bitcode for the specified triple.
69 bool LTOModule::isBitcodeFileForTarget(const void *mem, size_t length,
70 const char *triplePrefix) {
71 MemoryBuffer *buffer = makeBuffer(mem, length);
74 return isTargetMatch(buffer, triplePrefix);
77 bool LTOModule::isBitcodeFileForTarget(const char *path,
78 const char *triplePrefix) {
79 OwningPtr<MemoryBuffer> buffer;
80 if (MemoryBuffer::getFile(path, buffer))
82 return isTargetMatch(buffer.take(), triplePrefix);
85 /// isTargetMatch - Returns 'true' if the memory buffer is for the specified
87 bool LTOModule::isTargetMatch(MemoryBuffer *buffer, const char *triplePrefix) {
88 std::string Triple = getBitcodeTargetTriple(buffer, getGlobalContext());
90 return strncmp(Triple.c_str(), triplePrefix, strlen(triplePrefix)) == 0;
93 /// makeLTOModule - Create an LTOModule. N.B. These methods take ownership of
95 LTOModule *LTOModule::makeLTOModule(const char *path, TargetOptions options,
96 std::string &errMsg) {
97 OwningPtr<MemoryBuffer> buffer;
98 if (error_code ec = MemoryBuffer::getFile(path, buffer)) {
99 errMsg = ec.message();
102 return makeLTOModule(buffer.take(), options, errMsg);
105 LTOModule *LTOModule::makeLTOModule(int fd, const char *path,
106 size_t size, TargetOptions options,
107 std::string &errMsg) {
108 return makeLTOModule(fd, path, size, 0, options, errMsg);
111 LTOModule *LTOModule::makeLTOModule(int fd, const char *path,
114 TargetOptions options,
115 std::string &errMsg) {
116 OwningPtr<MemoryBuffer> buffer;
118 MemoryBuffer::getOpenFileSlice(fd, path, buffer, map_size, offset)) {
119 errMsg = ec.message();
122 return makeLTOModule(buffer.take(), options, errMsg);
125 LTOModule *LTOModule::makeLTOModule(const void *mem, size_t length,
126 TargetOptions options,
127 std::string &errMsg) {
128 OwningPtr<MemoryBuffer> buffer(makeBuffer(mem, length));
131 return makeLTOModule(buffer.take(), options, errMsg);
134 LTOModule *LTOModule::makeLTOModule(MemoryBuffer *buffer,
135 TargetOptions options,
136 std::string &errMsg) {
137 // parse bitcode buffer
138 ErrorOr<Module *> ModuleOrErr =
139 getLazyBitcodeModule(buffer, getGlobalContext());
140 if (error_code EC = ModuleOrErr.getError()) {
141 errMsg = EC.message();
145 OwningPtr<Module> m(ModuleOrErr.get());
147 std::string TripleStr = m->getTargetTriple();
148 if (TripleStr.empty())
149 TripleStr = sys::getDefaultTargetTriple();
150 llvm::Triple Triple(TripleStr);
152 // find machine architecture for this module
153 const Target *march = TargetRegistry::lookupTarget(TripleStr, errMsg);
157 // construct LTOModule, hand over ownership of module and target
158 SubtargetFeatures Features;
159 Features.getDefaultSubtargetFeatures(Triple);
160 std::string FeatureStr = Features.getString();
161 // Set a default CPU for Darwin triples.
163 if (Triple.isOSDarwin()) {
164 if (Triple.getArch() == llvm::Triple::x86_64)
166 else if (Triple.getArch() == llvm::Triple::x86)
170 TargetMachine *target = march->createTargetMachine(TripleStr, CPU, FeatureStr,
172 m->materializeAllPermanently();
174 LTOModule *Ret = new LTOModule(m.take(), target);
175 if (Ret->parseSymbols(errMsg)) {
183 /// makeBuffer - Create a MemoryBuffer from a memory range.
184 MemoryBuffer *LTOModule::makeBuffer(const void *mem, size_t length) {
185 const char *startPtr = (const char*)mem;
186 return MemoryBuffer::getMemBuffer(StringRef(startPtr, length), "", false);
189 /// objcClassNameFromExpression - Get string that the data pointer points to.
191 LTOModule::objcClassNameFromExpression(const Constant *c, std::string &name) {
192 if (const ConstantExpr *ce = dyn_cast<ConstantExpr>(c)) {
193 Constant *op = ce->getOperand(0);
194 if (GlobalVariable *gvn = dyn_cast<GlobalVariable>(op)) {
195 Constant *cn = gvn->getInitializer();
196 if (ConstantDataArray *ca = dyn_cast<ConstantDataArray>(cn)) {
197 if (ca->isCString()) {
198 name = ".objc_class_name_" + ca->getAsCString().str();
207 /// addObjCClass - Parse i386/ppc ObjC class data structure.
208 void LTOModule::addObjCClass(const GlobalVariable *clgv) {
209 const ConstantStruct *c = dyn_cast<ConstantStruct>(clgv->getInitializer());
212 // second slot in __OBJC,__class is pointer to superclass name
213 std::string superclassName;
214 if (objcClassNameFromExpression(c->getOperand(1), superclassName)) {
215 NameAndAttributes info;
216 StringMap<NameAndAttributes>::value_type &entry =
217 _undefines.GetOrCreateValue(superclassName);
218 if (!entry.getValue().name) {
219 const char *symbolName = entry.getKey().data();
220 info.name = symbolName;
221 info.attributes = LTO_SYMBOL_DEFINITION_UNDEFINED;
222 info.isFunction = false;
224 entry.setValue(info);
228 // third slot in __OBJC,__class is pointer to class name
229 std::string className;
230 if (objcClassNameFromExpression(c->getOperand(2), className)) {
231 StringSet::value_type &entry = _defines.GetOrCreateValue(className);
234 NameAndAttributes info;
235 info.name = entry.getKey().data();
236 info.attributes = LTO_SYMBOL_PERMISSIONS_DATA |
237 LTO_SYMBOL_DEFINITION_REGULAR | LTO_SYMBOL_SCOPE_DEFAULT;
238 info.isFunction = false;
240 _symbols.push_back(info);
244 /// addObjCCategory - Parse i386/ppc ObjC category data structure.
245 void LTOModule::addObjCCategory(const GlobalVariable *clgv) {
246 const ConstantStruct *c = dyn_cast<ConstantStruct>(clgv->getInitializer());
249 // second slot in __OBJC,__category is pointer to target class name
250 std::string targetclassName;
251 if (!objcClassNameFromExpression(c->getOperand(1), targetclassName))
254 NameAndAttributes info;
255 StringMap<NameAndAttributes>::value_type &entry =
256 _undefines.GetOrCreateValue(targetclassName);
258 if (entry.getValue().name)
261 const char *symbolName = entry.getKey().data();
262 info.name = symbolName;
263 info.attributes = LTO_SYMBOL_DEFINITION_UNDEFINED;
264 info.isFunction = false;
266 entry.setValue(info);
269 /// addObjCClassRef - Parse i386/ppc ObjC class list data structure.
270 void LTOModule::addObjCClassRef(const GlobalVariable *clgv) {
271 std::string targetclassName;
272 if (!objcClassNameFromExpression(clgv->getInitializer(), targetclassName))
275 NameAndAttributes info;
276 StringMap<NameAndAttributes>::value_type &entry =
277 _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 /// addDefinedDataSymbol - Add a data symbol as defined to the list.
290 void LTOModule::addDefinedDataSymbol(const GlobalValue *v) {
291 // Add to list of defined symbols.
292 addDefinedSymbol(v, false);
294 if (!v->hasSection() /* || !isTargetDarwin */)
297 // Special case i386/ppc ObjC data structures in magic sections:
298 // The issue is that the old ObjC object format did some strange
299 // contortions to avoid real linker symbols. For instance, the
300 // ObjC class data structure is allocated statically in the executable
301 // that defines that class. That data structures contains a pointer to
302 // its superclass. But instead of just initializing that part of the
303 // struct to the address of its superclass, and letting the static and
304 // dynamic linkers do the rest, the runtime works by having that field
305 // instead point to a C-string that is the name of the superclass.
306 // At runtime the objc initialization updates that pointer and sets
307 // it to point to the actual super class. As far as the linker
308 // knows it is just a pointer to a string. But then someone wanted the
309 // linker to issue errors at build time if the superclass was not found.
310 // So they figured out a way in mach-o object format to use an absolute
311 // symbols (.objc_class_name_Foo = 0) and a floating reference
312 // (.reference .objc_class_name_Bar) to cause the linker into erroring when
313 // a class was missing.
314 // The following synthesizes the implicit .objc_* symbols for the linker
315 // from the ObjC data structures generated by the front end.
317 // special case if this data blob is an ObjC class definition
318 if (v->getSection().compare(0, 15, "__OBJC,__class,") == 0) {
319 if (const GlobalVariable *gv = dyn_cast<GlobalVariable>(v)) {
324 // special case if this data blob is an ObjC category definition
325 else if (v->getSection().compare(0, 18, "__OBJC,__category,") == 0) {
326 if (const GlobalVariable *gv = dyn_cast<GlobalVariable>(v)) {
331 // special case if this data blob is the list of referenced classes
332 else if (v->getSection().compare(0, 18, "__OBJC,__cls_refs,") == 0) {
333 if (const GlobalVariable *gv = dyn_cast<GlobalVariable>(v)) {
339 /// addDefinedFunctionSymbol - Add a function symbol as defined to the list.
340 void LTOModule::addDefinedFunctionSymbol(const Function *f) {
341 // add to list of defined symbols
342 addDefinedSymbol(f, true);
345 static bool canBeHidden(const GlobalValue *GV) {
346 GlobalValue::LinkageTypes L = GV->getLinkage();
348 if (L != GlobalValue::LinkOnceODRLinkage)
351 if (GV->hasUnnamedAddr())
355 if (GlobalStatus::analyzeGlobal(GV, GS))
358 return !GS.IsCompared;
361 /// addDefinedSymbol - Add a defined symbol to the list.
362 void LTOModule::addDefinedSymbol(const GlobalValue *def, bool isFunction) {
363 // ignore all llvm.* symbols
364 if (def->getName().startswith("llvm."))
367 // string is owned by _defines
368 SmallString<64> Buffer;
369 _mangler.getNameWithPrefix(Buffer, def);
371 // set alignment part log2() can have rounding errors
372 uint32_t align = def->getAlignment();
373 uint32_t attr = align ? countTrailingZeros(def->getAlignment()) : 0;
375 // set permissions part
377 attr |= LTO_SYMBOL_PERMISSIONS_CODE;
379 const GlobalVariable *gv = dyn_cast<GlobalVariable>(def);
380 if (gv && gv->isConstant())
381 attr |= LTO_SYMBOL_PERMISSIONS_RODATA;
383 attr |= LTO_SYMBOL_PERMISSIONS_DATA;
386 // set definition part
387 if (def->hasWeakLinkage() || def->hasLinkOnceLinkage() ||
388 def->hasLinkerPrivateWeakLinkage())
389 attr |= LTO_SYMBOL_DEFINITION_WEAK;
390 else if (def->hasCommonLinkage())
391 attr |= LTO_SYMBOL_DEFINITION_TENTATIVE;
393 attr |= LTO_SYMBOL_DEFINITION_REGULAR;
396 if (def->hasHiddenVisibility())
397 attr |= LTO_SYMBOL_SCOPE_HIDDEN;
398 else if (def->hasProtectedVisibility())
399 attr |= LTO_SYMBOL_SCOPE_PROTECTED;
400 else if (canBeHidden(def))
401 attr |= LTO_SYMBOL_SCOPE_DEFAULT_CAN_BE_HIDDEN;
402 else if (def->hasExternalLinkage() || def->hasWeakLinkage() ||
403 def->hasLinkOnceLinkage() || def->hasCommonLinkage() ||
404 def->hasLinkerPrivateWeakLinkage())
405 attr |= LTO_SYMBOL_SCOPE_DEFAULT;
407 attr |= LTO_SYMBOL_SCOPE_INTERNAL;
409 StringSet::value_type &entry = _defines.GetOrCreateValue(Buffer);
412 // fill information structure
413 NameAndAttributes info;
414 StringRef Name = entry.getKey();
415 info.name = Name.data();
416 assert(info.name[Name.size()] == '\0');
417 info.attributes = attr;
418 info.isFunction = isFunction;
421 // add to table of symbols
422 _symbols.push_back(info);
425 /// addAsmGlobalSymbol - Add a global symbol from module-level ASM to the
427 void LTOModule::addAsmGlobalSymbol(const char *name,
428 lto_symbol_attributes scope) {
429 StringSet::value_type &entry = _defines.GetOrCreateValue(name);
431 // only add new define if not already defined
432 if (entry.getValue())
437 NameAndAttributes &info = _undefines[entry.getKey().data()];
439 if (info.symbol == 0) {
440 // FIXME: This is trying to take care of module ASM like this:
442 // module asm ".zerofill __FOO, __foo, _bar_baz_qux, 0"
444 // but is gross and its mother dresses it funny. Have the ASM parser give us
445 // more details for this type of situation so that we're not guessing so
448 // fill information structure
449 info.name = entry.getKey().data();
451 LTO_SYMBOL_PERMISSIONS_DATA | LTO_SYMBOL_DEFINITION_REGULAR | scope;
452 info.isFunction = false;
455 // add to table of symbols
456 _symbols.push_back(info);
461 addDefinedFunctionSymbol(cast<Function>(info.symbol));
463 addDefinedDataSymbol(info.symbol);
465 _symbols.back().attributes &= ~LTO_SYMBOL_SCOPE_MASK;
466 _symbols.back().attributes |= scope;
469 /// addAsmGlobalSymbolUndef - Add a global symbol from module-level ASM to the
471 void LTOModule::addAsmGlobalSymbolUndef(const char *name) {
472 StringMap<NameAndAttributes>::value_type &entry =
473 _undefines.GetOrCreateValue(name);
475 _asm_undefines.push_back(entry.getKey().data());
477 // we already have the symbol
478 if (entry.getValue().name)
481 uint32_t attr = LTO_SYMBOL_DEFINITION_UNDEFINED;;
482 attr |= LTO_SYMBOL_SCOPE_DEFAULT;
483 NameAndAttributes info;
484 info.name = entry.getKey().data();
485 info.attributes = attr;
486 info.isFunction = false;
489 entry.setValue(info);
492 /// addPotentialUndefinedSymbol - Add a symbol which isn't defined just yet to a
493 /// list to be resolved later.
495 LTOModule::addPotentialUndefinedSymbol(const GlobalValue *decl, bool isFunc) {
496 // ignore all llvm.* symbols
497 if (decl->getName().startswith("llvm."))
500 // ignore all aliases
501 if (isa<GlobalAlias>(decl))
504 SmallString<64> name;
505 _mangler.getNameWithPrefix(name, decl);
507 StringMap<NameAndAttributes>::value_type &entry =
508 _undefines.GetOrCreateValue(name);
510 // we already have the symbol
511 if (entry.getValue().name)
514 NameAndAttributes info;
516 info.name = entry.getKey().data();
518 if (decl->hasExternalWeakLinkage())
519 info.attributes = LTO_SYMBOL_DEFINITION_WEAKUNDEF;
521 info.attributes = LTO_SYMBOL_DEFINITION_UNDEFINED;
523 info.isFunction = isFunc;
526 entry.setValue(info);
530 class RecordStreamer : public MCStreamer {
532 enum State { NeverSeen, Global, Defined, DefinedGlobal, Used };
535 StringMap<State> Symbols;
537 void markDefined(const MCSymbol &Symbol) {
538 State &S = Symbols[Symbol.getName()];
551 void markGlobal(const MCSymbol &Symbol) {
552 State &S = Symbols[Symbol.getName()];
566 void markUsed(const MCSymbol &Symbol) {
567 State &S = Symbols[Symbol.getName()];
581 // FIXME: mostly copied for the obj streamer.
582 void AddValueSymbols(const MCExpr *Value) {
583 switch (Value->getKind()) {
585 // FIXME: What should we do in here?
588 case MCExpr::Constant:
591 case MCExpr::Binary: {
592 const MCBinaryExpr *BE = cast<MCBinaryExpr>(Value);
593 AddValueSymbols(BE->getLHS());
594 AddValueSymbols(BE->getRHS());
598 case MCExpr::SymbolRef:
599 markUsed(cast<MCSymbolRefExpr>(Value)->getSymbol());
603 AddValueSymbols(cast<MCUnaryExpr>(Value)->getSubExpr());
609 typedef StringMap<State>::const_iterator const_iterator;
611 const_iterator begin() {
612 return Symbols.begin();
615 const_iterator end() {
616 return Symbols.end();
619 RecordStreamer(MCContext &Context) : MCStreamer(Context, 0) {}
621 virtual void EmitInstruction(const MCInst &Inst) {
623 for (unsigned i = Inst.getNumOperands(); i--; )
624 if (Inst.getOperand(i).isExpr())
625 AddValueSymbols(Inst.getOperand(i).getExpr());
627 virtual void EmitLabel(MCSymbol *Symbol) {
628 Symbol->setSection(*getCurrentSection().first);
629 markDefined(*Symbol);
631 virtual void EmitDebugLabel(MCSymbol *Symbol) {
634 virtual void EmitAssignment(MCSymbol *Symbol, const MCExpr *Value) {
635 // FIXME: should we handle aliases?
636 markDefined(*Symbol);
638 virtual bool EmitSymbolAttribute(MCSymbol *Symbol, MCSymbolAttr Attribute) {
639 if (Attribute == MCSA_Global)
643 virtual void EmitZerofill(const MCSection *Section, MCSymbol *Symbol,
644 uint64_t Size , unsigned ByteAlignment) {
645 markDefined(*Symbol);
647 virtual void EmitCommonSymbol(MCSymbol *Symbol, uint64_t Size,
648 unsigned ByteAlignment) {
649 markDefined(*Symbol);
652 virtual void EmitBundleAlignMode(unsigned AlignPow2) {}
653 virtual void EmitBundleLock(bool AlignToEnd) {}
654 virtual void EmitBundleUnlock() {}
657 virtual void ChangeSection(const MCSection *Section,
658 const MCExpr *Subsection) {}
659 virtual void InitToTextSection() {}
660 virtual void InitSections() {}
661 virtual void EmitAssemblerFlag(MCAssemblerFlag Flag) {}
662 virtual void EmitThumbFunc(MCSymbol *Func) {}
663 virtual void EmitSymbolDesc(MCSymbol *Symbol, unsigned DescValue) {}
664 virtual void EmitWeakReference(MCSymbol *Alias, const MCSymbol *Symbol) {}
665 virtual void BeginCOFFSymbolDef(const MCSymbol *Symbol) {}
666 virtual void EmitCOFFSymbolStorageClass(int StorageClass) {}
667 virtual void EmitCOFFSymbolType(int Type) {}
668 virtual void EndCOFFSymbolDef() {}
669 virtual void EmitELFSize(MCSymbol *Symbol, const MCExpr *Value) {}
670 virtual void EmitLocalCommonSymbol(MCSymbol *Symbol, uint64_t Size,
671 unsigned ByteAlignment) {}
672 virtual void EmitTBSSSymbol(const MCSection *Section, MCSymbol *Symbol,
673 uint64_t Size, unsigned ByteAlignment) {}
674 virtual void EmitBytes(StringRef Data) {}
675 virtual void EmitValueImpl(const MCExpr *Value, unsigned Size) {}
676 virtual void EmitULEB128Value(const MCExpr *Value) {}
677 virtual void EmitSLEB128Value(const MCExpr *Value) {}
678 virtual void EmitValueToAlignment(unsigned ByteAlignment, int64_t Value,
680 unsigned MaxBytesToEmit) {}
681 virtual void EmitCodeAlignment(unsigned ByteAlignment,
682 unsigned MaxBytesToEmit) {}
683 virtual bool EmitValueToOffset(const MCExpr *Offset,
684 unsigned char Value ) { return false; }
685 virtual void EmitFileDirective(StringRef Filename) {}
686 virtual void EmitDwarfAdvanceLineAddr(int64_t LineDelta,
687 const MCSymbol *LastLabel,
688 const MCSymbol *Label,
689 unsigned PointerSize) {}
690 virtual void FinishImpl() {}
691 virtual void EmitCFIEndProcImpl(MCDwarfFrameInfo &Frame) {
692 RecordProcEnd(Frame);
695 } // end anonymous namespace
697 /// addAsmGlobalSymbols - Add global symbols from module-level ASM to the
698 /// defined or undefined lists.
699 bool LTOModule::addAsmGlobalSymbols(std::string &errMsg) {
700 const std::string &inlineAsm = _module->getModuleInlineAsm();
701 if (inlineAsm.empty())
704 OwningPtr<RecordStreamer> Streamer(new RecordStreamer(_context));
705 MemoryBuffer *Buffer = MemoryBuffer::getMemBuffer(inlineAsm);
707 SrcMgr.AddNewSourceBuffer(Buffer, SMLoc());
708 OwningPtr<MCAsmParser> Parser(createMCAsmParser(SrcMgr,
710 *_target->getMCAsmInfo()));
711 const Target &T = _target->getTarget();
712 OwningPtr<MCInstrInfo> MCII(T.createMCInstrInfo());
713 OwningPtr<MCSubtargetInfo>
714 STI(T.createMCSubtargetInfo(_target->getTargetTriple(),
715 _target->getTargetCPU(),
716 _target->getTargetFeatureString()));
717 OwningPtr<MCTargetAsmParser> TAP(T.createMCAsmParser(*STI, *Parser.get(), *MCII));
719 errMsg = "target " + std::string(T.getName()) +
720 " does not define AsmParser.";
724 Parser->setTargetParser(*TAP);
725 if (Parser->Run(false))
728 for (RecordStreamer::const_iterator i = Streamer->begin(),
729 e = Streamer->end(); i != e; ++i) {
730 StringRef Key = i->first();
731 RecordStreamer::State Value = i->second;
732 if (Value == RecordStreamer::DefinedGlobal)
733 addAsmGlobalSymbol(Key.data(), LTO_SYMBOL_SCOPE_DEFAULT);
734 else if (Value == RecordStreamer::Defined)
735 addAsmGlobalSymbol(Key.data(), LTO_SYMBOL_SCOPE_INTERNAL);
736 else if (Value == RecordStreamer::Global ||
737 Value == RecordStreamer::Used)
738 addAsmGlobalSymbolUndef(Key.data());
744 /// isDeclaration - Return 'true' if the global value is a declaration.
745 static bool isDeclaration(const GlobalValue &V) {
746 if (V.hasAvailableExternallyLinkage())
749 if (V.isMaterializable())
752 return V.isDeclaration();
755 /// parseSymbols - Parse the symbols from the module and model-level ASM and add
756 /// them to either the defined or undefined lists.
757 bool LTOModule::parseSymbols(std::string &errMsg) {
759 for (Module::iterator f = _module->begin(), e = _module->end(); f != e; ++f) {
760 if (isDeclaration(*f))
761 addPotentialUndefinedSymbol(f, true);
763 addDefinedFunctionSymbol(f);
767 for (Module::global_iterator v = _module->global_begin(),
768 e = _module->global_end(); v != e; ++v) {
769 if (isDeclaration(*v))
770 addPotentialUndefinedSymbol(v, false);
772 addDefinedDataSymbol(v);
776 if (addAsmGlobalSymbols(errMsg))
780 for (Module::alias_iterator a = _module->alias_begin(),
781 e = _module->alias_end(); a != e; ++a) {
782 if (isDeclaration(*a->getAliasedGlobal()))
783 // Is an alias to a declaration.
784 addPotentialUndefinedSymbol(a, false);
786 addDefinedDataSymbol(a);
789 // make symbols for all undefines
790 for (StringMap<NameAndAttributes>::iterator u =_undefines.begin(),
791 e = _undefines.end(); u != e; ++u) {
792 // If this symbol also has a definition, then don't make an undefine because
793 // it is a tentative definition.
794 if (_defines.count(u->getKey())) continue;
795 NameAndAttributes info = u->getValue();
796 _symbols.push_back(info);