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