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