Sink SubtargetFeature and TargetInstrItineraries (renamed MCInstrItineraries) into MC.
[oota-llvm.git] / tools / lto / LTOModule.cpp
1 //===-- LTOModule.cpp - LLVM Link Time Optimizer --------------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
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.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #include "LTOModule.h"
16
17 #include "llvm/Constants.h"
18 #include "llvm/LLVMContext.h"
19 #include "llvm/Module.h"
20 #include "llvm/ADT/OwningPtr.h"
21 #include "llvm/ADT/Triple.h"
22 #include "llvm/Bitcode/ReaderWriter.h"
23 #include "llvm/Support/SystemUtils.h"
24 #include "llvm/Support/MemoryBuffer.h"
25 #include "llvm/Support/MathExtras.h"
26 #include "llvm/Support/Host.h"
27 #include "llvm/Support/Path.h"
28 #include "llvm/Support/Process.h"
29 #include "llvm/Support/SourceMgr.h"
30 #include "llvm/Support/system_error.h"
31 #include "llvm/Target/Mangler.h"
32 #include "llvm/MC/MCAsmInfo.h"
33 #include "llvm/MC/MCContext.h"
34 #include "llvm/MC/MCExpr.h"
35 #include "llvm/MC/MCInst.h"
36 #include "llvm/MC/MCParser/MCAsmParser.h"
37 #include "llvm/MC/MCStreamer.h"
38 #include "llvm/MC/MCSymbol.h"
39 #include "llvm/MC/SubtargetFeature.h"
40 #include "llvm/Target/TargetAsmParser.h"
41 #include "llvm/Target/TargetMachine.h"
42 #include "llvm/Target/TargetRegistry.h"
43 #include "llvm/Target/TargetSelect.h"
44
45 using namespace llvm;
46
47 bool LTOModule::isBitcodeFile(const void *mem, size_t length) {
48   return llvm::sys::IdentifyFileType((char*)mem, length)
49     == llvm::sys::Bitcode_FileType;
50 }
51
52 bool LTOModule::isBitcodeFile(const char *path) {
53   return llvm::sys::Path(path).isBitcodeFile();
54 }
55
56 bool LTOModule::isBitcodeFileForTarget(const void *mem, size_t length,
57                                        const char *triplePrefix) {
58   MemoryBuffer *buffer = makeBuffer(mem, length);
59   if (!buffer)
60     return false;
61   return isTargetMatch(buffer, triplePrefix);
62 }
63
64
65 bool LTOModule::isBitcodeFileForTarget(const char *path,
66                                        const char *triplePrefix) {
67   OwningPtr<MemoryBuffer> buffer;
68   if (MemoryBuffer::getFile(path, buffer))
69     return false;
70   return isTargetMatch(buffer.take(), triplePrefix);
71 }
72
73 // Takes ownership of buffer.
74 bool LTOModule::isTargetMatch(MemoryBuffer *buffer, const char *triplePrefix) {
75   std::string Triple = getBitcodeTargetTriple(buffer, getGlobalContext());
76   delete buffer;
77   return (strncmp(Triple.c_str(), triplePrefix,
78                   strlen(triplePrefix)) == 0);
79 }
80
81
82 LTOModule::LTOModule(Module *m, TargetMachine *t)
83   : _module(m), _target(t)
84 {
85 }
86
87 LTOModule *LTOModule::makeLTOModule(const char *path,
88                                     std::string &errMsg) {
89   OwningPtr<MemoryBuffer> buffer;
90   if (error_code ec = MemoryBuffer::getFile(path, buffer)) {
91     errMsg = ec.message();
92     return NULL;
93   }
94   return makeLTOModule(buffer.take(), errMsg);
95 }
96
97 LTOModule *LTOModule::makeLTOModule(int fd, const char *path,
98                                     size_t size,
99                                     std::string &errMsg) {
100   return makeLTOModule(fd, path, size, size, 0, errMsg);
101 }
102
103 LTOModule *LTOModule::makeLTOModule(int fd, const char *path,
104                                     size_t file_size,
105                                     size_t map_size,
106                                     off_t offset,
107                                     std::string &errMsg) {
108   OwningPtr<MemoryBuffer> buffer;
109   if (error_code ec = MemoryBuffer::getOpenFile(fd, path, buffer, file_size,
110                                                 map_size, offset, false)) {
111     errMsg = ec.message();
112     return NULL;
113   }
114   return makeLTOModule(buffer.take(), errMsg);
115 }
116
117 /// makeBuffer - Create a MemoryBuffer from a memory range.
118 MemoryBuffer *LTOModule::makeBuffer(const void *mem, size_t length) {
119   const char *startPtr = (char*)mem;
120   return MemoryBuffer::getMemBuffer(StringRef(startPtr, length), "", false);
121 }
122
123
124 LTOModule *LTOModule::makeLTOModule(const void *mem, size_t length,
125                                     std::string &errMsg) {
126   OwningPtr<MemoryBuffer> buffer(makeBuffer(mem, length));
127   if (!buffer)
128     return NULL;
129   return makeLTOModule(buffer.take(), errMsg);
130 }
131
132 LTOModule *LTOModule::makeLTOModule(MemoryBuffer *buffer,
133                                     std::string &errMsg) {
134   static bool Initialized = false;
135   if (!Initialized) {
136     InitializeAllTargets();
137     InitializeAllAsmParsers();
138     Initialized = true;
139   }
140
141   // parse bitcode buffer
142   OwningPtr<Module> m(getLazyBitcodeModule(buffer, getGlobalContext(),
143                                            &errMsg));
144   if (!m) {
145     delete buffer;
146     return NULL;
147   }
148
149   std::string Triple = m->getTargetTriple();
150   if (Triple.empty())
151     Triple = sys::getHostTriple();
152
153   // find machine architecture for this module
154   const Target *march = TargetRegistry::lookupTarget(Triple, errMsg);
155   if (!march)
156     return NULL;
157
158   // construct LTOModule, hand over ownership of module and target
159   SubtargetFeatures Features;
160   Features.getDefaultSubtargetFeatures("" /* cpu */, llvm::Triple(Triple));
161   std::string FeatureStr = Features.getString();
162   TargetMachine *target = march->createTargetMachine(Triple, FeatureStr);
163   LTOModule *Ret = new LTOModule(m.take(), target);
164   bool Err = Ret->ParseSymbols();
165   if (Err) {
166     delete Ret;
167     return NULL;
168   }
169   return Ret;
170 }
171
172
173 const char *LTOModule::getTargetTriple() {
174   return _module->getTargetTriple().c_str();
175 }
176
177 void LTOModule::setTargetTriple(const char *triple) {
178   _module->setTargetTriple(triple);
179 }
180
181 void LTOModule::addDefinedFunctionSymbol(Function *f, Mangler &mangler) {
182   // add to list of defined symbols
183   addDefinedSymbol(f, mangler, true);
184 }
185
186 // Get string that data pointer points to.
187 bool LTOModule::objcClassNameFromExpression(Constant *c, std::string &name) {
188   if (ConstantExpr *ce = dyn_cast<ConstantExpr>(c)) {
189     Constant *op = ce->getOperand(0);
190     if (GlobalVariable *gvn = dyn_cast<GlobalVariable>(op)) {
191       Constant *cn = gvn->getInitializer();
192       if (ConstantArray *ca = dyn_cast<ConstantArray>(cn)) {
193         if (ca->isCString()) {
194           name = ".objc_class_name_" + ca->getAsCString();
195           return true;
196         }
197       }
198     }
199   }
200   return false;
201 }
202
203 // Parse i386/ppc ObjC class data structure.
204 void LTOModule::addObjCClass(GlobalVariable *clgv) {
205   if (ConstantStruct *c = dyn_cast<ConstantStruct>(clgv->getInitializer())) {
206     // second slot in __OBJC,__class is pointer to superclass name
207     std::string superclassName;
208     if (objcClassNameFromExpression(c->getOperand(1), superclassName)) {
209       NameAndAttributes info;
210       StringMap<NameAndAttributes>::value_type &entry =
211         _undefines.GetOrCreateValue(superclassName);
212       if (!entry.getValue().name) {
213         const char *symbolName = entry.getKey().data();
214         info.name = symbolName;
215         info.attributes = LTO_SYMBOL_DEFINITION_UNDEFINED;
216         entry.setValue(info);
217       }
218     }
219     // third slot in __OBJC,__class is pointer to class name
220     std::string className;
221     if (objcClassNameFromExpression(c->getOperand(2), className)) {
222       StringSet::value_type &entry =
223         _defines.GetOrCreateValue(className);
224       entry.setValue(1);
225       NameAndAttributes info;
226       info.name = entry.getKey().data();
227       info.attributes = (lto_symbol_attributes)
228         (LTO_SYMBOL_PERMISSIONS_DATA |
229          LTO_SYMBOL_DEFINITION_REGULAR |
230          LTO_SYMBOL_SCOPE_DEFAULT);
231       _symbols.push_back(info);
232     }
233   }
234 }
235
236
237 // Parse i386/ppc ObjC category data structure.
238 void LTOModule::addObjCCategory(GlobalVariable *clgv) {
239   if (ConstantStruct *c = dyn_cast<ConstantStruct>(clgv->getInitializer())) {
240     // second slot in __OBJC,__category is pointer to target class name
241     std::string targetclassName;
242     if (objcClassNameFromExpression(c->getOperand(1), targetclassName)) {
243       NameAndAttributes info;
244
245       StringMap<NameAndAttributes>::value_type &entry =
246         _undefines.GetOrCreateValue(targetclassName);
247
248       if (entry.getValue().name)
249         return;
250
251       const char *symbolName = entry.getKey().data();
252       info.name = symbolName;
253       info.attributes = LTO_SYMBOL_DEFINITION_UNDEFINED;
254       entry.setValue(info);
255     }
256   }
257 }
258
259
260 // Parse i386/ppc ObjC class list data structure.
261 void LTOModule::addObjCClassRef(GlobalVariable *clgv) {
262   std::string targetclassName;
263   if (objcClassNameFromExpression(clgv->getInitializer(), targetclassName)) {
264     NameAndAttributes info;
265
266     StringMap<NameAndAttributes>::value_type &entry =
267       _undefines.GetOrCreateValue(targetclassName);
268     if (entry.getValue().name)
269       return;
270
271     const char *symbolName = entry.getKey().data();
272     info.name = symbolName;
273     info.attributes = LTO_SYMBOL_DEFINITION_UNDEFINED;
274     entry.setValue(info);
275   }
276 }
277
278
279 void LTOModule::addDefinedDataSymbol(GlobalValue *v, Mangler &mangler) {
280   // Add to list of defined symbols.
281   addDefinedSymbol(v, mangler, false);
282
283   // Special case i386/ppc ObjC data structures in magic sections:
284   // The issue is that the old ObjC object format did some strange
285   // contortions to avoid real linker symbols.  For instance, the
286   // ObjC class data structure is allocated statically in the executable
287   // that defines that class.  That data structures contains a pointer to
288   // its superclass.  But instead of just initializing that part of the
289   // struct to the address of its superclass, and letting the static and
290   // dynamic linkers do the rest, the runtime works by having that field
291   // instead point to a C-string that is the name of the superclass.
292   // At runtime the objc initialization updates that pointer and sets
293   // it to point to the actual super class.  As far as the linker
294   // knows it is just a pointer to a string.  But then someone wanted the
295   // linker to issue errors at build time if the superclass was not found.
296   // So they figured out a way in mach-o object format to use an absolute
297   // symbols (.objc_class_name_Foo = 0) and a floating reference
298   // (.reference .objc_class_name_Bar) to cause the linker into erroring when
299   // a class was missing.
300   // The following synthesizes the implicit .objc_* symbols for the linker
301   // from the ObjC data structures generated by the front end.
302   if (v->hasSection() /* && isTargetDarwin */) {
303     // special case if this data blob is an ObjC class definition
304     if (v->getSection().compare(0, 15, "__OBJC,__class,") == 0) {
305       if (GlobalVariable *gv = dyn_cast<GlobalVariable>(v)) {
306         addObjCClass(gv);
307       }
308     }
309
310     // special case if this data blob is an ObjC category definition
311     else if (v->getSection().compare(0, 18, "__OBJC,__category,") == 0) {
312       if (GlobalVariable *gv = dyn_cast<GlobalVariable>(v)) {
313         addObjCCategory(gv);
314       }
315     }
316
317     // special case if this data blob is the list of referenced classes
318     else if (v->getSection().compare(0, 18, "__OBJC,__cls_refs,") == 0) {
319       if (GlobalVariable *gv = dyn_cast<GlobalVariable>(v)) {
320         addObjCClassRef(gv);
321       }
322     }
323   }
324 }
325
326
327 void LTOModule::addDefinedSymbol(GlobalValue *def, Mangler &mangler,
328                                  bool isFunction) {
329   // ignore all llvm.* symbols
330   if (def->getName().startswith("llvm."))
331     return;
332
333   // string is owned by _defines
334   SmallString<64> Buffer;
335   mangler.getNameWithPrefix(Buffer, def, false);
336
337   // set alignment part log2() can have rounding errors
338   uint32_t align = def->getAlignment();
339   uint32_t attr = align ? CountTrailingZeros_32(def->getAlignment()) : 0;
340
341   // set permissions part
342   if (isFunction)
343     attr |= LTO_SYMBOL_PERMISSIONS_CODE;
344   else {
345     GlobalVariable *gv = dyn_cast<GlobalVariable>(def);
346     if (gv && gv->isConstant())
347       attr |= LTO_SYMBOL_PERMISSIONS_RODATA;
348     else
349       attr |= LTO_SYMBOL_PERMISSIONS_DATA;
350   }
351
352   // set definition part
353   if (def->hasWeakLinkage() || def->hasLinkOnceLinkage() ||
354       def->hasLinkerPrivateWeakLinkage() ||
355       def->hasLinkerPrivateWeakDefAutoLinkage())
356     attr |= LTO_SYMBOL_DEFINITION_WEAK;
357   else if (def->hasCommonLinkage())
358     attr |= LTO_SYMBOL_DEFINITION_TENTATIVE;
359   else
360     attr |= LTO_SYMBOL_DEFINITION_REGULAR;
361
362   // set scope part
363   if (def->hasHiddenVisibility())
364     attr |= LTO_SYMBOL_SCOPE_HIDDEN;
365   else if (def->hasProtectedVisibility())
366     attr |= LTO_SYMBOL_SCOPE_PROTECTED;
367   else if (def->hasExternalLinkage() || def->hasWeakLinkage() ||
368            def->hasLinkOnceLinkage() || def->hasCommonLinkage() ||
369            def->hasLinkerPrivateWeakLinkage())
370     attr |= LTO_SYMBOL_SCOPE_DEFAULT;
371   else if (def->hasLinkerPrivateWeakDefAutoLinkage())
372     attr |= LTO_SYMBOL_SCOPE_DEFAULT_CAN_BE_HIDDEN;
373   else
374     attr |= LTO_SYMBOL_SCOPE_INTERNAL;
375
376   // add to table of symbols
377   NameAndAttributes info;
378   StringSet::value_type &entry = _defines.GetOrCreateValue(Buffer);
379   entry.setValue(1);
380
381   StringRef Name = entry.getKey();
382   info.name = Name.data();
383   assert(info.name[Name.size()] == '\0');
384   info.attributes = (lto_symbol_attributes)attr;
385   _symbols.push_back(info);
386 }
387
388 void LTOModule::addAsmGlobalSymbol(const char *name,
389                                    lto_symbol_attributes scope) {
390   StringSet::value_type &entry = _defines.GetOrCreateValue(name);
391
392   // only add new define if not already defined
393   if (entry.getValue())
394     return;
395
396   entry.setValue(1);
397   const char *symbolName = entry.getKey().data();
398   uint32_t attr = LTO_SYMBOL_DEFINITION_REGULAR;
399   attr |= scope;
400   NameAndAttributes info;
401   info.name = symbolName;
402   info.attributes = (lto_symbol_attributes)attr;
403   _symbols.push_back(info);
404 }
405
406 void LTOModule::addAsmGlobalSymbolUndef(const char *name) {
407   StringMap<NameAndAttributes>::value_type &entry =
408     _undefines.GetOrCreateValue(name);
409
410   _asm_undefines.push_back(entry.getKey().data());
411
412   // we already have the symbol
413   if (entry.getValue().name)
414     return;
415
416   uint32_t attr = LTO_SYMBOL_DEFINITION_UNDEFINED;;
417   attr |= LTO_SYMBOL_SCOPE_DEFAULT;
418   NameAndAttributes info;
419   info.name = entry.getKey().data();
420   info.attributes = (lto_symbol_attributes)attr;
421
422   entry.setValue(info);
423 }
424
425 void LTOModule::addPotentialUndefinedSymbol(GlobalValue *decl,
426                                             Mangler &mangler) {
427   // ignore all llvm.* symbols
428   if (decl->getName().startswith("llvm."))
429     return;
430
431   // ignore all aliases
432   if (isa<GlobalAlias>(decl))
433     return;
434
435   SmallString<64> name;
436   mangler.getNameWithPrefix(name, decl, false);
437
438   StringMap<NameAndAttributes>::value_type &entry =
439     _undefines.GetOrCreateValue(name);
440
441   // we already have the symbol
442   if (entry.getValue().name)
443     return;
444
445   NameAndAttributes info;
446
447   info.name = entry.getKey().data();
448   if (decl->hasExternalWeakLinkage())
449     info.attributes = LTO_SYMBOL_DEFINITION_WEAKUNDEF;
450   else
451     info.attributes = LTO_SYMBOL_DEFINITION_UNDEFINED;
452
453   entry.setValue(info);
454 }
455
456
457 namespace {
458   class RecordStreamer : public MCStreamer {
459   public:
460     enum State { NeverSeen, Global, Defined, DefinedGlobal, Used};
461
462   private:
463     StringMap<State> Symbols;
464
465     void markDefined(const MCSymbol &Symbol) {
466       State &S = Symbols[Symbol.getName()];
467       switch (S) {
468       case DefinedGlobal:
469       case Global:
470         S = DefinedGlobal;
471         break;
472       case NeverSeen:
473       case Defined:
474       case Used:
475         S = Defined;
476         break;
477       }
478     }
479     void markGlobal(const MCSymbol &Symbol) {
480       State &S = Symbols[Symbol.getName()];
481       switch (S) {
482       case DefinedGlobal:
483       case Defined:
484         S = DefinedGlobal;
485         break;
486
487       case NeverSeen:
488       case Global:
489       case Used:
490         S = Global;
491         break;
492       }
493     }
494     void markUsed(const MCSymbol &Symbol) {
495       State &S = Symbols[Symbol.getName()];
496       switch (S) {
497       case DefinedGlobal:
498       case Defined:
499       case Global:
500         break;
501
502       case NeverSeen:
503       case Used:
504         S = Used;
505         break;
506       }
507     }
508
509     // FIXME: mostly copied for the obj streamer.
510     void AddValueSymbols(const MCExpr *Value) {
511       switch (Value->getKind()) {
512       case MCExpr::Target:
513         // FIXME: What should we do in here?
514         break;
515
516       case MCExpr::Constant:
517         break;
518
519       case MCExpr::Binary: {
520         const MCBinaryExpr *BE = cast<MCBinaryExpr>(Value);
521         AddValueSymbols(BE->getLHS());
522         AddValueSymbols(BE->getRHS());
523         break;
524       }
525
526       case MCExpr::SymbolRef:
527         markUsed(cast<MCSymbolRefExpr>(Value)->getSymbol());
528         break;
529
530       case MCExpr::Unary:
531         AddValueSymbols(cast<MCUnaryExpr>(Value)->getSubExpr());
532         break;
533       }
534     }
535
536   public:
537     typedef StringMap<State>::const_iterator const_iterator;
538
539     const_iterator begin() {
540       return Symbols.begin();
541     }
542
543     const_iterator end() {
544       return Symbols.end();
545     }
546
547     RecordStreamer(MCContext &Context) : MCStreamer(Context) {}
548
549     virtual void ChangeSection(const MCSection *Section) {}
550     virtual void InitSections() {}
551     virtual void EmitLabel(MCSymbol *Symbol) {
552       Symbol->setSection(*getCurrentSection());
553       markDefined(*Symbol);
554     }
555     virtual void EmitAssemblerFlag(MCAssemblerFlag Flag) {}
556     virtual void EmitThumbFunc(MCSymbol *Func) {}
557     virtual void EmitAssignment(MCSymbol *Symbol, const MCExpr *Value) {
558       // FIXME: should we handle aliases?
559       markDefined(*Symbol);
560     }
561     virtual void EmitSymbolAttribute(MCSymbol *Symbol, MCSymbolAttr Attribute) {
562       if (Attribute == MCSA_Global)
563         markGlobal(*Symbol);
564     }
565     virtual void EmitSymbolDesc(MCSymbol *Symbol, unsigned DescValue) {}
566     virtual void EmitWeakReference(MCSymbol *Alias, const MCSymbol *Symbol) {}
567     virtual void BeginCOFFSymbolDef(const MCSymbol *Symbol) {}
568     virtual void EmitCOFFSymbolStorageClass(int StorageClass) {}
569     virtual void EmitZerofill(const MCSection *Section, MCSymbol *Symbol,
570                               unsigned Size , unsigned ByteAlignment) {
571       markDefined(*Symbol);
572     }
573     virtual void EmitCOFFSymbolType(int Type) {}
574     virtual void EndCOFFSymbolDef() {}
575     virtual void EmitCommonSymbol(MCSymbol *Symbol, uint64_t Size,
576                                   unsigned ByteAlignment) {
577       markDefined(*Symbol);
578     }
579     virtual void EmitELFSize(MCSymbol *Symbol, const MCExpr *Value) {}
580     virtual void EmitLocalCommonSymbol(MCSymbol *Symbol, uint64_t Size) {}
581     virtual void EmitTBSSSymbol(const MCSection *Section, MCSymbol *Symbol,
582                                 uint64_t Size, unsigned ByteAlignment) {}
583     virtual void EmitBytes(StringRef Data, unsigned AddrSpace) {}
584     virtual void EmitValueImpl(const MCExpr *Value, unsigned Size,
585                                unsigned AddrSpace) {}
586     virtual void EmitULEB128Value(const MCExpr *Value) {}
587     virtual void EmitSLEB128Value(const MCExpr *Value) {}
588     virtual void EmitValueToAlignment(unsigned ByteAlignment, int64_t Value,
589                                       unsigned ValueSize,
590                                       unsigned MaxBytesToEmit) {}
591     virtual void EmitCodeAlignment(unsigned ByteAlignment,
592                                    unsigned MaxBytesToEmit) {}
593     virtual void EmitValueToOffset(const MCExpr *Offset,
594                                    unsigned char Value ) {}
595     virtual void EmitFileDirective(StringRef Filename) {}
596     virtual void EmitDwarfAdvanceLineAddr(int64_t LineDelta,
597                                           const MCSymbol *LastLabel,
598                                         const MCSymbol *Label) {}
599
600     virtual void EmitInstruction(const MCInst &Inst) {
601       // Scan for values.
602       for (unsigned i = Inst.getNumOperands(); i--; )
603         if (Inst.getOperand(i).isExpr())
604           AddValueSymbols(Inst.getOperand(i).getExpr());
605     }
606     virtual void Finish() {}
607   };
608 }
609
610 bool LTOModule::addAsmGlobalSymbols(MCContext &Context) {
611   const std::string &inlineAsm = _module->getModuleInlineAsm();
612
613   OwningPtr<RecordStreamer> Streamer(new RecordStreamer(Context));
614   MemoryBuffer *Buffer = MemoryBuffer::getMemBuffer(inlineAsm);
615   SourceMgr SrcMgr;
616   SrcMgr.AddNewSourceBuffer(Buffer, SMLoc());
617   OwningPtr<MCAsmParser> Parser(createMCAsmParser(_target->getTarget(), SrcMgr,
618                                                   Context, *Streamer,
619                                                   *_target->getMCAsmInfo()));
620   OwningPtr<TargetAsmParser>
621     TAP(_target->getTarget().createAsmParser(*Parser.get(), *_target.get()));
622   Parser->setTargetParser(*TAP);
623   int Res = Parser->Run(false);
624   if (Res)
625     return true;
626
627   for (RecordStreamer::const_iterator i = Streamer->begin(),
628          e = Streamer->end(); i != e; ++i) {
629     StringRef Key = i->first();
630     RecordStreamer::State Value = i->second;
631     if (Value == RecordStreamer::DefinedGlobal)
632       addAsmGlobalSymbol(Key.data(), LTO_SYMBOL_SCOPE_DEFAULT);
633     else if (Value == RecordStreamer::Defined)
634       addAsmGlobalSymbol(Key.data(), LTO_SYMBOL_SCOPE_INTERNAL);
635     else if (Value == RecordStreamer::Global ||
636              Value == RecordStreamer::Used)
637       addAsmGlobalSymbolUndef(Key.data());
638   }
639   return false;
640 }
641
642 static bool isDeclaration(const GlobalValue &V) {
643   if (V.hasAvailableExternallyLinkage())
644     return true;
645   if (V.isMaterializable())
646     return false;
647   return V.isDeclaration();
648 }
649
650 static bool isAliasToDeclaration(const GlobalAlias &V) {
651   return isDeclaration(*V.getAliasedGlobal());
652 }
653
654 bool LTOModule::ParseSymbols() {
655   // Use mangler to add GlobalPrefix to names to match linker names.
656   MCContext Context(*_target->getMCAsmInfo(), NULL);
657   Mangler mangler(Context, *_target->getTargetData());
658
659   // add functions
660   for (Module::iterator f = _module->begin(); f != _module->end(); ++f) {
661     if (isDeclaration(*f))
662       addPotentialUndefinedSymbol(f, mangler);
663     else
664       addDefinedFunctionSymbol(f, mangler);
665   }
666
667   // add data
668   for (Module::global_iterator v = _module->global_begin(),
669          e = _module->global_end(); v !=  e; ++v) {
670     if (isDeclaration(*v))
671       addPotentialUndefinedSymbol(v, mangler);
672     else
673       addDefinedDataSymbol(v, mangler);
674   }
675
676   // add asm globals
677   if (addAsmGlobalSymbols(Context))
678     return true;
679
680   // add aliases
681   for (Module::alias_iterator i = _module->alias_begin(),
682          e = _module->alias_end(); i != e; ++i) {
683     if (isAliasToDeclaration(*i))
684       addPotentialUndefinedSymbol(i, mangler);
685     else
686       addDefinedDataSymbol(i, mangler);
687   }
688
689   // make symbols for all undefines
690   for (StringMap<NameAndAttributes>::iterator it=_undefines.begin();
691        it != _undefines.end(); ++it) {
692     // if this symbol also has a definition, then don't make an undefine
693     // because it is a tentative definition
694     if (_defines.count(it->getKey()) == 0) {
695       NameAndAttributes info = it->getValue();
696       _symbols.push_back(info);
697     }
698   }
699   return false;
700 }
701
702
703 uint32_t LTOModule::getSymbolCount() {
704   return _symbols.size();
705 }
706
707
708 lto_symbol_attributes LTOModule::getSymbolAttributes(uint32_t index) {
709   if (index < _symbols.size())
710     return _symbols[index].attributes;
711   else
712     return lto_symbol_attributes(0);
713 }
714
715 const char *LTOModule::getSymbolName(uint32_t index) {
716   if (index < _symbols.size())
717     return _symbols[index].name;
718   else
719     return NULL;
720 }