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