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