91240aa5a0010d082c0fd6dd5191d3e49206900c
[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/Host.h"
33 #include "llvm/Support/FileSystem.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(), NULL),
47     _mangler(t) {}
48
49 /// isBitcodeFile - Returns 'true' if the file (or memory contents) is LLVM
50 /// bitcode.
51 bool LTOModule::isBitcodeFile(const void *mem, size_t length) {
52   return sys::fs::identify_magic(StringRef((const char *)mem, length)) ==
53          sys::fs::file_magic::bitcode;
54 }
55
56 bool LTOModule::isBitcodeFile(const char *path) {
57   sys::fs::file_magic type;
58   if (sys::fs::identify_magic(path, type))
59     return false;
60   return type == sys::fs::file_magic::bitcode;
61 }
62
63 /// isBitcodeFileForTarget - Returns 'true' if the file (or memory contents) is
64 /// LLVM bitcode for the specified triple.
65 bool LTOModule::isBitcodeFileForTarget(const void *mem, size_t length,
66                                        const char *triplePrefix) {
67   MemoryBuffer *buffer = makeBuffer(mem, length);
68   if (!buffer)
69     return false;
70   return isTargetMatch(buffer, triplePrefix);
71 }
72
73 bool LTOModule::isBitcodeFileForTarget(const char *path,
74                                        const char *triplePrefix) {
75   OwningPtr<MemoryBuffer> buffer;
76   if (MemoryBuffer::getFile(path, buffer))
77     return false;
78   return isTargetMatch(buffer.take(), triplePrefix);
79 }
80
81 /// isTargetMatch - Returns 'true' if the memory buffer is for the specified
82 /// target triple.
83 bool LTOModule::isTargetMatch(MemoryBuffer *buffer, const char *triplePrefix) {
84   std::string Triple = getBitcodeTargetTriple(buffer, getGlobalContext());
85   delete buffer;
86   return strncmp(Triple.c_str(), triplePrefix, strlen(triplePrefix)) == 0;
87 }
88
89 /// makeLTOModule - Create an LTOModule. N.B. These methods take ownership of
90 /// the buffer.
91 LTOModule *LTOModule::makeLTOModule(const char *path, TargetOptions options,
92                                     std::string &errMsg) {
93   OwningPtr<MemoryBuffer> buffer;
94   if (error_code ec = MemoryBuffer::getFile(path, buffer)) {
95     errMsg = ec.message();
96     return NULL;
97   }
98   return makeLTOModule(buffer.take(), options, errMsg);
99 }
100
101 LTOModule *LTOModule::makeLTOModule(int fd, const char *path,
102                                     size_t size, TargetOptions options,
103                                     std::string &errMsg) {
104   return makeLTOModule(fd, path, size, 0, options, errMsg);
105 }
106
107 LTOModule *LTOModule::makeLTOModule(int fd, const char *path,
108                                     size_t map_size,
109                                     off_t offset,
110                                     TargetOptions options,
111                                     std::string &errMsg) {
112   OwningPtr<MemoryBuffer> buffer;
113   if (error_code ec =
114           MemoryBuffer::getOpenFileSlice(fd, path, buffer, map_size, offset)) {
115     errMsg = ec.message();
116     return NULL;
117   }
118   return makeLTOModule(buffer.take(), options, errMsg);
119 }
120
121 LTOModule *LTOModule::makeLTOModule(const void *mem, size_t length,
122                                     TargetOptions options,
123                                     std::string &errMsg) {
124   OwningPtr<MemoryBuffer> buffer(makeBuffer(mem, length));
125   if (!buffer)
126     return NULL;
127   return makeLTOModule(buffer.take(), options, errMsg);
128 }
129
130 LTOModule *LTOModule::makeLTOModule(MemoryBuffer *buffer,
131                                     TargetOptions options,
132                                     std::string &errMsg) {
133   // parse bitcode buffer
134   OwningPtr<Module> m(getLazyBitcodeModule(buffer, getGlobalContext(),
135                                            &errMsg));
136   if (!m) {
137     delete buffer;
138     return NULL;
139   }
140
141   std::string TripleStr = m->getTargetTriple();
142   if (TripleStr.empty())
143     TripleStr = sys::getDefaultTargetTriple();
144   llvm::Triple Triple(TripleStr);
145
146   // find machine architecture for this module
147   const Target *march = TargetRegistry::lookupTarget(TripleStr, errMsg);
148   if (!march)
149     return NULL;
150
151   // construct LTOModule, hand over ownership of module and target
152   SubtargetFeatures Features;
153   Features.getDefaultSubtargetFeatures(Triple);
154   std::string FeatureStr = Features.getString();
155   // Set a default CPU for Darwin triples.
156   std::string CPU;
157   if (Triple.isOSDarwin()) {
158     if (Triple.getArch() == llvm::Triple::x86_64)
159       CPU = "core2";
160     else if (Triple.getArch() == llvm::Triple::x86)
161       CPU = "yonah";
162   }
163
164   TargetMachine *target = march->createTargetMachine(TripleStr, CPU, FeatureStr,
165                                                      options);
166   m->MaterializeAllPermanently();
167
168   LTOModule *Ret = new LTOModule(m.take(), target);
169   if (Ret->parseSymbols(errMsg)) {
170     delete Ret;
171     return NULL;
172   }
173
174   return Ret;
175 }
176
177 /// makeBuffer - Create a MemoryBuffer from a memory range.
178 MemoryBuffer *LTOModule::makeBuffer(const void *mem, size_t length) {
179   const char *startPtr = (const char*)mem;
180   return MemoryBuffer::getMemBuffer(StringRef(startPtr, length), "", false);
181 }
182
183 /// objcClassNameFromExpression - Get string that the data pointer points to.
184 bool
185 LTOModule::objcClassNameFromExpression(const Constant *c, std::string &name) {
186   if (const ConstantExpr *ce = dyn_cast<ConstantExpr>(c)) {
187     Constant *op = ce->getOperand(0);
188     if (GlobalVariable *gvn = dyn_cast<GlobalVariable>(op)) {
189       Constant *cn = gvn->getInitializer();
190       if (ConstantDataArray *ca = dyn_cast<ConstantDataArray>(cn)) {
191         if (ca->isCString()) {
192           name = ".objc_class_name_" + ca->getAsCString().str();
193           return true;
194         }
195       }
196     }
197   }
198   return false;
199 }
200
201 /// addObjCClass - Parse i386/ppc ObjC class data structure.
202 void LTOModule::addObjCClass(const GlobalVariable *clgv) {
203   const ConstantStruct *c = dyn_cast<ConstantStruct>(clgv->getInitializer());
204   if (!c) return;
205
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       info.isFunction = false;
217       info.symbol = clgv;
218       entry.setValue(info);
219     }
220   }
221
222   // third slot in __OBJC,__class is pointer to class name
223   std::string className;
224   if (objcClassNameFromExpression(c->getOperand(2), className)) {
225     StringSet::value_type &entry = _defines.GetOrCreateValue(className);
226     entry.setValue(1);
227
228     NameAndAttributes info;
229     info.name = entry.getKey().data();
230     info.attributes = LTO_SYMBOL_PERMISSIONS_DATA |
231       LTO_SYMBOL_DEFINITION_REGULAR | LTO_SYMBOL_SCOPE_DEFAULT;
232     info.isFunction = false;
233     info.symbol = clgv;
234     _symbols.push_back(info);
235   }
236 }
237
238 /// addObjCCategory - Parse i386/ppc ObjC category data structure.
239 void LTOModule::addObjCCategory(const GlobalVariable *clgv) {
240   const ConstantStruct *c = dyn_cast<ConstantStruct>(clgv->getInitializer());
241   if (!c) return;
242
243   // second slot in __OBJC,__category is pointer to target class name
244   std::string targetclassName;
245   if (!objcClassNameFromExpression(c->getOperand(1), targetclassName))
246     return;
247
248   NameAndAttributes info;
249   StringMap<NameAndAttributes>::value_type &entry =
250     _undefines.GetOrCreateValue(targetclassName);
251
252   if (entry.getValue().name)
253     return;
254
255   const char *symbolName = entry.getKey().data();
256   info.name = symbolName;
257   info.attributes = LTO_SYMBOL_DEFINITION_UNDEFINED;
258   info.isFunction = false;
259   info.symbol = clgv;
260   entry.setValue(info);
261 }
262
263 /// addObjCClassRef - Parse i386/ppc ObjC class list data structure.
264 void LTOModule::addObjCClassRef(const GlobalVariable *clgv) {
265   std::string targetclassName;
266   if (!objcClassNameFromExpression(clgv->getInitializer(), targetclassName))
267     return;
268
269   NameAndAttributes info;
270   StringMap<NameAndAttributes>::value_type &entry =
271     _undefines.GetOrCreateValue(targetclassName);
272   if (entry.getValue().name)
273     return;
274
275   const char *symbolName = entry.getKey().data();
276   info.name = symbolName;
277   info.attributes = LTO_SYMBOL_DEFINITION_UNDEFINED;
278   info.isFunction = false;
279   info.symbol = clgv;
280   entry.setValue(info);
281 }
282
283 /// addDefinedDataSymbol - Add a data symbol as defined to the list.
284 void LTOModule::addDefinedDataSymbol(const GlobalValue *v) {
285   // Add to list of defined symbols.
286   addDefinedSymbol(v, false);
287
288   if (!v->hasSection() /* || !isTargetDarwin */)
289     return;
290
291   // Special case i386/ppc ObjC data structures in magic sections:
292   // The issue is that the old ObjC object format did some strange
293   // contortions to avoid real linker symbols.  For instance, the
294   // ObjC class data structure is allocated statically in the executable
295   // that defines that class.  That data structures contains a pointer to
296   // its superclass.  But instead of just initializing that part of the
297   // struct to the address of its superclass, and letting the static and
298   // dynamic linkers do the rest, the runtime works by having that field
299   // instead point to a C-string that is the name of the superclass.
300   // At runtime the objc initialization updates that pointer and sets
301   // it to point to the actual super class.  As far as the linker
302   // knows it is just a pointer to a string.  But then someone wanted the
303   // linker to issue errors at build time if the superclass was not found.
304   // So they figured out a way in mach-o object format to use an absolute
305   // symbols (.objc_class_name_Foo = 0) and a floating reference
306   // (.reference .objc_class_name_Bar) to cause the linker into erroring when
307   // a class was missing.
308   // The following synthesizes the implicit .objc_* symbols for the linker
309   // from the ObjC data structures generated by the front end.
310
311   // special case if this data blob is an ObjC class definition
312   if (v->getSection().compare(0, 15, "__OBJC,__class,") == 0) {
313     if (const GlobalVariable *gv = dyn_cast<GlobalVariable>(v)) {
314       addObjCClass(gv);
315     }
316   }
317
318   // special case if this data blob is an ObjC category definition
319   else if (v->getSection().compare(0, 18, "__OBJC,__category,") == 0) {
320     if (const GlobalVariable *gv = dyn_cast<GlobalVariable>(v)) {
321       addObjCCategory(gv);
322     }
323   }
324
325   // special case if this data blob is the list of referenced classes
326   else if (v->getSection().compare(0, 18, "__OBJC,__cls_refs,") == 0) {
327     if (const GlobalVariable *gv = dyn_cast<GlobalVariable>(v)) {
328       addObjCClassRef(gv);
329     }
330   }
331 }
332
333 /// addDefinedFunctionSymbol - Add a function symbol as defined to the list.
334 void LTOModule::addDefinedFunctionSymbol(const Function *f) {
335   // add to list of defined symbols
336   addDefinedSymbol(f, true);
337 }
338
339 static bool canBeHidden(const GlobalValue *GV) {
340   GlobalValue::LinkageTypes L = GV->getLinkage();
341
342   if (L == GlobalValue::LinkOnceODRAutoHideLinkage)
343     return true;
344
345   if (L != GlobalValue::LinkOnceODRLinkage)
346     return false;
347
348   if (GV->hasUnnamedAddr())
349     return true;
350
351   GlobalStatus GS;
352   if (GlobalStatus::analyzeGlobal(GV, GS))
353     return false;
354
355   return !GS.IsCompared;
356 }
357
358 /// addDefinedSymbol - Add a defined symbol to the list.
359 void LTOModule::addDefinedSymbol(const GlobalValue *def, bool isFunction) {
360   // ignore all llvm.* symbols
361   if (def->getName().startswith("llvm."))
362     return;
363
364   // string is owned by _defines
365   SmallString<64> Buffer;
366   _mangler.getNameWithPrefix(Buffer, def, false);
367
368   // set alignment part log2() can have rounding errors
369   uint32_t align = def->getAlignment();
370   uint32_t attr = align ? countTrailingZeros(def->getAlignment()) : 0;
371
372   // set permissions part
373   if (isFunction) {
374     attr |= LTO_SYMBOL_PERMISSIONS_CODE;
375   } else {
376     const GlobalVariable *gv = dyn_cast<GlobalVariable>(def);
377     if (gv && gv->isConstant())
378       attr |= LTO_SYMBOL_PERMISSIONS_RODATA;
379     else
380       attr |= LTO_SYMBOL_PERMISSIONS_DATA;
381   }
382
383   // set definition part
384   if (def->hasWeakLinkage() || def->hasLinkOnceLinkage() ||
385       def->hasLinkerPrivateWeakLinkage())
386     attr |= LTO_SYMBOL_DEFINITION_WEAK;
387   else if (def->hasCommonLinkage())
388     attr |= LTO_SYMBOL_DEFINITION_TENTATIVE;
389   else
390     attr |= LTO_SYMBOL_DEFINITION_REGULAR;
391
392   // set scope part
393   if (def->hasHiddenVisibility())
394     attr |= LTO_SYMBOL_SCOPE_HIDDEN;
395   else if (def->hasProtectedVisibility())
396     attr |= LTO_SYMBOL_SCOPE_PROTECTED;
397   else if (canBeHidden(def))
398     attr |= LTO_SYMBOL_SCOPE_DEFAULT_CAN_BE_HIDDEN;
399   else if (def->hasExternalLinkage() || def->hasWeakLinkage() ||
400            def->hasLinkOnceLinkage() || def->hasCommonLinkage() ||
401            def->hasLinkerPrivateWeakLinkage())
402     attr |= LTO_SYMBOL_SCOPE_DEFAULT;
403   else
404     attr |= LTO_SYMBOL_SCOPE_INTERNAL;
405
406   StringSet::value_type &entry = _defines.GetOrCreateValue(Buffer);
407   entry.setValue(1);
408
409   // fill information structure
410   NameAndAttributes info;
411   StringRef Name = entry.getKey();
412   info.name = Name.data();
413   assert(info.name[Name.size()] == '\0');
414   info.attributes = attr;
415   info.isFunction = isFunction;
416   info.symbol = def;
417
418   // add to table of symbols
419   _symbols.push_back(info);
420 }
421
422 /// addAsmGlobalSymbol - Add a global symbol from module-level ASM to the
423 /// defined list.
424 void LTOModule::addAsmGlobalSymbol(const char *name,
425                                    lto_symbol_attributes scope) {
426   StringSet::value_type &entry = _defines.GetOrCreateValue(name);
427
428   // only add new define if not already defined
429   if (entry.getValue())
430     return;
431
432   entry.setValue(1);
433
434   NameAndAttributes &info = _undefines[entry.getKey().data()];
435
436   if (info.symbol == 0) {
437     // FIXME: This is trying to take care of module ASM like this:
438     //
439     //   module asm ".zerofill __FOO, __foo, _bar_baz_qux, 0"
440     //
441     // but is gross and its mother dresses it funny. Have the ASM parser give us
442     // more details for this type of situation so that we're not guessing so
443     // much.
444
445     // fill information structure
446     info.name = entry.getKey().data();
447     info.attributes =
448       LTO_SYMBOL_PERMISSIONS_DATA | LTO_SYMBOL_DEFINITION_REGULAR | scope;
449     info.isFunction = false;
450     info.symbol = 0;
451
452     // add to table of symbols
453     _symbols.push_back(info);
454     return;
455   }
456
457   if (info.isFunction)
458     addDefinedFunctionSymbol(cast<Function>(info.symbol));
459   else
460     addDefinedDataSymbol(info.symbol);
461
462   _symbols.back().attributes &= ~LTO_SYMBOL_SCOPE_MASK;
463   _symbols.back().attributes |= scope;
464 }
465
466 /// addAsmGlobalSymbolUndef - Add a global symbol from module-level ASM to the
467 /// undefined list.
468 void LTOModule::addAsmGlobalSymbolUndef(const char *name) {
469   StringMap<NameAndAttributes>::value_type &entry =
470     _undefines.GetOrCreateValue(name);
471
472   _asm_undefines.push_back(entry.getKey().data());
473
474   // we already have the symbol
475   if (entry.getValue().name)
476     return;
477
478   uint32_t attr = LTO_SYMBOL_DEFINITION_UNDEFINED;;
479   attr |= LTO_SYMBOL_SCOPE_DEFAULT;
480   NameAndAttributes info;
481   info.name = entry.getKey().data();
482   info.attributes = attr;
483   info.isFunction = false;
484   info.symbol = 0;
485
486   entry.setValue(info);
487 }
488
489 /// addPotentialUndefinedSymbol - Add a symbol which isn't defined just yet to a
490 /// list to be resolved later.
491 void
492 LTOModule::addPotentialUndefinedSymbol(const GlobalValue *decl, bool isFunc) {
493   // ignore all llvm.* symbols
494   if (decl->getName().startswith("llvm."))
495     return;
496
497   // ignore all aliases
498   if (isa<GlobalAlias>(decl))
499     return;
500
501   SmallString<64> name;
502   _mangler.getNameWithPrefix(name, decl, false);
503
504   StringMap<NameAndAttributes>::value_type &entry =
505     _undefines.GetOrCreateValue(name);
506
507   // we already have the symbol
508   if (entry.getValue().name)
509     return;
510
511   NameAndAttributes info;
512
513   info.name = entry.getKey().data();
514
515   if (decl->hasExternalWeakLinkage())
516     info.attributes = LTO_SYMBOL_DEFINITION_WEAKUNDEF;
517   else
518     info.attributes = LTO_SYMBOL_DEFINITION_UNDEFINED;
519
520   info.isFunction = isFunc;
521   info.symbol = decl;
522
523   entry.setValue(info);
524 }
525
526 namespace {
527   class RecordStreamer : public MCStreamer {
528   public:
529     enum State { NeverSeen, Global, Defined, DefinedGlobal, Used };
530
531   private:
532     StringMap<State> Symbols;
533
534     void markDefined(const MCSymbol &Symbol) {
535       State &S = Symbols[Symbol.getName()];
536       switch (S) {
537       case DefinedGlobal:
538       case Global:
539         S = DefinedGlobal;
540         break;
541       case NeverSeen:
542       case Defined:
543       case Used:
544         S = Defined;
545         break;
546       }
547     }
548     void markGlobal(const MCSymbol &Symbol) {
549       State &S = Symbols[Symbol.getName()];
550       switch (S) {
551       case DefinedGlobal:
552       case Defined:
553         S = DefinedGlobal;
554         break;
555
556       case NeverSeen:
557       case Global:
558       case Used:
559         S = Global;
560         break;
561       }
562     }
563     void markUsed(const MCSymbol &Symbol) {
564       State &S = Symbols[Symbol.getName()];
565       switch (S) {
566       case DefinedGlobal:
567       case Defined:
568       case Global:
569         break;
570
571       case NeverSeen:
572       case Used:
573         S = Used;
574         break;
575       }
576     }
577
578     // FIXME: mostly copied for the obj streamer.
579     void AddValueSymbols(const MCExpr *Value) {
580       switch (Value->getKind()) {
581       case MCExpr::Target:
582         // FIXME: What should we do in here?
583         break;
584
585       case MCExpr::Constant:
586         break;
587
588       case MCExpr::Binary: {
589         const MCBinaryExpr *BE = cast<MCBinaryExpr>(Value);
590         AddValueSymbols(BE->getLHS());
591         AddValueSymbols(BE->getRHS());
592         break;
593       }
594
595       case MCExpr::SymbolRef:
596         markUsed(cast<MCSymbolRefExpr>(Value)->getSymbol());
597         break;
598
599       case MCExpr::Unary:
600         AddValueSymbols(cast<MCUnaryExpr>(Value)->getSubExpr());
601         break;
602       }
603     }
604
605   public:
606     typedef StringMap<State>::const_iterator const_iterator;
607
608     const_iterator begin() {
609       return Symbols.begin();
610     }
611
612     const_iterator end() {
613       return Symbols.end();
614     }
615
616     RecordStreamer(MCContext &Context) : MCStreamer(Context, 0) {}
617
618     virtual void EmitInstruction(const MCInst &Inst) {
619       // Scan for values.
620       for (unsigned i = Inst.getNumOperands(); i--; )
621         if (Inst.getOperand(i).isExpr())
622           AddValueSymbols(Inst.getOperand(i).getExpr());
623     }
624     virtual void EmitLabel(MCSymbol *Symbol) {
625       Symbol->setSection(*getCurrentSection().first);
626       markDefined(*Symbol);
627     }
628     virtual void EmitDebugLabel(MCSymbol *Symbol) {
629       EmitLabel(Symbol);
630     }
631     virtual void EmitAssignment(MCSymbol *Symbol, const MCExpr *Value) {
632       // FIXME: should we handle aliases?
633       markDefined(*Symbol);
634     }
635     virtual bool EmitSymbolAttribute(MCSymbol *Symbol, MCSymbolAttr Attribute) {
636       if (Attribute == MCSA_Global)
637         markGlobal(*Symbol);
638       return true;
639     }
640     virtual void EmitZerofill(const MCSection *Section, MCSymbol *Symbol,
641                               uint64_t Size , unsigned ByteAlignment) {
642       markDefined(*Symbol);
643     }
644     virtual void EmitCommonSymbol(MCSymbol *Symbol, uint64_t Size,
645                                   unsigned ByteAlignment) {
646       markDefined(*Symbol);
647     }
648
649     virtual void EmitBundleAlignMode(unsigned AlignPow2) {}
650     virtual void EmitBundleLock(bool AlignToEnd) {}
651     virtual void EmitBundleUnlock() {}
652
653     // Noop calls.
654     virtual void ChangeSection(const MCSection *Section,
655                                const MCExpr *Subsection) {}
656     virtual void InitToTextSection() {}
657     virtual void InitSections() {}
658     virtual void EmitAssemblerFlag(MCAssemblerFlag Flag) {}
659     virtual void EmitThumbFunc(MCSymbol *Func) {}
660     virtual void EmitSymbolDesc(MCSymbol *Symbol, unsigned DescValue) {}
661     virtual void EmitWeakReference(MCSymbol *Alias, const MCSymbol *Symbol) {}
662     virtual void BeginCOFFSymbolDef(const MCSymbol *Symbol) {}
663     virtual void EmitCOFFSymbolStorageClass(int StorageClass) {}
664     virtual void EmitCOFFSymbolType(int Type) {}
665     virtual void EndCOFFSymbolDef() {}
666     virtual void EmitELFSize(MCSymbol *Symbol, const MCExpr *Value) {}
667     virtual void EmitLocalCommonSymbol(MCSymbol *Symbol, uint64_t Size,
668                                        unsigned ByteAlignment) {}
669     virtual void EmitTBSSSymbol(const MCSection *Section, MCSymbol *Symbol,
670                                 uint64_t Size, unsigned ByteAlignment) {}
671     virtual void EmitBytes(StringRef Data) {}
672     virtual void EmitValueImpl(const MCExpr *Value, unsigned Size) {}
673     virtual void EmitULEB128Value(const MCExpr *Value) {}
674     virtual void EmitSLEB128Value(const MCExpr *Value) {}
675     virtual void EmitValueToAlignment(unsigned ByteAlignment, int64_t Value,
676                                       unsigned ValueSize,
677                                       unsigned MaxBytesToEmit) {}
678     virtual void EmitCodeAlignment(unsigned ByteAlignment,
679                                    unsigned MaxBytesToEmit) {}
680     virtual bool EmitValueToOffset(const MCExpr *Offset,
681                                    unsigned char Value ) { return false; }
682     virtual void EmitFileDirective(StringRef Filename) {}
683     virtual void EmitDwarfAdvanceLineAddr(int64_t LineDelta,
684                                           const MCSymbol *LastLabel,
685                                           const MCSymbol *Label,
686                                           unsigned PointerSize) {}
687     virtual void FinishImpl() {}
688     virtual void EmitCFIEndProcImpl(MCDwarfFrameInfo &Frame) {
689       RecordProcEnd(Frame);
690     }
691   };
692 } // end anonymous namespace
693
694 /// addAsmGlobalSymbols - Add global symbols from module-level ASM to the
695 /// defined or undefined lists.
696 bool LTOModule::addAsmGlobalSymbols(std::string &errMsg) {
697   const std::string &inlineAsm = _module->getModuleInlineAsm();
698   if (inlineAsm.empty())
699     return false;
700
701   OwningPtr<RecordStreamer> Streamer(new RecordStreamer(_context));
702   MemoryBuffer *Buffer = MemoryBuffer::getMemBuffer(inlineAsm);
703   SourceMgr SrcMgr;
704   SrcMgr.AddNewSourceBuffer(Buffer, SMLoc());
705   OwningPtr<MCAsmParser> Parser(createMCAsmParser(SrcMgr,
706                                                   _context, *Streamer,
707                                                   *_target->getMCAsmInfo()));
708   const Target &T = _target->getTarget();
709   OwningPtr<MCInstrInfo> MCII(T.createMCInstrInfo());
710   OwningPtr<MCSubtargetInfo>
711     STI(T.createMCSubtargetInfo(_target->getTargetTriple(),
712                                 _target->getTargetCPU(),
713                                 _target->getTargetFeatureString()));
714   OwningPtr<MCTargetAsmParser> TAP(T.createMCAsmParser(*STI, *Parser.get(), *MCII));
715   if (!TAP) {
716     errMsg = "target " + std::string(T.getName()) +
717       " does not define AsmParser.";
718     return true;
719   }
720
721   Parser->setTargetParser(*TAP);
722   if (Parser->Run(false))
723     return true;
724
725   for (RecordStreamer::const_iterator i = Streamer->begin(),
726          e = Streamer->end(); i != e; ++i) {
727     StringRef Key = i->first();
728     RecordStreamer::State Value = i->second;
729     if (Value == RecordStreamer::DefinedGlobal)
730       addAsmGlobalSymbol(Key.data(), LTO_SYMBOL_SCOPE_DEFAULT);
731     else if (Value == RecordStreamer::Defined)
732       addAsmGlobalSymbol(Key.data(), LTO_SYMBOL_SCOPE_INTERNAL);
733     else if (Value == RecordStreamer::Global ||
734              Value == RecordStreamer::Used)
735       addAsmGlobalSymbolUndef(Key.data());
736   }
737
738   return false;
739 }
740
741 /// isDeclaration - Return 'true' if the global value is a declaration.
742 static bool isDeclaration(const GlobalValue &V) {
743   if (V.hasAvailableExternallyLinkage())
744     return true;
745
746   if (V.isMaterializable())
747     return false;
748
749   return V.isDeclaration();
750 }
751
752 /// parseSymbols - Parse the symbols from the module and model-level ASM and add
753 /// them to either the defined or undefined lists.
754 bool LTOModule::parseSymbols(std::string &errMsg) {
755   // add functions
756   for (Module::iterator f = _module->begin(), e = _module->end(); f != e; ++f) {
757     if (isDeclaration(*f))
758       addPotentialUndefinedSymbol(f, true);
759     else
760       addDefinedFunctionSymbol(f);
761   }
762
763   // add data
764   for (Module::global_iterator v = _module->global_begin(),
765          e = _module->global_end(); v !=  e; ++v) {
766     if (isDeclaration(*v))
767       addPotentialUndefinedSymbol(v, false);
768     else
769       addDefinedDataSymbol(v);
770   }
771
772   // add asm globals
773   if (addAsmGlobalSymbols(errMsg))
774     return true;
775
776   // add aliases
777   for (Module::alias_iterator a = _module->alias_begin(),
778          e = _module->alias_end(); a != e; ++a) {
779     if (isDeclaration(*a->getAliasedGlobal()))
780       // Is an alias to a declaration.
781       addPotentialUndefinedSymbol(a, false);
782     else
783       addDefinedDataSymbol(a);
784   }
785
786   // make symbols for all undefines
787   for (StringMap<NameAndAttributes>::iterator u =_undefines.begin(),
788          e = _undefines.end(); u != e; ++u) {
789     // If this symbol also has a definition, then don't make an undefine because
790     // it is a tentative definition.
791     if (_defines.count(u->getKey())) continue;
792     NameAndAttributes info = u->getValue();
793     _symbols.push_back(info);
794   }
795
796   return false;
797 }