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