Update getLazyBitcodeModule to use ErrorOr for error handling.
[oota-llvm.git] / lib / 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 "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"
42 using namespace llvm;
43
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(),
50                                    _context);
51 }
52
53 /// isBitcodeFile - Returns 'true' if the file (or memory contents) is LLVM
54 /// bitcode.
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;
58 }
59
60 bool LTOModule::isBitcodeFile(const char *path) {
61   sys::fs::file_magic type;
62   if (sys::fs::identify_magic(path, type))
63     return false;
64   return type == sys::fs::file_magic::bitcode;
65 }
66
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);
72   if (!buffer)
73     return false;
74   return isTargetMatch(buffer, triplePrefix);
75 }
76
77 bool LTOModule::isBitcodeFileForTarget(const char *path,
78                                        const char *triplePrefix) {
79   OwningPtr<MemoryBuffer> buffer;
80   if (MemoryBuffer::getFile(path, buffer))
81     return false;
82   return isTargetMatch(buffer.take(), triplePrefix);
83 }
84
85 /// isTargetMatch - Returns 'true' if the memory buffer is for the specified
86 /// target triple.
87 bool LTOModule::isTargetMatch(MemoryBuffer *buffer, const char *triplePrefix) {
88   std::string Triple = getBitcodeTargetTriple(buffer, getGlobalContext());
89   delete buffer;
90   return strncmp(Triple.c_str(), triplePrefix, strlen(triplePrefix)) == 0;
91 }
92
93 /// makeLTOModule - Create an LTOModule. N.B. These methods take ownership of
94 /// the buffer.
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();
100     return NULL;
101   }
102   return makeLTOModule(buffer.take(), options, errMsg);
103 }
104
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);
109 }
110
111 LTOModule *LTOModule::makeLTOModule(int fd, const char *path,
112                                     size_t map_size,
113                                     off_t offset,
114                                     TargetOptions options,
115                                     std::string &errMsg) {
116   OwningPtr<MemoryBuffer> buffer;
117   if (error_code ec =
118           MemoryBuffer::getOpenFileSlice(fd, path, buffer, map_size, offset)) {
119     errMsg = ec.message();
120     return NULL;
121   }
122   return makeLTOModule(buffer.take(), options, errMsg);
123 }
124
125 LTOModule *LTOModule::makeLTOModule(const void *mem, size_t length,
126                                     TargetOptions options,
127                                     std::string &errMsg) {
128   OwningPtr<MemoryBuffer> buffer(makeBuffer(mem, length));
129   if (!buffer)
130     return NULL;
131   return makeLTOModule(buffer.take(), options, errMsg);
132 }
133
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();
142     delete buffer;
143     return NULL;
144   }
145   OwningPtr<Module> m(ModuleOrErr.get());
146
147   std::string TripleStr = m->getTargetTriple();
148   if (TripleStr.empty())
149     TripleStr = sys::getDefaultTargetTriple();
150   llvm::Triple Triple(TripleStr);
151
152   // find machine architecture for this module
153   const Target *march = TargetRegistry::lookupTarget(TripleStr, errMsg);
154   if (!march)
155     return NULL;
156
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.
162   std::string CPU;
163   if (Triple.isOSDarwin()) {
164     if (Triple.getArch() == llvm::Triple::x86_64)
165       CPU = "core2";
166     else if (Triple.getArch() == llvm::Triple::x86)
167       CPU = "yonah";
168   }
169
170   TargetMachine *target = march->createTargetMachine(TripleStr, CPU, FeatureStr,
171                                                      options);
172   m->MaterializeAllPermanently();
173
174   LTOModule *Ret = new LTOModule(m.take(), target);
175   if (Ret->parseSymbols(errMsg)) {
176     delete Ret;
177     return NULL;
178   }
179
180   return Ret;
181 }
182
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);
187 }
188
189 /// objcClassNameFromExpression - Get string that the data pointer points to.
190 bool
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();
199           return true;
200         }
201       }
202     }
203   }
204   return false;
205 }
206
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());
210   if (!c) return;
211
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;
223       info.symbol = clgv;
224       entry.setValue(info);
225     }
226   }
227
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);
232     entry.setValue(1);
233
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;
239     info.symbol = clgv;
240     _symbols.push_back(info);
241   }
242 }
243
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());
247   if (!c) return;
248
249   // second slot in __OBJC,__category is pointer to target class name
250   std::string targetclassName;
251   if (!objcClassNameFromExpression(c->getOperand(1), targetclassName))
252     return;
253
254   NameAndAttributes info;
255   StringMap<NameAndAttributes>::value_type &entry =
256     _undefines.GetOrCreateValue(targetclassName);
257
258   if (entry.getValue().name)
259     return;
260
261   const char *symbolName = entry.getKey().data();
262   info.name = symbolName;
263   info.attributes = LTO_SYMBOL_DEFINITION_UNDEFINED;
264   info.isFunction = false;
265   info.symbol = clgv;
266   entry.setValue(info);
267 }
268
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))
273     return;
274
275   NameAndAttributes info;
276   StringMap<NameAndAttributes>::value_type &entry =
277     _undefines.GetOrCreateValue(targetclassName);
278   if (entry.getValue().name)
279     return;
280
281   const char *symbolName = entry.getKey().data();
282   info.name = symbolName;
283   info.attributes = LTO_SYMBOL_DEFINITION_UNDEFINED;
284   info.isFunction = false;
285   info.symbol = clgv;
286   entry.setValue(info);
287 }
288
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);
293
294   if (!v->hasSection() /* || !isTargetDarwin */)
295     return;
296
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.
316
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)) {
320       addObjCClass(gv);
321     }
322   }
323
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)) {
327       addObjCCategory(gv);
328     }
329   }
330
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)) {
334       addObjCClassRef(gv);
335     }
336   }
337 }
338
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);
343 }
344
345 static bool canBeHidden(const GlobalValue *GV) {
346   GlobalValue::LinkageTypes L = GV->getLinkage();
347
348   if (L != GlobalValue::LinkOnceODRLinkage)
349     return false;
350
351   if (GV->hasUnnamedAddr())
352     return true;
353
354   GlobalStatus GS;
355   if (GlobalStatus::analyzeGlobal(GV, GS))
356     return false;
357
358   return !GS.IsCompared;
359 }
360
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."))
365     return;
366
367   // string is owned by _defines
368   SmallString<64> Buffer;
369   _mangler.getNameWithPrefix(Buffer, def);
370
371   // set alignment part log2() can have rounding errors
372   uint32_t align = def->getAlignment();
373   uint32_t attr = align ? countTrailingZeros(def->getAlignment()) : 0;
374
375   // set permissions part
376   if (isFunction) {
377     attr |= LTO_SYMBOL_PERMISSIONS_CODE;
378   } else {
379     const GlobalVariable *gv = dyn_cast<GlobalVariable>(def);
380     if (gv && gv->isConstant())
381       attr |= LTO_SYMBOL_PERMISSIONS_RODATA;
382     else
383       attr |= LTO_SYMBOL_PERMISSIONS_DATA;
384   }
385
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;
392   else
393     attr |= LTO_SYMBOL_DEFINITION_REGULAR;
394
395   // set scope part
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;
406   else
407     attr |= LTO_SYMBOL_SCOPE_INTERNAL;
408
409   StringSet::value_type &entry = _defines.GetOrCreateValue(Buffer);
410   entry.setValue(1);
411
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;
419   info.symbol = def;
420
421   // add to table of symbols
422   _symbols.push_back(info);
423 }
424
425 /// addAsmGlobalSymbol - Add a global symbol from module-level ASM to the
426 /// defined list.
427 void LTOModule::addAsmGlobalSymbol(const char *name,
428                                    lto_symbol_attributes scope) {
429   StringSet::value_type &entry = _defines.GetOrCreateValue(name);
430
431   // only add new define if not already defined
432   if (entry.getValue())
433     return;
434
435   entry.setValue(1);
436
437   NameAndAttributes &info = _undefines[entry.getKey().data()];
438
439   if (info.symbol == 0) {
440     // FIXME: This is trying to take care of module ASM like this:
441     //
442     //   module asm ".zerofill __FOO, __foo, _bar_baz_qux, 0"
443     //
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
446     // much.
447
448     // fill information structure
449     info.name = entry.getKey().data();
450     info.attributes =
451       LTO_SYMBOL_PERMISSIONS_DATA | LTO_SYMBOL_DEFINITION_REGULAR | scope;
452     info.isFunction = false;
453     info.symbol = 0;
454
455     // add to table of symbols
456     _symbols.push_back(info);
457     return;
458   }
459
460   if (info.isFunction)
461     addDefinedFunctionSymbol(cast<Function>(info.symbol));
462   else
463     addDefinedDataSymbol(info.symbol);
464
465   _symbols.back().attributes &= ~LTO_SYMBOL_SCOPE_MASK;
466   _symbols.back().attributes |= scope;
467 }
468
469 /// addAsmGlobalSymbolUndef - Add a global symbol from module-level ASM to the
470 /// undefined list.
471 void LTOModule::addAsmGlobalSymbolUndef(const char *name) {
472   StringMap<NameAndAttributes>::value_type &entry =
473     _undefines.GetOrCreateValue(name);
474
475   _asm_undefines.push_back(entry.getKey().data());
476
477   // we already have the symbol
478   if (entry.getValue().name)
479     return;
480
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;
487   info.symbol = 0;
488
489   entry.setValue(info);
490 }
491
492 /// addPotentialUndefinedSymbol - Add a symbol which isn't defined just yet to a
493 /// list to be resolved later.
494 void
495 LTOModule::addPotentialUndefinedSymbol(const GlobalValue *decl, bool isFunc) {
496   // ignore all llvm.* symbols
497   if (decl->getName().startswith("llvm."))
498     return;
499
500   // ignore all aliases
501   if (isa<GlobalAlias>(decl))
502     return;
503
504   SmallString<64> name;
505   _mangler.getNameWithPrefix(name, decl);
506
507   StringMap<NameAndAttributes>::value_type &entry =
508     _undefines.GetOrCreateValue(name);
509
510   // we already have the symbol
511   if (entry.getValue().name)
512     return;
513
514   NameAndAttributes info;
515
516   info.name = entry.getKey().data();
517
518   if (decl->hasExternalWeakLinkage())
519     info.attributes = LTO_SYMBOL_DEFINITION_WEAKUNDEF;
520   else
521     info.attributes = LTO_SYMBOL_DEFINITION_UNDEFINED;
522
523   info.isFunction = isFunc;
524   info.symbol = decl;
525
526   entry.setValue(info);
527 }
528
529 namespace {
530   class RecordStreamer : public MCStreamer {
531   public:
532     enum State { NeverSeen, Global, Defined, DefinedGlobal, Used };
533
534   private:
535     StringMap<State> Symbols;
536
537     void markDefined(const MCSymbol &Symbol) {
538       State &S = Symbols[Symbol.getName()];
539       switch (S) {
540       case DefinedGlobal:
541       case Global:
542         S = DefinedGlobal;
543         break;
544       case NeverSeen:
545       case Defined:
546       case Used:
547         S = Defined;
548         break;
549       }
550     }
551     void markGlobal(const MCSymbol &Symbol) {
552       State &S = Symbols[Symbol.getName()];
553       switch (S) {
554       case DefinedGlobal:
555       case Defined:
556         S = DefinedGlobal;
557         break;
558
559       case NeverSeen:
560       case Global:
561       case Used:
562         S = Global;
563         break;
564       }
565     }
566     void markUsed(const MCSymbol &Symbol) {
567       State &S = Symbols[Symbol.getName()];
568       switch (S) {
569       case DefinedGlobal:
570       case Defined:
571       case Global:
572         break;
573
574       case NeverSeen:
575       case Used:
576         S = Used;
577         break;
578       }
579     }
580
581     // FIXME: mostly copied for the obj streamer.
582     void AddValueSymbols(const MCExpr *Value) {
583       switch (Value->getKind()) {
584       case MCExpr::Target:
585         // FIXME: What should we do in here?
586         break;
587
588       case MCExpr::Constant:
589         break;
590
591       case MCExpr::Binary: {
592         const MCBinaryExpr *BE = cast<MCBinaryExpr>(Value);
593         AddValueSymbols(BE->getLHS());
594         AddValueSymbols(BE->getRHS());
595         break;
596       }
597
598       case MCExpr::SymbolRef:
599         markUsed(cast<MCSymbolRefExpr>(Value)->getSymbol());
600         break;
601
602       case MCExpr::Unary:
603         AddValueSymbols(cast<MCUnaryExpr>(Value)->getSubExpr());
604         break;
605       }
606     }
607
608   public:
609     typedef StringMap<State>::const_iterator const_iterator;
610
611     const_iterator begin() {
612       return Symbols.begin();
613     }
614
615     const_iterator end() {
616       return Symbols.end();
617     }
618
619     RecordStreamer(MCContext &Context) : MCStreamer(Context, 0) {}
620
621     virtual void EmitInstruction(const MCInst &Inst) {
622       // Scan for values.
623       for (unsigned i = Inst.getNumOperands(); i--; )
624         if (Inst.getOperand(i).isExpr())
625           AddValueSymbols(Inst.getOperand(i).getExpr());
626     }
627     virtual void EmitLabel(MCSymbol *Symbol) {
628       Symbol->setSection(*getCurrentSection().first);
629       markDefined(*Symbol);
630     }
631     virtual void EmitDebugLabel(MCSymbol *Symbol) {
632       EmitLabel(Symbol);
633     }
634     virtual void EmitAssignment(MCSymbol *Symbol, const MCExpr *Value) {
635       // FIXME: should we handle aliases?
636       markDefined(*Symbol);
637     }
638     virtual bool EmitSymbolAttribute(MCSymbol *Symbol, MCSymbolAttr Attribute) {
639       if (Attribute == MCSA_Global)
640         markGlobal(*Symbol);
641       return true;
642     }
643     virtual void EmitZerofill(const MCSection *Section, MCSymbol *Symbol,
644                               uint64_t Size , unsigned ByteAlignment) {
645       markDefined(*Symbol);
646     }
647     virtual void EmitCommonSymbol(MCSymbol *Symbol, uint64_t Size,
648                                   unsigned ByteAlignment) {
649       markDefined(*Symbol);
650     }
651
652     virtual void EmitBundleAlignMode(unsigned AlignPow2) {}
653     virtual void EmitBundleLock(bool AlignToEnd) {}
654     virtual void EmitBundleUnlock() {}
655
656     // Noop calls.
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,
679                                       unsigned ValueSize,
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);
693     }
694   };
695 } // end anonymous namespace
696
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())
702     return false;
703
704   OwningPtr<RecordStreamer> Streamer(new RecordStreamer(_context));
705   MemoryBuffer *Buffer = MemoryBuffer::getMemBuffer(inlineAsm);
706   SourceMgr SrcMgr;
707   SrcMgr.AddNewSourceBuffer(Buffer, SMLoc());
708   OwningPtr<MCAsmParser> Parser(createMCAsmParser(SrcMgr,
709                                                   _context, *Streamer,
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));
718   if (!TAP) {
719     errMsg = "target " + std::string(T.getName()) +
720       " does not define AsmParser.";
721     return true;
722   }
723
724   Parser->setTargetParser(*TAP);
725   if (Parser->Run(false))
726     return true;
727
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());
739   }
740
741   return false;
742 }
743
744 /// isDeclaration - Return 'true' if the global value is a declaration.
745 static bool isDeclaration(const GlobalValue &V) {
746   if (V.hasAvailableExternallyLinkage())
747     return true;
748
749   if (V.isMaterializable())
750     return false;
751
752   return V.isDeclaration();
753 }
754
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) {
758   // add functions
759   for (Module::iterator f = _module->begin(), e = _module->end(); f != e; ++f) {
760     if (isDeclaration(*f))
761       addPotentialUndefinedSymbol(f, true);
762     else
763       addDefinedFunctionSymbol(f);
764   }
765
766   // add data
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);
771     else
772       addDefinedDataSymbol(v);
773   }
774
775   // add asm globals
776   if (addAsmGlobalSymbols(errMsg))
777     return true;
778
779   // add aliases
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);
785     else
786       addDefinedDataSymbol(a);
787   }
788
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);
797   }
798
799   return false;
800 }