LLVM API Documentation

 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Groups Pages
LTOModule.cpp
Go to the documentation of this file.
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"
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"
26 #include "llvm/MC/MCStreamer.h"
28 #include "llvm/MC/MCSymbol.h"
32 #include "llvm/Support/Host.h"
35 #include "llvm/Support/Path.h"
36 #include "llvm/Support/SourceMgr.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(), NULL),
47  _mangler(t) {}
48 
49 /// isBitcodeFile - Returns 'true' if the file (or memory contents) is LLVM
50 /// bitcode.
51 bool LTOModule::isBitcodeFile(const void *mem, size_t length) {
52  return sys::fs::identify_magic(StringRef((const char *)mem, length)) ==
53  sys::fs::file_magic::bitcode;
54 }
55 
56 bool LTOModule::isBitcodeFile(const char *path) {
58  if (sys::fs::identify_magic(path, type))
59  return false;
60  return type == sys::fs::file_magic::bitcode;
61 }
62 
63 /// isBitcodeFileForTarget - Returns 'true' if the file (or memory contents) is
64 /// LLVM bitcode for the specified triple.
65 bool LTOModule::isBitcodeFileForTarget(const void *mem, size_t length,
66  const char *triplePrefix) {
67  MemoryBuffer *buffer = makeBuffer(mem, length);
68  if (!buffer)
69  return false;
70  return isTargetMatch(buffer, triplePrefix);
71 }
72 
73 bool LTOModule::isBitcodeFileForTarget(const char *path,
74  const char *triplePrefix) {
76  if (MemoryBuffer::getFile(path, buffer))
77  return false;
78  return isTargetMatch(buffer.take(), triplePrefix);
79 }
80 
81 /// isTargetMatch - Returns 'true' if the memory buffer is for the specified
82 /// target triple.
83 bool LTOModule::isTargetMatch(MemoryBuffer *buffer, const char *triplePrefix) {
84  std::string Triple = getBitcodeTargetTriple(buffer, getGlobalContext());
85  delete buffer;
86  return strncmp(Triple.c_str(), triplePrefix, strlen(triplePrefix)) == 0;
87 }
88 
89 /// makeLTOModule - Create an LTOModule. N.B. These methods take ownership of
90 /// the buffer.
92  std::string &errMsg) {
94  if (error_code ec = MemoryBuffer::getFile(path, buffer)) {
95  errMsg = ec.message();
96  return NULL;
97  }
98  return makeLTOModule(buffer.take(), options, errMsg);
99 }
100 
101 LTOModule *LTOModule::makeLTOModule(int fd, const char *path,
102  size_t size, TargetOptions options,
103  std::string &errMsg) {
104  return makeLTOModule(fd, path, size, 0, options, errMsg);
105 }
106 
107 LTOModule *LTOModule::makeLTOModule(int fd, const char *path,
108  size_t map_size,
109  off_t offset,
110  TargetOptions options,
111  std::string &errMsg) {
113  if (error_code ec =
114  MemoryBuffer::getOpenFileSlice(fd, path, buffer, map_size, offset)) {
115  errMsg = ec.message();
116  return NULL;
117  }
118  return makeLTOModule(buffer.take(), options, errMsg);
119 }
120 
121 LTOModule *LTOModule::makeLTOModule(const void *mem, size_t length,
122  TargetOptions options,
123  std::string &errMsg) {
124  OwningPtr<MemoryBuffer> buffer(makeBuffer(mem, length));
125  if (!buffer)
126  return NULL;
127  return makeLTOModule(buffer.take(), options, errMsg);
128 }
129 
131  TargetOptions options,
132  std::string &errMsg) {
133  // parse bitcode buffer
135  &errMsg));
136  if (!m) {
137  delete buffer;
138  return NULL;
139  }
140 
141  std::string TripleStr = m->getTargetTriple();
142  if (TripleStr.empty())
143  TripleStr = sys::getDefaultTargetTriple();
144  llvm::Triple Triple(TripleStr);
145 
146  // find machine architecture for this module
147  const Target *march = TargetRegistry::lookupTarget(TripleStr, errMsg);
148  if (!march)
149  return NULL;
150 
151  // construct LTOModule, hand over ownership of module and target
152  SubtargetFeatures Features;
153  Features.getDefaultSubtargetFeatures(Triple);
154  std::string FeatureStr = Features.getString();
155  // Set a default CPU for Darwin triples.
156  std::string CPU;
157  if (Triple.isOSDarwin()) {
158  if (Triple.getArch() == llvm::Triple::x86_64)
159  CPU = "core2";
160  else if (Triple.getArch() == llvm::Triple::x86)
161  CPU = "yonah";
162  }
163 
164  TargetMachine *target = march->createTargetMachine(TripleStr, CPU, FeatureStr,
165  options);
166  m->MaterializeAllPermanently();
167 
168  LTOModule *Ret = new LTOModule(m.take(), target);
169  if (Ret->parseSymbols(errMsg)) {
170  delete Ret;
171  return NULL;
172  }
173 
174  return Ret;
175 }
176 
177 /// makeBuffer - Create a MemoryBuffer from a memory range.
178 MemoryBuffer *LTOModule::makeBuffer(const void *mem, size_t length) {
179  const char *startPtr = (const char*)mem;
180  return MemoryBuffer::getMemBuffer(StringRef(startPtr, length), "", false);
181 }
182 
183 /// objcClassNameFromExpression - Get string that the data pointer points to.
184 bool
185 LTOModule::objcClassNameFromExpression(const Constant *c, std::string &name) {
186  if (const ConstantExpr *ce = dyn_cast<ConstantExpr>(c)) {
187  Constant *op = ce->getOperand(0);
188  if (GlobalVariable *gvn = dyn_cast<GlobalVariable>(op)) {
189  Constant *cn = gvn->getInitializer();
190  if (ConstantDataArray *ca = dyn_cast<ConstantDataArray>(cn)) {
191  if (ca->isCString()) {
192  name = ".objc_class_name_" + ca->getAsCString().str();
193  return true;
194  }
195  }
196  }
197  }
198  return false;
199 }
200 
201 /// addObjCClass - Parse i386/ppc ObjC class data structure.
202 void LTOModule::addObjCClass(const GlobalVariable *clgv) {
204  if (!c) return;
205 
206  // second slot in __OBJC,__class is pointer to superclass name
207  std::string superclassName;
208  if (objcClassNameFromExpression(c->getOperand(1), superclassName)) {
209  NameAndAttributes info;
211  _undefines.GetOrCreateValue(superclassName);
212  if (!entry.getValue().name) {
213  const char *symbolName = entry.getKey().data();
214  info.name = symbolName;
215  info.attributes = LTO_SYMBOL_DEFINITION_UNDEFINED;
216  info.isFunction = false;
217  info.symbol = clgv;
218  entry.setValue(info);
219  }
220  }
221 
222  // third slot in __OBJC,__class is pointer to class name
223  std::string className;
224  if (objcClassNameFromExpression(c->getOperand(2), className)) {
225  StringSet::value_type &entry = _defines.GetOrCreateValue(className);
226  entry.setValue(1);
227 
228  NameAndAttributes info;
229  info.name = entry.getKey().data();
230  info.attributes = LTO_SYMBOL_PERMISSIONS_DATA |
232  info.isFunction = false;
233  info.symbol = clgv;
234  _symbols.push_back(info);
235  }
236 }
237 
238 /// addObjCCategory - Parse i386/ppc ObjC category data structure.
239 void LTOModule::addObjCCategory(const GlobalVariable *clgv) {
241  if (!c) return;
242 
243  // second slot in __OBJC,__category is pointer to target class name
244  std::string targetclassName;
245  if (!objcClassNameFromExpression(c->getOperand(1), targetclassName))
246  return;
247 
248  NameAndAttributes info;
250  _undefines.GetOrCreateValue(targetclassName);
251 
252  if (entry.getValue().name)
253  return;
254 
255  const char *symbolName = entry.getKey().data();
256  info.name = symbolName;
257  info.attributes = LTO_SYMBOL_DEFINITION_UNDEFINED;
258  info.isFunction = false;
259  info.symbol = clgv;
260  entry.setValue(info);
261 }
262 
263 /// addObjCClassRef - Parse i386/ppc ObjC class list data structure.
264 void LTOModule::addObjCClassRef(const GlobalVariable *clgv) {
265  std::string targetclassName;
266  if (!objcClassNameFromExpression(clgv->getInitializer(), targetclassName))
267  return;
268 
269  NameAndAttributes info;
271  _undefines.GetOrCreateValue(targetclassName);
272  if (entry.getValue().name)
273  return;
274 
275  const char *symbolName = entry.getKey().data();
276  info.name = symbolName;
277  info.attributes = LTO_SYMBOL_DEFINITION_UNDEFINED;
278  info.isFunction = false;
279  info.symbol = clgv;
280  entry.setValue(info);
281 }
282 
283 /// addDefinedDataSymbol - Add a data symbol as defined to the list.
284 void LTOModule::addDefinedDataSymbol(const GlobalValue *v) {
285  // Add to list of defined symbols.
286  addDefinedSymbol(v, false);
287 
288  if (!v->hasSection() /* || !isTargetDarwin */)
289  return;
290 
291  // Special case i386/ppc ObjC data structures in magic sections:
292  // The issue is that the old ObjC object format did some strange
293  // contortions to avoid real linker symbols. For instance, the
294  // ObjC class data structure is allocated statically in the executable
295  // that defines that class. That data structures contains a pointer to
296  // its superclass. But instead of just initializing that part of the
297  // struct to the address of its superclass, and letting the static and
298  // dynamic linkers do the rest, the runtime works by having that field
299  // instead point to a C-string that is the name of the superclass.
300  // At runtime the objc initialization updates that pointer and sets
301  // it to point to the actual super class. As far as the linker
302  // knows it is just a pointer to a string. But then someone wanted the
303  // linker to issue errors at build time if the superclass was not found.
304  // So they figured out a way in mach-o object format to use an absolute
305  // symbols (.objc_class_name_Foo = 0) and a floating reference
306  // (.reference .objc_class_name_Bar) to cause the linker into erroring when
307  // a class was missing.
308  // The following synthesizes the implicit .objc_* symbols for the linker
309  // from the ObjC data structures generated by the front end.
310 
311  // special case if this data blob is an ObjC class definition
312  if (v->getSection().compare(0, 15, "__OBJC,__class,") == 0) {
313  if (const GlobalVariable *gv = dyn_cast<GlobalVariable>(v)) {
314  addObjCClass(gv);
315  }
316  }
317 
318  // special case if this data blob is an ObjC category definition
319  else if (v->getSection().compare(0, 18, "__OBJC,__category,") == 0) {
320  if (const GlobalVariable *gv = dyn_cast<GlobalVariable>(v)) {
321  addObjCCategory(gv);
322  }
323  }
324 
325  // special case if this data blob is the list of referenced classes
326  else if (v->getSection().compare(0, 18, "__OBJC,__cls_refs,") == 0) {
327  if (const GlobalVariable *gv = dyn_cast<GlobalVariable>(v)) {
328  addObjCClassRef(gv);
329  }
330  }
331 }
332 
333 /// addDefinedFunctionSymbol - Add a function symbol as defined to the list.
334 void LTOModule::addDefinedFunctionSymbol(const Function *f) {
335  // add to list of defined symbols
336  addDefinedSymbol(f, true);
337 }
338 
339 static bool canBeHidden(const GlobalValue *GV) {
341 
342  if (L != GlobalValue::LinkOnceODRLinkage)
343  return false;
344 
345  if (GV->hasUnnamedAddr())
346  return true;
347 
349  if (GlobalStatus::analyzeGlobal(GV, GS))
350  return false;
351 
352  return !GS.IsCompared;
353 }
354 
355 /// addDefinedSymbol - Add a defined symbol to the list.
356 void LTOModule::addDefinedSymbol(const GlobalValue *def, bool isFunction) {
357  // ignore all llvm.* symbols
358  if (def->getName().startswith("llvm."))
359  return;
360 
361  // string is owned by _defines
362  SmallString<64> Buffer;
363  _mangler.getNameWithPrefix(Buffer, def, false);
364 
365  // set alignment part log2() can have rounding errors
366  uint32_t align = def->getAlignment();
367  uint32_t attr = align ? countTrailingZeros(def->getAlignment()) : 0;
368 
369  // set permissions part
370  if (isFunction) {
372  } else {
373  const GlobalVariable *gv = dyn_cast<GlobalVariable>(def);
374  if (gv && gv->isConstant())
376  else
378  }
379 
380  // set definition part
381  if (def->hasWeakLinkage() || def->hasLinkOnceLinkage() ||
384  else if (def->hasCommonLinkage())
386  else
388 
389  // set scope part
390  if (def->hasHiddenVisibility())
391  attr |= LTO_SYMBOL_SCOPE_HIDDEN;
392  else if (def->hasProtectedVisibility())
394  else if (canBeHidden(def))
396  else if (def->hasExternalLinkage() || def->hasWeakLinkage() ||
397  def->hasLinkOnceLinkage() || def->hasCommonLinkage() ||
399  attr |= LTO_SYMBOL_SCOPE_DEFAULT;
400  else
402 
403  StringSet::value_type &entry = _defines.GetOrCreateValue(Buffer);
404  entry.setValue(1);
405 
406  // fill information structure
407  NameAndAttributes info;
408  StringRef Name = entry.getKey();
409  info.name = Name.data();
410  assert(info.name[Name.size()] == '\0');
411  info.attributes = attr;
412  info.isFunction = isFunction;
413  info.symbol = def;
414 
415  // add to table of symbols
416  _symbols.push_back(info);
417 }
418 
419 /// addAsmGlobalSymbol - Add a global symbol from module-level ASM to the
420 /// defined list.
421 void LTOModule::addAsmGlobalSymbol(const char *name,
422  lto_symbol_attributes scope) {
423  StringSet::value_type &entry = _defines.GetOrCreateValue(name);
424 
425  // only add new define if not already defined
426  if (entry.getValue())
427  return;
428 
429  entry.setValue(1);
430 
431  NameAndAttributes &info = _undefines[entry.getKey().data()];
432 
433  if (info.symbol == 0) {
434  // FIXME: This is trying to take care of module ASM like this:
435  //
436  // module asm ".zerofill __FOO, __foo, _bar_baz_qux, 0"
437  //
438  // but is gross and its mother dresses it funny. Have the ASM parser give us
439  // more details for this type of situation so that we're not guessing so
440  // much.
441 
442  // fill information structure
443  info.name = entry.getKey().data();
444  info.attributes =
446  info.isFunction = false;
447  info.symbol = 0;
448 
449  // add to table of symbols
450  _symbols.push_back(info);
451  return;
452  }
453 
454  if (info.isFunction)
455  addDefinedFunctionSymbol(cast<Function>(info.symbol));
456  else
457  addDefinedDataSymbol(info.symbol);
458 
459  _symbols.back().attributes &= ~LTO_SYMBOL_SCOPE_MASK;
460  _symbols.back().attributes |= scope;
461 }
462 
463 /// addAsmGlobalSymbolUndef - Add a global symbol from module-level ASM to the
464 /// undefined list.
465 void LTOModule::addAsmGlobalSymbolUndef(const char *name) {
467  _undefines.GetOrCreateValue(name);
468 
469  _asm_undefines.push_back(entry.getKey().data());
470 
471  // we already have the symbol
472  if (entry.getValue().name)
473  return;
474 
475  uint32_t attr = LTO_SYMBOL_DEFINITION_UNDEFINED;;
476  attr |= LTO_SYMBOL_SCOPE_DEFAULT;
477  NameAndAttributes info;
478  info.name = entry.getKey().data();
479  info.attributes = attr;
480  info.isFunction = false;
481  info.symbol = 0;
482 
483  entry.setValue(info);
484 }
485 
486 /// addPotentialUndefinedSymbol - Add a symbol which isn't defined just yet to a
487 /// list to be resolved later.
488 void
489 LTOModule::addPotentialUndefinedSymbol(const GlobalValue *decl, bool isFunc) {
490  // ignore all llvm.* symbols
491  if (decl->getName().startswith("llvm."))
492  return;
493 
494  // ignore all aliases
495  if (isa<GlobalAlias>(decl))
496  return;
497 
498  SmallString<64> name;
499  _mangler.getNameWithPrefix(name, decl, false);
500 
502  _undefines.GetOrCreateValue(name);
503 
504  // we already have the symbol
505  if (entry.getValue().name)
506  return;
507 
508  NameAndAttributes info;
509 
510  info.name = entry.getKey().data();
511 
512  if (decl->hasExternalWeakLinkage())
513  info.attributes = LTO_SYMBOL_DEFINITION_WEAKUNDEF;
514  else
515  info.attributes = LTO_SYMBOL_DEFINITION_UNDEFINED;
516 
517  info.isFunction = isFunc;
518  info.symbol = decl;
519 
520  entry.setValue(info);
521 }
522 
523 namespace {
524  class RecordStreamer : public MCStreamer {
525  public:
526  enum State { NeverSeen, Global, Defined, DefinedGlobal, Used };
527 
528  private:
529  StringMap<State> Symbols;
530 
531  void markDefined(const MCSymbol &Symbol) {
532  State &S = Symbols[Symbol.getName()];
533  switch (S) {
534  case DefinedGlobal:
535  case Global:
536  S = DefinedGlobal;
537  break;
538  case NeverSeen:
539  case Defined:
540  case Used:
541  S = Defined;
542  break;
543  }
544  }
545  void markGlobal(const MCSymbol &Symbol) {
546  State &S = Symbols[Symbol.getName()];
547  switch (S) {
548  case DefinedGlobal:
549  case Defined:
550  S = DefinedGlobal;
551  break;
552 
553  case NeverSeen:
554  case Global:
555  case Used:
556  S = Global;
557  break;
558  }
559  }
560  void markUsed(const MCSymbol &Symbol) {
561  State &S = Symbols[Symbol.getName()];
562  switch (S) {
563  case DefinedGlobal:
564  case Defined:
565  case Global:
566  break;
567 
568  case NeverSeen:
569  case Used:
570  S = Used;
571  break;
572  }
573  }
574 
575  // FIXME: mostly copied for the obj streamer.
576  void AddValueSymbols(const MCExpr *Value) {
577  switch (Value->getKind()) {
578  case MCExpr::Target:
579  // FIXME: What should we do in here?
580  break;
581 
582  case MCExpr::Constant:
583  break;
584 
585  case MCExpr::Binary: {
586  const MCBinaryExpr *BE = cast<MCBinaryExpr>(Value);
587  AddValueSymbols(BE->getLHS());
588  AddValueSymbols(BE->getRHS());
589  break;
590  }
591 
592  case MCExpr::SymbolRef:
593  markUsed(cast<MCSymbolRefExpr>(Value)->getSymbol());
594  break;
595 
596  case MCExpr::Unary:
597  AddValueSymbols(cast<MCUnaryExpr>(Value)->getSubExpr());
598  break;
599  }
600  }
601 
602  public:
603  typedef StringMap<State>::const_iterator const_iterator;
604 
605  const_iterator begin() {
606  return Symbols.begin();
607  }
608 
609  const_iterator end() {
610  return Symbols.end();
611  }
612 
613  RecordStreamer(MCContext &Context) : MCStreamer(Context, 0) {}
614 
615  virtual void EmitInstruction(const MCInst &Inst) {
616  // Scan for values.
617  for (unsigned i = Inst.getNumOperands(); i--; )
618  if (Inst.getOperand(i).isExpr())
619  AddValueSymbols(Inst.getOperand(i).getExpr());
620  }
621  virtual void EmitLabel(MCSymbol *Symbol) {
622  Symbol->setSection(*getCurrentSection().first);
623  markDefined(*Symbol);
624  }
625  virtual void EmitDebugLabel(MCSymbol *Symbol) {
626  EmitLabel(Symbol);
627  }
628  virtual void EmitAssignment(MCSymbol *Symbol, const MCExpr *Value) {
629  // FIXME: should we handle aliases?
630  markDefined(*Symbol);
631  }
632  virtual bool EmitSymbolAttribute(MCSymbol *Symbol, MCSymbolAttr Attribute) {
633  if (Attribute == MCSA_Global)
634  markGlobal(*Symbol);
635  return true;
636  }
637  virtual void EmitZerofill(const MCSection *Section, MCSymbol *Symbol,
638  uint64_t Size , unsigned ByteAlignment) {
639  markDefined(*Symbol);
640  }
641  virtual void EmitCommonSymbol(MCSymbol *Symbol, uint64_t Size,
642  unsigned ByteAlignment) {
643  markDefined(*Symbol);
644  }
645 
646  virtual void EmitBundleAlignMode(unsigned AlignPow2) {}
647  virtual void EmitBundleLock(bool AlignToEnd) {}
648  virtual void EmitBundleUnlock() {}
649 
650  // Noop calls.
651  virtual void ChangeSection(const MCSection *Section,
652  const MCExpr *Subsection) {}
653  virtual void InitToTextSection() {}
654  virtual void InitSections() {}
655  virtual void EmitAssemblerFlag(MCAssemblerFlag Flag) {}
656  virtual void EmitThumbFunc(MCSymbol *Func) {}
657  virtual void EmitSymbolDesc(MCSymbol *Symbol, unsigned DescValue) {}
658  virtual void EmitWeakReference(MCSymbol *Alias, const MCSymbol *Symbol) {}
659  virtual void BeginCOFFSymbolDef(const MCSymbol *Symbol) {}
660  virtual void EmitCOFFSymbolStorageClass(int StorageClass) {}
661  virtual void EmitCOFFSymbolType(int Type) {}
662  virtual void EndCOFFSymbolDef() {}
663  virtual void EmitELFSize(MCSymbol *Symbol, const MCExpr *Value) {}
664  virtual void EmitLocalCommonSymbol(MCSymbol *Symbol, uint64_t Size,
665  unsigned ByteAlignment) {}
666  virtual void EmitTBSSSymbol(const MCSection *Section, MCSymbol *Symbol,
667  uint64_t Size, unsigned ByteAlignment) {}
668  virtual void EmitBytes(StringRef Data) {}
669  virtual void EmitValueImpl(const MCExpr *Value, unsigned Size) {}
670  virtual void EmitULEB128Value(const MCExpr *Value) {}
671  virtual void EmitSLEB128Value(const MCExpr *Value) {}
672  virtual void EmitValueToAlignment(unsigned ByteAlignment, int64_t Value,
673  unsigned ValueSize,
674  unsigned MaxBytesToEmit) {}
675  virtual void EmitCodeAlignment(unsigned ByteAlignment,
676  unsigned MaxBytesToEmit) {}
677  virtual bool EmitValueToOffset(const MCExpr *Offset,
678  unsigned char Value ) { return false; }
679  virtual void EmitFileDirective(StringRef Filename) {}
680  virtual void EmitDwarfAdvanceLineAddr(int64_t LineDelta,
681  const MCSymbol *LastLabel,
682  const MCSymbol *Label,
683  unsigned PointerSize) {}
684  virtual void FinishImpl() {}
685  virtual void EmitCFIEndProcImpl(MCDwarfFrameInfo &Frame) {
686  RecordProcEnd(Frame);
687  }
688  };
689 } // end anonymous namespace
690 
691 /// addAsmGlobalSymbols - Add global symbols from module-level ASM to the
692 /// defined or undefined lists.
693 bool LTOModule::addAsmGlobalSymbols(std::string &errMsg) {
694  const std::string &inlineAsm = _module->getModuleInlineAsm();
695  if (inlineAsm.empty())
696  return false;
697 
698  OwningPtr<RecordStreamer> Streamer(new RecordStreamer(_context));
699  MemoryBuffer *Buffer = MemoryBuffer::getMemBuffer(inlineAsm);
701  SrcMgr.AddNewSourceBuffer(Buffer, SMLoc());
703  _context, *Streamer,
704  *_target->getMCAsmInfo()));
705  const Target &T = _target->getTarget();
708  STI(T.createMCSubtargetInfo(_target->getTargetTriple(),
709  _target->getTargetCPU(),
710  _target->getTargetFeatureString()));
711  OwningPtr<MCTargetAsmParser> TAP(T.createMCAsmParser(*STI, *Parser.get(), *MCII));
712  if (!TAP) {
713  errMsg = "target " + std::string(T.getName()) +
714  " does not define AsmParser.";
715  return true;
716  }
717 
718  Parser->setTargetParser(*TAP);
719  if (Parser->Run(false))
720  return true;
721 
722  for (RecordStreamer::const_iterator i = Streamer->begin(),
723  e = Streamer->end(); i != e; ++i) {
724  StringRef Key = i->first();
725  RecordStreamer::State Value = i->second;
726  if (Value == RecordStreamer::DefinedGlobal)
727  addAsmGlobalSymbol(Key.data(), LTO_SYMBOL_SCOPE_DEFAULT);
728  else if (Value == RecordStreamer::Defined)
729  addAsmGlobalSymbol(Key.data(), LTO_SYMBOL_SCOPE_INTERNAL);
730  else if (Value == RecordStreamer::Global ||
731  Value == RecordStreamer::Used)
732  addAsmGlobalSymbolUndef(Key.data());
733  }
734 
735  return false;
736 }
737 
738 /// isDeclaration - Return 'true' if the global value is a declaration.
739 static bool isDeclaration(const GlobalValue &V) {
741  return true;
742 
743  if (V.isMaterializable())
744  return false;
745 
746  return V.isDeclaration();
747 }
748 
749 /// parseSymbols - Parse the symbols from the module and model-level ASM and add
750 /// them to either the defined or undefined lists.
751 bool LTOModule::parseSymbols(std::string &errMsg) {
752  // add functions
753  for (Module::iterator f = _module->begin(), e = _module->end(); f != e; ++f) {
754  if (isDeclaration(*f))
755  addPotentialUndefinedSymbol(f, true);
756  else
757  addDefinedFunctionSymbol(f);
758  }
759 
760  // add data
761  for (Module::global_iterator v = _module->global_begin(),
762  e = _module->global_end(); v != e; ++v) {
763  if (isDeclaration(*v))
764  addPotentialUndefinedSymbol(v, false);
765  else
766  addDefinedDataSymbol(v);
767  }
768 
769  // add asm globals
770  if (addAsmGlobalSymbols(errMsg))
771  return true;
772 
773  // add aliases
774  for (Module::alias_iterator a = _module->alias_begin(),
775  e = _module->alias_end(); a != e; ++a) {
776  if (isDeclaration(*a->getAliasedGlobal()))
777  // Is an alias to a declaration.
778  addPotentialUndefinedSymbol(a, false);
779  else
780  addDefinedDataSymbol(a);
781  }
782 
783  // make symbols for all undefines
784  for (StringMap<NameAndAttributes>::iterator u =_undefines.begin(),
785  e = _undefines.end(); u != e; ++u) {
786  // If this symbol also has a definition, then don't make an undefine because
787  // it is a tentative definition.
788  if (_defines.count(u->getKey())) continue;
789  NameAndAttributes info = u->getValue();
790  _symbols.push_back(info);
791  }
792 
793  return false;
794 }
virtual void EmitULEB128Value(const MCExpr *Value)=0
const_iterator end(StringRef path)
Get end iterator over path.
Definition: Path.cpp:181
LinkageTypes getLinkage() const
Definition: GlobalValue.h:218
virtual void EmitDwarfAdvanceLineAddr(int64_t LineDelta, const MCSymbol *LastLabel, const MCSymbol *Label, unsigned PointerSize)=0
size_t size() const
size - Get the string size.
Definition: StringRef.h:113
const char * getName() const
getName - Get the target name.
void getDefaultSubtargetFeatures(const Triple &Triple)
Adds the default features for the specified target triple.
Module * getLazyBitcodeModule(MemoryBuffer *Buffer, LLVMContext &Context, std::string *ErrMsg=0)
The main container class for the LLVM Intermediate Representation.
Definition: Module.h:112
unsigned getAlignment() const
Definition: GlobalValue.h:79
void setValue(const ValueTy &V)
Definition: StringMap.h:135
virtual void InitSections()=0
InitSections - Create the default sections and set the initial one.
enable_if_c<!is_simple_type< Y >::value, typename cast_retty< X, const Y >::ret_type >::type dyn_cast(const Y &Val)
Definition: Casting.h:266
SourceMgr SrcMgr
void getNameWithPrefix(SmallVectorImpl< char > &OutName, const GlobalValue *GV, bool isImplicitlyPrivate, bool UseGlobalPrefix=true)
Definition: Mangler.cpp:90
std::string getDefaultTargetTriple()
virtual void EmitValueImpl(const MCExpr *Value, unsigned Size)=0
virtual void EmitFileDirective(StringRef Filename)=0
const StringRef getTargetFeatureString() const
const StringRef getTargetCPU() const
ExprKind getKind() const
Definition: MCExpr.h:61
virtual void EmitZerofill(const MCSection *Section, MCSymbol *Symbol=0, uint64_t Size=0, unsigned ByteAlignment=0)=0
static bool isBitcodeFileForTarget(const void *mem, size_t length, const char *triplePrefix)
Definition: LTOModule.cpp:65
bool hasAvailableExternallyLinkage() const
Definition: GlobalValue.h:195
virtual void EmitInstruction(const MCInst &Inst)=0
const_iterator begin(StringRef path)
Get begin iterator over path.
Definition: Path.cpp:173
virtual void EmitBundleAlignMode(unsigned AlignPow2)=0
Set the bundle alignment mode from now on in the section. The argument is the power of 2 to which the...
virtual void EmitThumbFunc(MCSymbol *Func)=0
const Constant * getInitializer() const
COFF::SymbolStorageClass StorageClass
Definition: COFFYAML.cpp:204
virtual void EmitAssignment(MCSymbol *Symbol, const MCExpr *Value)=0
StringRef getName() const
Definition: Value.cpp:167
MCInstrInfo * createMCInstrInfo() const
lazy value info
bool hasCommonLinkage() const
Definition: GlobalValue.h:215
bool hasSection() const
Definition: GlobalValue.h:95
const MCAsmInfo * getMCAsmInfo() const
static bool isDeclaration(const GlobalValue &V)
isDeclaration - Return 'true' if the global value is a declaration.
Definition: LTOModule.cpp:739
bool hasLinkerPrivateWeakLinkage() const
Definition: GlobalValue.h:208
MCSectionSubPair getCurrentSection() const
Definition: MCStreamer.h:224
virtual void EmitBytes(StringRef Data)=0
size_type count(StringRef Key) const
Definition: StringMap.h:316
std::string getBitcodeTargetTriple(MemoryBuffer *Buffer, LLVMContext &Context, std::string *ErrMsg=0)
global_iterator global_begin()
Definition: Module.h:521
const char * data() const
Definition: StringRef.h:107
virtual void EmitCFIEndProcImpl(MCDwarfFrameInfo &CurFrame)
Definition: MCStreamer.cpp:271
enable_if_c< std::numeric_limits< T >::is_integer &&!std::numeric_limits< T >::is_signed, std::size_t >::type countTrailingZeros(T Val, ZeroBehavior ZB=ZB_Width)
Count number of 0's from the least significant bit to the most stopping at the first 1...
Definition: MathExtras.h:49
bool isMaterializable() const
Definition: Globals.cpp:30
virtual void BeginCOFFSymbolDef(const MCSymbol *Symbol)=0
static bool isBitcodeFile(const void *mem, size_t length)
Definition: LTOModule.cpp:51
const MCExpr * getExpr() const
Definition: MCInst.h:93
static bool canBeHidden(const GlobalValue *GV)
Definition: LTOModule.cpp:339
const MCExpr * getLHS() const
getLHS - Get the left-hand side expression of the binary operator.
Definition: MCExpr.h:477
virtual void EmitAssemblerFlag(MCAssemblerFlag Flag)=0
EmitAssemblerFlag - Note in the output the specified Flag.
alias_iterator alias_end()
Definition: Module.h:544
virtual void EmitLocalCommonSymbol(MCSymbol *Symbol, uint64_t Size, unsigned ByteAlignment)=0
virtual void EmitSLEB128Value(const MCExpr *Value)=0
LLVM Constant Representation.
Definition: Constant.h:41
bool hasHiddenVisibility() const
Definition: GlobalValue.h:89
virtual void EmitELFSize(MCSymbol *Symbol, const MCExpr *Value)=0
bool isExpr() const
Definition: MCInst.h:59
virtual bool EmitSymbolAttribute(MCSymbol *Symbol, MCSymbolAttr Attribute)=0
EmitSymbolAttribute - Add the given Attribute to Symbol.
MCAsmParser * createMCAsmParser(SourceMgr &, MCContext &, MCStreamer &, const MCAsmInfo &)
Create an MCAsmParser instance.
Definition: AsmParser.cpp:4312
Value * getOperand(unsigned i) const
Definition: User.h:88
const std::string & getSection() const
Definition: GlobalValue.h:96
virtual void EmitBundleLock(bool AlignToEnd)=0
The following instructions are a bundle-locked group.
bool hasWeakLinkage() const
Definition: GlobalValue.h:201
MCBinaryExpr - Binary assembler expressions.
Definition: MCExpr.h:356
std::string getString() const
Features string accessors.
virtual void EmitValueToAlignment(unsigned ByteAlignment, int64_t Value=0, unsigned ValueSize=1, unsigned MaxBytesToEmit=0)=0
MCSubtargetInfo * createMCSubtargetInfo(StringRef Triple, StringRef CPU, StringRef Features) const
virtual void FinishImpl()=0
FinishImpl - Streamer specific finalization.
const std::string & getModuleInlineAsm() const
Definition: Module.h:253
file_magic identify_magic(StringRef magic)
Identify the type of a binary file based on how magical it is.
Definition: Path.cpp:846
global_iterator global_end()
Definition: Module.h:523
TargetMachine * createTargetMachine(StringRef Triple, StringRef CPU, StringRef Features, const TargetOptions &Options, Reloc::Model RM=Reloc::Default, CodeModel::Model CM=CodeModel::Default, CodeGenOpt::Level OL=CodeGenOpt::Default) const
bool hasExternalWeakLinkage() const
Definition: GlobalValue.h:214
bool hasExternalLinkage() const
Definition: GlobalValue.h:194
virtual void EmitCOFFSymbolType(int Type)=0
bool startswith(StringRef Prefix) const
Check if this string starts with the given Prefix.
Definition: StringRef.h:208
virtual void EmitLabel(MCSymbol *Symbol)
Definition: MCStreamer.cpp:212
MCTargetAsmParser * createMCAsmParser(MCSubtargetInfo &STI, MCAsmParser &Parser, const MCInstrInfo &MII) const
virtual void EmitDebugLabel(MCSymbol *Symbol)
Definition: MCStreamer.cpp:219
StringMapEntry< uint8_t > value_type
Definition: StringMap.h:272
virtual void EmitTBSSSymbol(const MCSection *Section, MCSymbol *Symbol, uint64_t Size, unsigned ByteAlignment=0)=0
alias_iterator alias_begin()
Definition: Module.h:542
MCSymbolAttr
Definition: MCDirectives.h:19
size_t strlen(const char *s);
LinkageTypes
An enumeration for the kinds of linkage for global values.
Definition: GlobalValue.h:33
virtual void EmitSymbolDesc(MCSymbol *Symbol, unsigned DescValue)=0
bool isConstant() const
virtual bool EmitValueToOffset(const MCExpr *Offset, unsigned char Value=0)=0
virtual void EmitBundleUnlock()=0
Ends a bundle-locked group.
const StringRef getTargetTriple() const
virtual void EndCOFFSymbolDef()=0
EndCOFFSymbolDef - Marks the end of the symbol definition.
const MCExpr * getRHS() const
getRHS - Get the right-hand side expression of the binary operator.
Definition: MCExpr.h:480
MapEntryTy & GetOrCreateValue(StringRef Key, InitTy Val)
Definition: StringMap.h:361
bool hasLinkOnceLinkage() const
Definition: GlobalValue.h:198
StringRef getName() const
getName - Get the symbol name.
Definition: MCSymbol.h:70
iterator end()
Definition: Module.h:533
iterator begin()
Definition: StringMap.h:278
bool IsCompared
True if the global's address is used in a comparison.
Definition: GlobalStatus.h:30
.type _foo,
Definition: MCDirectives.h:30
bool isDeclaration() const
Definition: Globals.cpp:66
MCAssemblerFlag
Definition: MCDirectives.h:47
lto_symbol_attributes
Definition: lto.h:45
void RecordProcEnd(MCDwarfFrameInfo &Frame)
Definition: MCStreamer.cpp:274
virtual void EmitWeakReference(MCSymbol *Alias, const MCSymbol *Symbol)=0
unsigned getNumOperands() const
Definition: MCInst.h:165
iterator begin()
Definition: Module.h:531
void setSection(const MCSection &S)
setSection - Mark the symbol as defined in the section S.
Definition: MCSymbol.h:117
bool hasProtectedVisibility() const
Definition: GlobalValue.h:90
static LTOModule * makeLTOModule(const char *path, llvm::TargetOptions options, std::string &errMsg)
Definition: LTOModule.cpp:91
virtual void EmitCommonSymbol(MCSymbol *Symbol, uint64_t Size, unsigned ByteAlignment)=0
LLVM Value Representation.
Definition: Value.h:66
bool hasUnnamedAddr() const
Definition: GlobalValue.h:84
virtual void ChangeSection(const MCSection *, const MCExpr *)=0
virtual void EmitCodeAlignment(unsigned ByteAlignment, unsigned MaxBytesToEmit=0)=0
const Target & getTarget() const
int strncmp(const char *s1, const char *s2, size_t n);
Represents a location in source code.
Definition: SMLoc.h:23
virtual void EmitCOFFSymbolStorageClass(int StorageClass)=0
size_t AddNewSourceBuffer(MemoryBuffer *F, SMLoc IncludeLoc)
Definition: SourceMgr.h:112
virtual void InitToTextSection()=0
InitToTextSection - Create a text section and switch the streamer to it.
iterator end()
Definition: StringMap.h:281
LLVMContext & getGlobalContext()
Definition: LLVMContext.cpp:27
const MCOperand & getOperand(unsigned i) const
Definition: MCInst.h:163