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