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