LLVM  3.7.0
BitcodeWriter.cpp
Go to the documentation of this file.
1 //===--- Bitcode/Writer/BitcodeWriter.cpp - Bitcode Writer ----------------===//
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 // Bitcode writer implementation.
11 //
12 //===----------------------------------------------------------------------===//
13 
15 #include "ValueEnumerator.h"
16 #include "llvm/ADT/Triple.h"
19 #include "llvm/IR/Constants.h"
21 #include "llvm/IR/DerivedTypes.h"
22 #include "llvm/IR/InlineAsm.h"
23 #include "llvm/IR/Instructions.h"
24 #include "llvm/IR/Module.h"
25 #include "llvm/IR/Operator.h"
26 #include "llvm/IR/UseListOrder.h"
31 #include "llvm/Support/Program.h"
33 #include <cctype>
34 #include <map>
35 using namespace llvm;
36 
37 /// These are manifest constants used by the bitcode writer. They do not need to
38 /// be kept in sync with the reader, but need to be consistent within this file.
39 enum {
40  // VALUE_SYMTAB_BLOCK abbrev id's.
45 
46  // CONSTANTS_BLOCK abbrev id's.
51 
52  // FUNCTION_BLOCK abbrev id's.
61 };
62 
63 static unsigned GetEncodedCastOpcode(unsigned Opcode) {
64  switch (Opcode) {
65  default: llvm_unreachable("Unknown cast instruction!");
66  case Instruction::Trunc : return bitc::CAST_TRUNC;
67  case Instruction::ZExt : return bitc::CAST_ZEXT;
68  case Instruction::SExt : return bitc::CAST_SEXT;
69  case Instruction::FPToUI : return bitc::CAST_FPTOUI;
70  case Instruction::FPToSI : return bitc::CAST_FPTOSI;
71  case Instruction::UIToFP : return bitc::CAST_UITOFP;
72  case Instruction::SIToFP : return bitc::CAST_SITOFP;
73  case Instruction::FPTrunc : return bitc::CAST_FPTRUNC;
74  case Instruction::FPExt : return bitc::CAST_FPEXT;
75  case Instruction::PtrToInt: return bitc::CAST_PTRTOINT;
76  case Instruction::IntToPtr: return bitc::CAST_INTTOPTR;
77  case Instruction::BitCast : return bitc::CAST_BITCAST;
78  case Instruction::AddrSpaceCast: return bitc::CAST_ADDRSPACECAST;
79  }
80 }
81 
82 static unsigned GetEncodedBinaryOpcode(unsigned Opcode) {
83  switch (Opcode) {
84  default: llvm_unreachable("Unknown binary instruction!");
85  case Instruction::Add:
86  case Instruction::FAdd: return bitc::BINOP_ADD;
87  case Instruction::Sub:
88  case Instruction::FSub: return bitc::BINOP_SUB;
89  case Instruction::Mul:
90  case Instruction::FMul: return bitc::BINOP_MUL;
91  case Instruction::UDiv: return bitc::BINOP_UDIV;
92  case Instruction::FDiv:
93  case Instruction::SDiv: return bitc::BINOP_SDIV;
94  case Instruction::URem: return bitc::BINOP_UREM;
95  case Instruction::FRem:
96  case Instruction::SRem: return bitc::BINOP_SREM;
97  case Instruction::Shl: return bitc::BINOP_SHL;
98  case Instruction::LShr: return bitc::BINOP_LSHR;
99  case Instruction::AShr: return bitc::BINOP_ASHR;
100  case Instruction::And: return bitc::BINOP_AND;
101  case Instruction::Or: return bitc::BINOP_OR;
102  case Instruction::Xor: return bitc::BINOP_XOR;
103  }
104 }
105 
107  switch (Op) {
108  default: llvm_unreachable("Unknown RMW operation!");
109  case AtomicRMWInst::Xchg: return bitc::RMW_XCHG;
110  case AtomicRMWInst::Add: return bitc::RMW_ADD;
111  case AtomicRMWInst::Sub: return bitc::RMW_SUB;
112  case AtomicRMWInst::And: return bitc::RMW_AND;
113  case AtomicRMWInst::Nand: return bitc::RMW_NAND;
114  case AtomicRMWInst::Or: return bitc::RMW_OR;
115  case AtomicRMWInst::Xor: return bitc::RMW_XOR;
116  case AtomicRMWInst::Max: return bitc::RMW_MAX;
117  case AtomicRMWInst::Min: return bitc::RMW_MIN;
118  case AtomicRMWInst::UMax: return bitc::RMW_UMAX;
119  case AtomicRMWInst::UMin: return bitc::RMW_UMIN;
120  }
121 }
122 
123 static unsigned GetEncodedOrdering(AtomicOrdering Ordering) {
124  switch (Ordering) {
125  case NotAtomic: return bitc::ORDERING_NOTATOMIC;
126  case Unordered: return bitc::ORDERING_UNORDERED;
127  case Monotonic: return bitc::ORDERING_MONOTONIC;
128  case Acquire: return bitc::ORDERING_ACQUIRE;
129  case Release: return bitc::ORDERING_RELEASE;
132  }
133  llvm_unreachable("Invalid ordering");
134 }
135 
136 static unsigned GetEncodedSynchScope(SynchronizationScope SynchScope) {
137  switch (SynchScope) {
140  }
141  llvm_unreachable("Invalid synch scope");
142 }
143 
144 static void WriteStringRecord(unsigned Code, StringRef Str,
145  unsigned AbbrevToUse, BitstreamWriter &Stream) {
147 
148  // Code: [strchar x N]
149  for (unsigned i = 0, e = Str.size(); i != e; ++i) {
150  if (AbbrevToUse && !BitCodeAbbrevOp::isChar6(Str[i]))
151  AbbrevToUse = 0;
152  Vals.push_back(Str[i]);
153  }
154 
155  // Emit the finished record.
156  Stream.EmitRecord(Code, Vals, AbbrevToUse);
157 }
158 
160  switch (Kind) {
167  case Attribute::Builtin:
169  case Attribute::ByVal:
170  return bitc::ATTR_KIND_BY_VAL;
173  case Attribute::InAlloca:
175  case Attribute::Cold:
176  return bitc::ATTR_KIND_COLD;
179  case Attribute::InReg:
180  return bitc::ATTR_KIND_IN_REG;
183  case Attribute::MinSize:
185  case Attribute::Naked:
186  return bitc::ATTR_KIND_NAKED;
187  case Attribute::Nest:
188  return bitc::ATTR_KIND_NEST;
189  case Attribute::NoAlias:
199  case Attribute::NoInline:
203  case Attribute::NonNull:
211  case Attribute::NoReturn:
213  case Attribute::NoUnwind:
219  case Attribute::ReadNone:
221  case Attribute::ReadOnly:
223  case Attribute::Returned:
227  case Attribute::SExt:
228  return bitc::ATTR_KIND_S_EXT;
247  case Attribute::UWTable:
249  case Attribute::ZExt:
250  return bitc::ATTR_KIND_Z_EXT;
252  llvm_unreachable("Can not encode end-attribute kinds marker.");
253  case Attribute::None:
254  llvm_unreachable("Can not encode none-attribute.");
255  }
256 
257  llvm_unreachable("Trying to encode unknown attribute");
258 }
259 
261  BitstreamWriter &Stream) {
262  const std::vector<AttributeSet> &AttrGrps = VE.getAttributeGroups();
263  if (AttrGrps.empty()) return;
264 
266 
268  for (unsigned i = 0, e = AttrGrps.size(); i != e; ++i) {
269  AttributeSet AS = AttrGrps[i];
270  for (unsigned i = 0, e = AS.getNumSlots(); i != e; ++i) {
272 
273  Record.push_back(VE.getAttributeGroupID(A));
274  Record.push_back(AS.getSlotIndex(i));
275 
276  for (AttributeSet::iterator I = AS.begin(0), E = AS.end(0);
277  I != E; ++I) {
278  Attribute Attr = *I;
279  if (Attr.isEnumAttribute()) {
280  Record.push_back(0);
282  } else if (Attr.isIntAttribute()) {
283  Record.push_back(1);
285  Record.push_back(Attr.getValueAsInt());
286  } else {
287  StringRef Kind = Attr.getKindAsString();
288  StringRef Val = Attr.getValueAsString();
289 
290  Record.push_back(Val.empty() ? 3 : 4);
291  Record.append(Kind.begin(), Kind.end());
292  Record.push_back(0);
293  if (!Val.empty()) {
294  Record.append(Val.begin(), Val.end());
295  Record.push_back(0);
296  }
297  }
298  }
299 
301  Record.clear();
302  }
303  }
304 
305  Stream.ExitBlock();
306 }
307 
308 static void WriteAttributeTable(const ValueEnumerator &VE,
309  BitstreamWriter &Stream) {
310  const std::vector<AttributeSet> &Attrs = VE.getAttributes();
311  if (Attrs.empty()) return;
312 
314 
316  for (unsigned i = 0, e = Attrs.size(); i != e; ++i) {
317  const AttributeSet &A = Attrs[i];
318  for (unsigned i = 0, e = A.getNumSlots(); i != e; ++i)
320 
321  Stream.EmitRecord(bitc::PARAMATTR_CODE_ENTRY, Record);
322  Record.clear();
323  }
324 
325  Stream.ExitBlock();
326 }
327 
328 /// WriteTypeTable - Write out the type table for a module.
329 static void WriteTypeTable(const ValueEnumerator &VE, BitstreamWriter &Stream) {
330  const ValueEnumerator::TypeList &TypeList = VE.getTypes();
331 
332  Stream.EnterSubblock(bitc::TYPE_BLOCK_ID_NEW, 4 /*count from # abbrevs */);
333  SmallVector<uint64_t, 64> TypeVals;
334 
335  uint64_t NumBits = VE.computeBitsRequiredForTypeIndicies();
336 
337  // Abbrev for TYPE_CODE_POINTER.
338  BitCodeAbbrev *Abbv = new BitCodeAbbrev();
340  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
341  Abbv->Add(BitCodeAbbrevOp(0)); // Addrspace = 0
342  unsigned PtrAbbrev = Stream.EmitAbbrev(Abbv);
343 
344  // Abbrev for TYPE_CODE_FUNCTION.
345  Abbv = new BitCodeAbbrev();
347  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // isvararg
349  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
350 
351  unsigned FunctionAbbrev = Stream.EmitAbbrev(Abbv);
352 
353  // Abbrev for TYPE_CODE_STRUCT_ANON.
354  Abbv = new BitCodeAbbrev();
356  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // ispacked
358  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
359 
360  unsigned StructAnonAbbrev = Stream.EmitAbbrev(Abbv);
361 
362  // Abbrev for TYPE_CODE_STRUCT_NAME.
363  Abbv = new BitCodeAbbrev();
367  unsigned StructNameAbbrev = Stream.EmitAbbrev(Abbv);
368 
369  // Abbrev for TYPE_CODE_STRUCT_NAMED.
370  Abbv = new BitCodeAbbrev();
372  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // ispacked
374  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
375 
376  unsigned StructNamedAbbrev = Stream.EmitAbbrev(Abbv);
377 
378  // Abbrev for TYPE_CODE_ARRAY.
379  Abbv = new BitCodeAbbrev();
381  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // size
382  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
383 
384  unsigned ArrayAbbrev = Stream.EmitAbbrev(Abbv);
385 
386  // Emit an entry count so the reader can reserve space.
387  TypeVals.push_back(TypeList.size());
388  Stream.EmitRecord(bitc::TYPE_CODE_NUMENTRY, TypeVals);
389  TypeVals.clear();
390 
391  // Loop over all of the types, emitting each in turn.
392  for (unsigned i = 0, e = TypeList.size(); i != e; ++i) {
393  Type *T = TypeList[i];
394  int AbbrevToUse = 0;
395  unsigned Code = 0;
396 
397  switch (T->getTypeID()) {
398  case Type::VoidTyID: Code = bitc::TYPE_CODE_VOID; break;
399  case Type::HalfTyID: Code = bitc::TYPE_CODE_HALF; break;
400  case Type::FloatTyID: Code = bitc::TYPE_CODE_FLOAT; break;
401  case Type::DoubleTyID: Code = bitc::TYPE_CODE_DOUBLE; break;
402  case Type::X86_FP80TyID: Code = bitc::TYPE_CODE_X86_FP80; break;
403  case Type::FP128TyID: Code = bitc::TYPE_CODE_FP128; break;
405  case Type::LabelTyID: Code = bitc::TYPE_CODE_LABEL; break;
406  case Type::MetadataTyID: Code = bitc::TYPE_CODE_METADATA; break;
407  case Type::X86_MMXTyID: Code = bitc::TYPE_CODE_X86_MMX; break;
408  case Type::IntegerTyID:
409  // INTEGER: [width]
411  TypeVals.push_back(cast<IntegerType>(T)->getBitWidth());
412  break;
413  case Type::PointerTyID: {
414  PointerType *PTy = cast<PointerType>(T);
415  // POINTER: [pointee type, address space]
417  TypeVals.push_back(VE.getTypeID(PTy->getElementType()));
418  unsigned AddressSpace = PTy->getAddressSpace();
419  TypeVals.push_back(AddressSpace);
420  if (AddressSpace == 0) AbbrevToUse = PtrAbbrev;
421  break;
422  }
423  case Type::FunctionTyID: {
424  FunctionType *FT = cast<FunctionType>(T);
425  // FUNCTION: [isvararg, retty, paramty x N]
427  TypeVals.push_back(FT->isVarArg());
428  TypeVals.push_back(VE.getTypeID(FT->getReturnType()));
429  for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i)
430  TypeVals.push_back(VE.getTypeID(FT->getParamType(i)));
431  AbbrevToUse = FunctionAbbrev;
432  break;
433  }
434  case Type::StructTyID: {
435  StructType *ST = cast<StructType>(T);
436  // STRUCT: [ispacked, eltty x N]
437  TypeVals.push_back(ST->isPacked());
438  // Output all of the element types.
440  E = ST->element_end(); I != E; ++I)
441  TypeVals.push_back(VE.getTypeID(*I));
442 
443  if (ST->isLiteral()) {
445  AbbrevToUse = StructAnonAbbrev;
446  } else {
447  if (ST->isOpaque()) {
448  Code = bitc::TYPE_CODE_OPAQUE;
449  } else {
451  AbbrevToUse = StructNamedAbbrev;
452  }
453 
454  // Emit the name if it is present.
455  if (!ST->getName().empty())
457  StructNameAbbrev, Stream);
458  }
459  break;
460  }
461  case Type::ArrayTyID: {
462  ArrayType *AT = cast<ArrayType>(T);
463  // ARRAY: [numelts, eltty]
464  Code = bitc::TYPE_CODE_ARRAY;
465  TypeVals.push_back(AT->getNumElements());
466  TypeVals.push_back(VE.getTypeID(AT->getElementType()));
467  AbbrevToUse = ArrayAbbrev;
468  break;
469  }
470  case Type::VectorTyID: {
471  VectorType *VT = cast<VectorType>(T);
472  // VECTOR [numelts, eltty]
473  Code = bitc::TYPE_CODE_VECTOR;
474  TypeVals.push_back(VT->getNumElements());
475  TypeVals.push_back(VE.getTypeID(VT->getElementType()));
476  break;
477  }
478  }
479 
480  // Emit the finished record.
481  Stream.EmitRecord(Code, TypeVals, AbbrevToUse);
482  TypeVals.clear();
483  }
484 
485  Stream.ExitBlock();
486 }
487 
488 static unsigned getEncodedLinkage(const GlobalValue &GV) {
489  switch (GV.getLinkage()) {
491  return 0;
493  return 16;
495  return 2;
497  return 3;
499  return 18;
501  return 7;
503  return 8;
505  return 9;
507  return 17;
509  return 19;
511  return 12;
512  }
513  llvm_unreachable("Invalid linkage");
514 }
515 
516 static unsigned getEncodedVisibility(const GlobalValue &GV) {
517  switch (GV.getVisibility()) {
518  case GlobalValue::DefaultVisibility: return 0;
519  case GlobalValue::HiddenVisibility: return 1;
520  case GlobalValue::ProtectedVisibility: return 2;
521  }
522  llvm_unreachable("Invalid visibility");
523 }
524 
525 static unsigned getEncodedDLLStorageClass(const GlobalValue &GV) {
526  switch (GV.getDLLStorageClass()) {
527  case GlobalValue::DefaultStorageClass: return 0;
528  case GlobalValue::DLLImportStorageClass: return 1;
529  case GlobalValue::DLLExportStorageClass: return 2;
530  }
531  llvm_unreachable("Invalid DLL storage class");
532 }
533 
534 static unsigned getEncodedThreadLocalMode(const GlobalValue &GV) {
535  switch (GV.getThreadLocalMode()) {
536  case GlobalVariable::NotThreadLocal: return 0;
540  case GlobalVariable::LocalExecTLSModel: return 4;
541  }
542  llvm_unreachable("Invalid TLS model");
543 }
544 
545 static unsigned getEncodedComdatSelectionKind(const Comdat &C) {
546  switch (C.getSelectionKind()) {
547  case Comdat::Any:
549  case Comdat::ExactMatch:
551  case Comdat::Largest:
555  case Comdat::SameSize:
557  }
558  llvm_unreachable("Invalid selection kind");
559 }
560 
561 static void writeComdats(const ValueEnumerator &VE, BitstreamWriter &Stream) {
563  for (const Comdat *C : VE.getComdats()) {
564  // COMDAT: [selection_kind, name]
566  size_t Size = C->getName().size();
567  assert(isUInt<16>(Size));
568  Vals.push_back(Size);
569  for (char Chr : C->getName())
570  Vals.push_back((unsigned char)Chr);
571  Stream.EmitRecord(bitc::MODULE_CODE_COMDAT, Vals, /*AbbrevToUse=*/0);
572  Vals.clear();
573  }
574 }
575 
576 // Emit top-level description of module, including target triple, inline asm,
577 // descriptors for global variables, and function prototype info.
578 static void WriteModuleInfo(const Module *M, const ValueEnumerator &VE,
579  BitstreamWriter &Stream) {
580  // Emit various pieces of data attached to a module.
581  if (!M->getTargetTriple().empty())
583  0/*TODO*/, Stream);
584  const std::string &DL = M->getDataLayoutStr();
585  if (!DL.empty())
586  WriteStringRecord(bitc::MODULE_CODE_DATALAYOUT, DL, 0 /*TODO*/, Stream);
587  if (!M->getModuleInlineAsm().empty())
589  0/*TODO*/, Stream);
590 
591  // Emit information about sections and GC, computing how many there are. Also
592  // compute the maximum alignment value.
593  std::map<std::string, unsigned> SectionMap;
594  std::map<std::string, unsigned> GCMap;
595  unsigned MaxAlignment = 0;
596  unsigned MaxGlobalType = 0;
597  for (const GlobalValue &GV : M->globals()) {
598  MaxAlignment = std::max(MaxAlignment, GV.getAlignment());
599  MaxGlobalType = std::max(MaxGlobalType, VE.getTypeID(GV.getValueType()));
600  if (GV.hasSection()) {
601  // Give section names unique ID's.
602  unsigned &Entry = SectionMap[GV.getSection()];
603  if (!Entry) {
605  0/*TODO*/, Stream);
606  Entry = SectionMap.size();
607  }
608  }
609  }
610  for (const Function &F : *M) {
611  MaxAlignment = std::max(MaxAlignment, F.getAlignment());
612  if (F.hasSection()) {
613  // Give section names unique ID's.
614  unsigned &Entry = SectionMap[F.getSection()];
615  if (!Entry) {
617  0/*TODO*/, Stream);
618  Entry = SectionMap.size();
619  }
620  }
621  if (F.hasGC()) {
622  // Same for GC names.
623  unsigned &Entry = GCMap[F.getGC()];
624  if (!Entry) {
626  0/*TODO*/, Stream);
627  Entry = GCMap.size();
628  }
629  }
630  }
631 
632  // Emit abbrev for globals, now that we know # sections and max alignment.
633  unsigned SimpleGVarAbbrev = 0;
634  if (!M->global_empty()) {
635  // Add an abbrev for common globals with no visibility or thread localness.
636  BitCodeAbbrev *Abbv = new BitCodeAbbrev();
639  Log2_32_Ceil(MaxGlobalType+1)));
640  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // AddrSpace << 2
641  //| explicitType << 1
642  //| constant
643  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Initializer.
644  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 5)); // Linkage.
645  if (MaxAlignment == 0) // Alignment.
646  Abbv->Add(BitCodeAbbrevOp(0));
647  else {
648  unsigned MaxEncAlignment = Log2_32(MaxAlignment)+1;
650  Log2_32_Ceil(MaxEncAlignment+1)));
651  }
652  if (SectionMap.empty()) // Section.
653  Abbv->Add(BitCodeAbbrevOp(0));
654  else
656  Log2_32_Ceil(SectionMap.size()+1)));
657  // Don't bother emitting vis + thread local.
658  SimpleGVarAbbrev = Stream.EmitAbbrev(Abbv);
659  }
660 
661  // Emit the global variable information.
663  for (const GlobalVariable &GV : M->globals()) {
664  unsigned AbbrevToUse = 0;
665 
666  // GLOBALVAR: [type, isconst, initid,
667  // linkage, alignment, section, visibility, threadlocal,
668  // unnamed_addr, externally_initialized, dllstorageclass,
669  // comdat]
670  Vals.push_back(VE.getTypeID(GV.getValueType()));
671  Vals.push_back(GV.getType()->getAddressSpace() << 2 | 2 | GV.isConstant());
672  Vals.push_back(GV.isDeclaration() ? 0 :
673  (VE.getValueID(GV.getInitializer()) + 1));
674  Vals.push_back(getEncodedLinkage(GV));
675  Vals.push_back(Log2_32(GV.getAlignment())+1);
676  Vals.push_back(GV.hasSection() ? SectionMap[GV.getSection()] : 0);
677  if (GV.isThreadLocal() ||
678  GV.getVisibility() != GlobalValue::DefaultVisibility ||
679  GV.hasUnnamedAddr() || GV.isExternallyInitialized() ||
680  GV.getDLLStorageClass() != GlobalValue::DefaultStorageClass ||
681  GV.hasComdat()) {
684  Vals.push_back(GV.hasUnnamedAddr());
685  Vals.push_back(GV.isExternallyInitialized());
687  Vals.push_back(GV.hasComdat() ? VE.getComdatID(GV.getComdat()) : 0);
688  } else {
689  AbbrevToUse = SimpleGVarAbbrev;
690  }
691 
692  Stream.EmitRecord(bitc::MODULE_CODE_GLOBALVAR, Vals, AbbrevToUse);
693  Vals.clear();
694  }
695 
696  // Emit the function proto information.
697  for (const Function &F : *M) {
698  // FUNCTION: [type, callingconv, isproto, linkage, paramattrs, alignment,
699  // section, visibility, gc, unnamed_addr, prologuedata,
700  // dllstorageclass, comdat, prefixdata, personalityfn]
701  Vals.push_back(VE.getTypeID(F.getFunctionType()));
702  Vals.push_back(F.getCallingConv());
703  Vals.push_back(F.isDeclaration());
705  Vals.push_back(VE.getAttributeID(F.getAttributes()));
706  Vals.push_back(Log2_32(F.getAlignment())+1);
707  Vals.push_back(F.hasSection() ? SectionMap[F.getSection()] : 0);
709  Vals.push_back(F.hasGC() ? GCMap[F.getGC()] : 0);
710  Vals.push_back(F.hasUnnamedAddr());
711  Vals.push_back(F.hasPrologueData() ? (VE.getValueID(F.getPrologueData()) + 1)
712  : 0);
714  Vals.push_back(F.hasComdat() ? VE.getComdatID(F.getComdat()) : 0);
715  Vals.push_back(F.hasPrefixData() ? (VE.getValueID(F.getPrefixData()) + 1)
716  : 0);
717  Vals.push_back(
718  F.hasPersonalityFn() ? (VE.getValueID(F.getPersonalityFn()) + 1) : 0);
719 
720  unsigned AbbrevToUse = 0;
721  Stream.EmitRecord(bitc::MODULE_CODE_FUNCTION, Vals, AbbrevToUse);
722  Vals.clear();
723  }
724 
725  // Emit the alias information.
726  for (const GlobalAlias &A : M->aliases()) {
727  // ALIAS: [alias type, aliasee val#, linkage, visibility]
728  Vals.push_back(VE.getTypeID(A.getType()));
729  Vals.push_back(VE.getValueID(A.getAliasee()));
734  Vals.push_back(A.hasUnnamedAddr());
735  unsigned AbbrevToUse = 0;
736  Stream.EmitRecord(bitc::MODULE_CODE_ALIAS, Vals, AbbrevToUse);
737  Vals.clear();
738  }
739 }
740 
741 static uint64_t GetOptimizationFlags(const Value *V) {
742  uint64_t Flags = 0;
743 
744  if (const auto *OBO = dyn_cast<OverflowingBinaryOperator>(V)) {
745  if (OBO->hasNoSignedWrap())
746  Flags |= 1 << bitc::OBO_NO_SIGNED_WRAP;
747  if (OBO->hasNoUnsignedWrap())
748  Flags |= 1 << bitc::OBO_NO_UNSIGNED_WRAP;
749  } else if (const auto *PEO = dyn_cast<PossiblyExactOperator>(V)) {
750  if (PEO->isExact())
751  Flags |= 1 << bitc::PEO_EXACT;
752  } else if (const auto *FPMO = dyn_cast<FPMathOperator>(V)) {
753  if (FPMO->hasUnsafeAlgebra())
755  if (FPMO->hasNoNaNs())
756  Flags |= FastMathFlags::NoNaNs;
757  if (FPMO->hasNoInfs())
758  Flags |= FastMathFlags::NoInfs;
759  if (FPMO->hasNoSignedZeros())
761  if (FPMO->hasAllowReciprocal())
763  }
764 
765  return Flags;
766 }
767 
768 static void WriteValueAsMetadata(const ValueAsMetadata *MD,
769  const ValueEnumerator &VE,
770  BitstreamWriter &Stream,
772  // Mimic an MDNode with a value as one operand.
773  Value *V = MD->getValue();
774  Record.push_back(VE.getTypeID(V->getType()));
775  Record.push_back(VE.getValueID(V));
776  Stream.EmitRecord(bitc::METADATA_VALUE, Record, 0);
777  Record.clear();
778 }
779 
780 static void WriteMDTuple(const MDTuple *N, const ValueEnumerator &VE,
781  BitstreamWriter &Stream,
782  SmallVectorImpl<uint64_t> &Record, unsigned Abbrev) {
783  for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
784  Metadata *MD = N->getOperand(i);
785  assert(!(MD && isa<LocalAsMetadata>(MD)) &&
786  "Unexpected function-local metadata");
787  Record.push_back(VE.getMetadataOrNullID(MD));
788  }
791  Record, Abbrev);
792  Record.clear();
793 }
794 
795 static void WriteDILocation(const DILocation *N, const ValueEnumerator &VE,
796  BitstreamWriter &Stream,
798  unsigned Abbrev) {
799  Record.push_back(N->isDistinct());
800  Record.push_back(N->getLine());
801  Record.push_back(N->getColumn());
802  Record.push_back(VE.getMetadataID(N->getScope()));
803  Record.push_back(VE.getMetadataOrNullID(N->getInlinedAt()));
804 
805  Stream.EmitRecord(bitc::METADATA_LOCATION, Record, Abbrev);
806  Record.clear();
807 }
808 
809 static void WriteGenericDINode(const GenericDINode *N,
810  const ValueEnumerator &VE,
811  BitstreamWriter &Stream,
813  unsigned Abbrev) {
814  Record.push_back(N->isDistinct());
815  Record.push_back(N->getTag());
816  Record.push_back(0); // Per-tag version field; unused for now.
817 
818  for (auto &I : N->operands())
819  Record.push_back(VE.getMetadataOrNullID(I));
820 
821  Stream.EmitRecord(bitc::METADATA_GENERIC_DEBUG, Record, Abbrev);
822  Record.clear();
823 }
824 
825 static uint64_t rotateSign(int64_t I) {
826  uint64_t U = I;
827  return I < 0 ? ~(U << 1) : U << 1;
828 }
829 
830 static void WriteDISubrange(const DISubrange *N, const ValueEnumerator &,
831  BitstreamWriter &Stream,
833  unsigned Abbrev) {
834  Record.push_back(N->isDistinct());
835  Record.push_back(N->getCount());
836  Record.push_back(rotateSign(N->getLowerBound()));
837 
838  Stream.EmitRecord(bitc::METADATA_SUBRANGE, Record, Abbrev);
839  Record.clear();
840 }
841 
842 static void WriteDIEnumerator(const DIEnumerator *N, const ValueEnumerator &VE,
843  BitstreamWriter &Stream,
845  unsigned Abbrev) {
846  Record.push_back(N->isDistinct());
847  Record.push_back(rotateSign(N->getValue()));
848  Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
849 
850  Stream.EmitRecord(bitc::METADATA_ENUMERATOR, Record, Abbrev);
851  Record.clear();
852 }
853 
854 static void WriteDIBasicType(const DIBasicType *N, const ValueEnumerator &VE,
855  BitstreamWriter &Stream,
857  unsigned Abbrev) {
858  Record.push_back(N->isDistinct());
859  Record.push_back(N->getTag());
860  Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
861  Record.push_back(N->getSizeInBits());
862  Record.push_back(N->getAlignInBits());
863  Record.push_back(N->getEncoding());
864 
865  Stream.EmitRecord(bitc::METADATA_BASIC_TYPE, Record, Abbrev);
866  Record.clear();
867 }
868 
869 static void WriteDIDerivedType(const DIDerivedType *N,
870  const ValueEnumerator &VE,
871  BitstreamWriter &Stream,
873  unsigned Abbrev) {
874  Record.push_back(N->isDistinct());
875  Record.push_back(N->getTag());
876  Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
877  Record.push_back(VE.getMetadataOrNullID(N->getFile()));
878  Record.push_back(N->getLine());
879  Record.push_back(VE.getMetadataOrNullID(N->getScope()));
880  Record.push_back(VE.getMetadataOrNullID(N->getBaseType()));
881  Record.push_back(N->getSizeInBits());
882  Record.push_back(N->getAlignInBits());
883  Record.push_back(N->getOffsetInBits());
884  Record.push_back(N->getFlags());
885  Record.push_back(VE.getMetadataOrNullID(N->getExtraData()));
886 
887  Stream.EmitRecord(bitc::METADATA_DERIVED_TYPE, Record, Abbrev);
888  Record.clear();
889 }
890 
892  const ValueEnumerator &VE,
893  BitstreamWriter &Stream,
895  unsigned Abbrev) {
896  Record.push_back(N->isDistinct());
897  Record.push_back(N->getTag());
898  Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
899  Record.push_back(VE.getMetadataOrNullID(N->getFile()));
900  Record.push_back(N->getLine());
901  Record.push_back(VE.getMetadataOrNullID(N->getScope()));
902  Record.push_back(VE.getMetadataOrNullID(N->getBaseType()));
903  Record.push_back(N->getSizeInBits());
904  Record.push_back(N->getAlignInBits());
905  Record.push_back(N->getOffsetInBits());
906  Record.push_back(N->getFlags());
907  Record.push_back(VE.getMetadataOrNullID(N->getElements().get()));
908  Record.push_back(N->getRuntimeLang());
910  Record.push_back(VE.getMetadataOrNullID(N->getTemplateParams().get()));
912 
913  Stream.EmitRecord(bitc::METADATA_COMPOSITE_TYPE, Record, Abbrev);
914  Record.clear();
915 }
916 
918  const ValueEnumerator &VE,
919  BitstreamWriter &Stream,
921  unsigned Abbrev) {
922  Record.push_back(N->isDistinct());
923  Record.push_back(N->getFlags());
924  Record.push_back(VE.getMetadataOrNullID(N->getTypeArray().get()));
925 
926  Stream.EmitRecord(bitc::METADATA_SUBROUTINE_TYPE, Record, Abbrev);
927  Record.clear();
928 }
929 
930 static void WriteDIFile(const DIFile *N, const ValueEnumerator &VE,
931  BitstreamWriter &Stream,
932  SmallVectorImpl<uint64_t> &Record, unsigned Abbrev) {
933  Record.push_back(N->isDistinct());
936 
937  Stream.EmitRecord(bitc::METADATA_FILE, Record, Abbrev);
938  Record.clear();
939 }
940 
941 static void WriteDICompileUnit(const DICompileUnit *N,
942  const ValueEnumerator &VE,
943  BitstreamWriter &Stream,
945  unsigned Abbrev) {
946  Record.push_back(N->isDistinct());
947  Record.push_back(N->getSourceLanguage());
948  Record.push_back(VE.getMetadataOrNullID(N->getFile()));
950  Record.push_back(N->isOptimized());
951  Record.push_back(VE.getMetadataOrNullID(N->getRawFlags()));
952  Record.push_back(N->getRuntimeVersion());
954  Record.push_back(N->getEmissionKind());
955  Record.push_back(VE.getMetadataOrNullID(N->getEnumTypes().get()));
956  Record.push_back(VE.getMetadataOrNullID(N->getRetainedTypes().get()));
957  Record.push_back(VE.getMetadataOrNullID(N->getSubprograms().get()));
958  Record.push_back(VE.getMetadataOrNullID(N->getGlobalVariables().get()));
959  Record.push_back(VE.getMetadataOrNullID(N->getImportedEntities().get()));
960  Record.push_back(N->getDWOId());
961 
962  Stream.EmitRecord(bitc::METADATA_COMPILE_UNIT, Record, Abbrev);
963  Record.clear();
964 }
965 
966 static void WriteDISubprogram(const DISubprogram *N, const ValueEnumerator &VE,
967  BitstreamWriter &Stream,
969  unsigned Abbrev) {
970  Record.push_back(N->isDistinct());
971  Record.push_back(VE.getMetadataOrNullID(N->getScope()));
972  Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
973  Record.push_back(VE.getMetadataOrNullID(N->getRawLinkageName()));
974  Record.push_back(VE.getMetadataOrNullID(N->getFile()));
975  Record.push_back(N->getLine());
976  Record.push_back(VE.getMetadataOrNullID(N->getType()));
977  Record.push_back(N->isLocalToUnit());
978  Record.push_back(N->isDefinition());
979  Record.push_back(N->getScopeLine());
980  Record.push_back(VE.getMetadataOrNullID(N->getContainingType()));
981  Record.push_back(N->getVirtuality());
982  Record.push_back(N->getVirtualIndex());
983  Record.push_back(N->getFlags());
984  Record.push_back(N->isOptimized());
985  Record.push_back(VE.getMetadataOrNullID(N->getRawFunction()));
986  Record.push_back(VE.getMetadataOrNullID(N->getTemplateParams().get()));
987  Record.push_back(VE.getMetadataOrNullID(N->getDeclaration()));
988  Record.push_back(VE.getMetadataOrNullID(N->getVariables().get()));
989 
990  Stream.EmitRecord(bitc::METADATA_SUBPROGRAM, Record, Abbrev);
991  Record.clear();
992 }
993 
995  const ValueEnumerator &VE,
996  BitstreamWriter &Stream,
998  unsigned Abbrev) {
999  Record.push_back(N->isDistinct());
1000  Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1001  Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1002  Record.push_back(N->getLine());
1003  Record.push_back(N->getColumn());
1004 
1005  Stream.EmitRecord(bitc::METADATA_LEXICAL_BLOCK, Record, Abbrev);
1006  Record.clear();
1007 }
1008 
1010  const ValueEnumerator &VE,
1011  BitstreamWriter &Stream,
1013  unsigned Abbrev) {
1014  Record.push_back(N->isDistinct());
1015  Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1016  Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1017  Record.push_back(N->getDiscriminator());
1018 
1019  Stream.EmitRecord(bitc::METADATA_LEXICAL_BLOCK_FILE, Record, Abbrev);
1020  Record.clear();
1021 }
1022 
1023 static void WriteDINamespace(const DINamespace *N, const ValueEnumerator &VE,
1024  BitstreamWriter &Stream,
1026  unsigned Abbrev) {
1027  Record.push_back(N->isDistinct());
1028  Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1029  Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1030  Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1031  Record.push_back(N->getLine());
1032 
1033  Stream.EmitRecord(bitc::METADATA_NAMESPACE, Record, Abbrev);
1034  Record.clear();
1035 }
1036 
1037 static void WriteDIModule(const DIModule *N, const ValueEnumerator &VE,
1038  BitstreamWriter &Stream,
1039  SmallVectorImpl<uint64_t> &Record, unsigned Abbrev) {
1040  Record.push_back(N->isDistinct());
1041  for (auto &I : N->operands())
1042  Record.push_back(VE.getMetadataOrNullID(I));
1043 
1044  Stream.EmitRecord(bitc::METADATA_MODULE, Record, Abbrev);
1045  Record.clear();
1046 }
1047 
1049  const ValueEnumerator &VE,
1050  BitstreamWriter &Stream,
1052  unsigned Abbrev) {
1053  Record.push_back(N->isDistinct());
1054  Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1055  Record.push_back(VE.getMetadataOrNullID(N->getType()));
1056 
1057  Stream.EmitRecord(bitc::METADATA_TEMPLATE_TYPE, Record, Abbrev);
1058  Record.clear();
1059 }
1060 
1062  const ValueEnumerator &VE,
1063  BitstreamWriter &Stream,
1065  unsigned Abbrev) {
1066  Record.push_back(N->isDistinct());
1067  Record.push_back(N->getTag());
1068  Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1069  Record.push_back(VE.getMetadataOrNullID(N->getType()));
1070  Record.push_back(VE.getMetadataOrNullID(N->getValue()));
1071 
1072  Stream.EmitRecord(bitc::METADATA_TEMPLATE_VALUE, Record, Abbrev);
1073  Record.clear();
1074 }
1075 
1077  const ValueEnumerator &VE,
1078  BitstreamWriter &Stream,
1080  unsigned Abbrev) {
1081  Record.push_back(N->isDistinct());
1082  Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1083  Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1085  Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1086  Record.push_back(N->getLine());
1087  Record.push_back(VE.getMetadataOrNullID(N->getType()));
1088  Record.push_back(N->isLocalToUnit());
1089  Record.push_back(N->isDefinition());
1090  Record.push_back(VE.getMetadataOrNullID(N->getRawVariable()));
1092 
1093  Stream.EmitRecord(bitc::METADATA_GLOBAL_VAR, Record, Abbrev);
1094  Record.clear();
1095 }
1096 
1098  const ValueEnumerator &VE,
1099  BitstreamWriter &Stream,
1101  unsigned Abbrev) {
1102  Record.push_back(N->isDistinct());
1103  Record.push_back(N->getTag());
1104  Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1105  Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1106  Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1107  Record.push_back(N->getLine());
1108  Record.push_back(VE.getMetadataOrNullID(N->getType()));
1109  Record.push_back(N->getArg());
1110  Record.push_back(N->getFlags());
1111 
1112  Stream.EmitRecord(bitc::METADATA_LOCAL_VAR, Record, Abbrev);
1113  Record.clear();
1114 }
1115 
1116 static void WriteDIExpression(const DIExpression *N, const ValueEnumerator &,
1117  BitstreamWriter &Stream,
1119  unsigned Abbrev) {
1120  Record.reserve(N->getElements().size() + 1);
1121 
1122  Record.push_back(N->isDistinct());
1123  Record.append(N->elements_begin(), N->elements_end());
1124 
1125  Stream.EmitRecord(bitc::METADATA_EXPRESSION, Record, Abbrev);
1126  Record.clear();
1127 }
1128 
1130  const ValueEnumerator &VE,
1131  BitstreamWriter &Stream,
1133  unsigned Abbrev) {
1134  Record.push_back(N->isDistinct());
1135  Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1136  Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1137  Record.push_back(N->getLine());
1140  Record.push_back(N->getAttributes());
1141  Record.push_back(VE.getMetadataOrNullID(N->getType()));
1142 
1143  Stream.EmitRecord(bitc::METADATA_OBJC_PROPERTY, Record, Abbrev);
1144  Record.clear();
1145 }
1146 
1148  const ValueEnumerator &VE,
1149  BitstreamWriter &Stream,
1151  unsigned Abbrev) {
1152  Record.push_back(N->isDistinct());
1153  Record.push_back(N->getTag());
1154  Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1155  Record.push_back(VE.getMetadataOrNullID(N->getEntity()));
1156  Record.push_back(N->getLine());
1157  Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1158 
1159  Stream.EmitRecord(bitc::METADATA_IMPORTED_ENTITY, Record, Abbrev);
1160  Record.clear();
1161 }
1162 
1163 static void WriteModuleMetadata(const Module *M,
1164  const ValueEnumerator &VE,
1165  BitstreamWriter &Stream) {
1166  const auto &MDs = VE.getMDs();
1167  if (MDs.empty() && M->named_metadata_empty())
1168  return;
1169 
1171 
1172  unsigned MDSAbbrev = 0;
1173  if (VE.hasMDString()) {
1174  // Abbrev for METADATA_STRING.
1175  BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1179  MDSAbbrev = Stream.EmitAbbrev(Abbv);
1180  }
1181 
1182  // Initialize MDNode abbreviations.
1183 #define HANDLE_MDNODE_LEAF(CLASS) unsigned CLASS##Abbrev = 0;
1184 #include "llvm/IR/Metadata.def"
1185 
1186  if (VE.hasDILocation()) {
1187  // Abbrev for METADATA_LOCATION.
1188  //
1189  // Assume the column is usually under 128, and always output the inlined-at
1190  // location (it's never more expensive than building an array size 1).
1191  BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1198  DILocationAbbrev = Stream.EmitAbbrev(Abbv);
1199  }
1200 
1201  if (VE.hasGenericDINode()) {
1202  // Abbrev for METADATA_GENERIC_DEBUG.
1203  //
1204  // Assume the column is usually under 128, and always output the inlined-at
1205  // location (it's never more expensive than building an array size 1).
1206  BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1214  GenericDINodeAbbrev = Stream.EmitAbbrev(Abbv);
1215  }
1216 
1217  unsigned NameAbbrev = 0;
1218  if (!M->named_metadata_empty()) {
1219  // Abbrev for METADATA_NAME.
1220  BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1224  NameAbbrev = Stream.EmitAbbrev(Abbv);
1225  }
1226 
1228  for (const Metadata *MD : MDs) {
1229  if (const MDNode *N = dyn_cast<MDNode>(MD)) {
1230  assert(N->isResolved() && "Expected forward references to be resolved");
1231 
1232  switch (N->getMetadataID()) {
1233  default:
1234  llvm_unreachable("Invalid MDNode subclass");
1235 #define HANDLE_MDNODE_LEAF(CLASS) \
1236  case Metadata::CLASS##Kind: \
1237  Write##CLASS(cast<CLASS>(N), VE, Stream, Record, CLASS##Abbrev); \
1238  continue;
1239 #include "llvm/IR/Metadata.def"
1240  }
1241  }
1242  if (const auto *MDC = dyn_cast<ConstantAsMetadata>(MD)) {
1243  WriteValueAsMetadata(MDC, VE, Stream, Record);
1244  continue;
1245  }
1246  const MDString *MDS = cast<MDString>(MD);
1247  // Code: [strchar x N]
1248  Record.append(MDS->bytes_begin(), MDS->bytes_end());
1249 
1250  // Emit the finished record.
1251  Stream.EmitRecord(bitc::METADATA_STRING, Record, MDSAbbrev);
1252  Record.clear();
1253  }
1254 
1255  // Write named metadata.
1256  for (const NamedMDNode &NMD : M->named_metadata()) {
1257  // Write name.
1258  StringRef Str = NMD.getName();
1259  Record.append(Str.bytes_begin(), Str.bytes_end());
1260  Stream.EmitRecord(bitc::METADATA_NAME, Record, NameAbbrev);
1261  Record.clear();
1262 
1263  // Write named metadata operands.
1264  for (const MDNode *N : NMD.operands())
1265  Record.push_back(VE.getMetadataID(N));
1266  Stream.EmitRecord(bitc::METADATA_NAMED_NODE, Record, 0);
1267  Record.clear();
1268  }
1269 
1270  Stream.ExitBlock();
1271 }
1272 
1274  const ValueEnumerator &VE,
1275  BitstreamWriter &Stream) {
1276  bool StartedMetadataBlock = false;
1279  VE.getFunctionLocalMDs();
1280  for (unsigned i = 0, e = MDs.size(); i != e; ++i) {
1281  assert(MDs[i] && "Expected valid function-local metadata");
1282  if (!StartedMetadataBlock) {
1284  StartedMetadataBlock = true;
1285  }
1286  WriteValueAsMetadata(MDs[i], VE, Stream, Record);
1287  }
1288 
1289  if (StartedMetadataBlock)
1290  Stream.ExitBlock();
1291 }
1292 
1294  const ValueEnumerator &VE,
1295  BitstreamWriter &Stream) {
1297 
1299 
1300  // Write metadata attachments
1301  // METADATA_ATTACHMENT - [m x [value, [n x [id, mdnode]]]
1303  F.getAllMetadata(MDs);
1304  if (!MDs.empty()) {
1305  for (const auto &I : MDs) {
1306  Record.push_back(I.first);
1307  Record.push_back(VE.getMetadataID(I.second));
1308  }
1309  Stream.EmitRecord(bitc::METADATA_ATTACHMENT, Record, 0);
1310  Record.clear();
1311  }
1312 
1313  for (Function::const_iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
1314  for (BasicBlock::const_iterator I = BB->begin(), E = BB->end();
1315  I != E; ++I) {
1316  MDs.clear();
1317  I->getAllMetadataOtherThanDebugLoc(MDs);
1318 
1319  // If no metadata, ignore instruction.
1320  if (MDs.empty()) continue;
1321 
1322  Record.push_back(VE.getInstructionID(I));
1323 
1324  for (unsigned i = 0, e = MDs.size(); i != e; ++i) {
1325  Record.push_back(MDs[i].first);
1326  Record.push_back(VE.getMetadataID(MDs[i].second));
1327  }
1328  Stream.EmitRecord(bitc::METADATA_ATTACHMENT, Record, 0);
1329  Record.clear();
1330  }
1331 
1332  Stream.ExitBlock();
1333 }
1334 
1335 static void WriteModuleMetadataStore(const Module *M, BitstreamWriter &Stream) {
1337 
1338  // Write metadata kinds
1339  // METADATA_KIND - [n x [id, name]]
1341  M->getMDKindNames(Names);
1342 
1343  if (Names.empty()) return;
1344 
1346 
1347  for (unsigned MDKindID = 0, e = Names.size(); MDKindID != e; ++MDKindID) {
1348  Record.push_back(MDKindID);
1349  StringRef KName = Names[MDKindID];
1350  Record.append(KName.begin(), KName.end());
1351 
1352  Stream.EmitRecord(bitc::METADATA_KIND, Record, 0);
1353  Record.clear();
1354  }
1355 
1356  Stream.ExitBlock();
1357 }
1358 
1359 static void emitSignedInt64(SmallVectorImpl<uint64_t> &Vals, uint64_t V) {
1360  if ((int64_t)V >= 0)
1361  Vals.push_back(V << 1);
1362  else
1363  Vals.push_back((-V << 1) | 1);
1364 }
1365 
1366 static void WriteConstants(unsigned FirstVal, unsigned LastVal,
1367  const ValueEnumerator &VE,
1368  BitstreamWriter &Stream, bool isGlobal) {
1369  if (FirstVal == LastVal) return;
1370 
1372 
1373  unsigned AggregateAbbrev = 0;
1374  unsigned String8Abbrev = 0;
1375  unsigned CString7Abbrev = 0;
1376  unsigned CString6Abbrev = 0;
1377  // If this is a constant pool for the module, emit module-specific abbrevs.
1378  if (isGlobal) {
1379  // Abbrev for CST_CODE_AGGREGATE.
1380  BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1384  AggregateAbbrev = Stream.EmitAbbrev(Abbv);
1385 
1386  // Abbrev for CST_CODE_STRING.
1387  Abbv = new BitCodeAbbrev();
1391  String8Abbrev = Stream.EmitAbbrev(Abbv);
1392  // Abbrev for CST_CODE_CSTRING.
1393  Abbv = new BitCodeAbbrev();
1397  CString7Abbrev = Stream.EmitAbbrev(Abbv);
1398  // Abbrev for CST_CODE_CSTRING.
1399  Abbv = new BitCodeAbbrev();
1403  CString6Abbrev = Stream.EmitAbbrev(Abbv);
1404  }
1405 
1407 
1408  const ValueEnumerator::ValueList &Vals = VE.getValues();
1409  Type *LastTy = nullptr;
1410  for (unsigned i = FirstVal; i != LastVal; ++i) {
1411  const Value *V = Vals[i].first;
1412  // If we need to switch types, do so now.
1413  if (V->getType() != LastTy) {
1414  LastTy = V->getType();
1415  Record.push_back(VE.getTypeID(LastTy));
1416  Stream.EmitRecord(bitc::CST_CODE_SETTYPE, Record,
1418  Record.clear();
1419  }
1420 
1421  if (const InlineAsm *IA = dyn_cast<InlineAsm>(V)) {
1422  Record.push_back(unsigned(IA->hasSideEffects()) |
1423  unsigned(IA->isAlignStack()) << 1 |
1424  unsigned(IA->getDialect()&1) << 2);
1425 
1426  // Add the asm string.
1427  const std::string &AsmStr = IA->getAsmString();
1428  Record.push_back(AsmStr.size());
1429  Record.append(AsmStr.begin(), AsmStr.end());
1430 
1431  // Add the constraint string.
1432  const std::string &ConstraintStr = IA->getConstraintString();
1433  Record.push_back(ConstraintStr.size());
1434  Record.append(ConstraintStr.begin(), ConstraintStr.end());
1435  Stream.EmitRecord(bitc::CST_CODE_INLINEASM, Record);
1436  Record.clear();
1437  continue;
1438  }
1439  const Constant *C = cast<Constant>(V);
1440  unsigned Code = -1U;
1441  unsigned AbbrevToUse = 0;
1442  if (C->isNullValue()) {
1443  Code = bitc::CST_CODE_NULL;
1444  } else if (isa<UndefValue>(C)) {
1445  Code = bitc::CST_CODE_UNDEF;
1446  } else if (const ConstantInt *IV = dyn_cast<ConstantInt>(C)) {
1447  if (IV->getBitWidth() <= 64) {
1448  uint64_t V = IV->getSExtValue();
1449  emitSignedInt64(Record, V);
1450  Code = bitc::CST_CODE_INTEGER;
1451  AbbrevToUse = CONSTANTS_INTEGER_ABBREV;
1452  } else { // Wide integers, > 64 bits in size.
1453  // We have an arbitrary precision integer value to write whose
1454  // bit width is > 64. However, in canonical unsigned integer
1455  // format it is likely that the high bits are going to be zero.
1456  // So, we only write the number of active words.
1457  unsigned NWords = IV->getValue().getActiveWords();
1458  const uint64_t *RawWords = IV->getValue().getRawData();
1459  for (unsigned i = 0; i != NWords; ++i) {
1460  emitSignedInt64(Record, RawWords[i]);
1461  }
1463  }
1464  } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
1465  Code = bitc::CST_CODE_FLOAT;
1466  Type *Ty = CFP->getType();
1467  if (Ty->isHalfTy() || Ty->isFloatTy() || Ty->isDoubleTy()) {
1468  Record.push_back(CFP->getValueAPF().bitcastToAPInt().getZExtValue());
1469  } else if (Ty->isX86_FP80Ty()) {
1470  // api needed to prevent premature destruction
1471  // bits are not in the same order as a normal i80 APInt, compensate.
1472  APInt api = CFP->getValueAPF().bitcastToAPInt();
1473  const uint64_t *p = api.getRawData();
1474  Record.push_back((p[1] << 48) | (p[0] >> 16));
1475  Record.push_back(p[0] & 0xffffLL);
1476  } else if (Ty->isFP128Ty() || Ty->isPPC_FP128Ty()) {
1477  APInt api = CFP->getValueAPF().bitcastToAPInt();
1478  const uint64_t *p = api.getRawData();
1479  Record.push_back(p[0]);
1480  Record.push_back(p[1]);
1481  } else {
1482  assert (0 && "Unknown FP type!");
1483  }
1484  } else if (isa<ConstantDataSequential>(C) &&
1485  cast<ConstantDataSequential>(C)->isString()) {
1486  const ConstantDataSequential *Str = cast<ConstantDataSequential>(C);
1487  // Emit constant strings specially.
1488  unsigned NumElts = Str->getNumElements();
1489  // If this is a null-terminated string, use the denser CSTRING encoding.
1490  if (Str->isCString()) {
1491  Code = bitc::CST_CODE_CSTRING;
1492  --NumElts; // Don't encode the null, which isn't allowed by char6.
1493  } else {
1494  Code = bitc::CST_CODE_STRING;
1495  AbbrevToUse = String8Abbrev;
1496  }
1497  bool isCStr7 = Code == bitc::CST_CODE_CSTRING;
1498  bool isCStrChar6 = Code == bitc::CST_CODE_CSTRING;
1499  for (unsigned i = 0; i != NumElts; ++i) {
1500  unsigned char V = Str->getElementAsInteger(i);
1501  Record.push_back(V);
1502  isCStr7 &= (V & 128) == 0;
1503  if (isCStrChar6)
1504  isCStrChar6 = BitCodeAbbrevOp::isChar6(V);
1505  }
1506 
1507  if (isCStrChar6)
1508  AbbrevToUse = CString6Abbrev;
1509  else if (isCStr7)
1510  AbbrevToUse = CString7Abbrev;
1511  } else if (const ConstantDataSequential *CDS =
1512  dyn_cast<ConstantDataSequential>(C)) {
1513  Code = bitc::CST_CODE_DATA;
1514  Type *EltTy = CDS->getType()->getElementType();
1515  if (isa<IntegerType>(EltTy)) {
1516  for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i)
1517  Record.push_back(CDS->getElementAsInteger(i));
1518  } else if (EltTy->isFloatTy()) {
1519  for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
1520  union { float F; uint32_t I; };
1521  F = CDS->getElementAsFloat(i);
1522  Record.push_back(I);
1523  }
1524  } else {
1525  assert(EltTy->isDoubleTy() && "Unknown ConstantData element type");
1526  for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
1527  union { double F; uint64_t I; };
1528  F = CDS->getElementAsDouble(i);
1529  Record.push_back(I);
1530  }
1531  }
1532  } else if (isa<ConstantArray>(C) || isa<ConstantStruct>(C) ||
1533  isa<ConstantVector>(C)) {
1534  Code = bitc::CST_CODE_AGGREGATE;
1535  for (const Value *Op : C->operands())
1536  Record.push_back(VE.getValueID(Op));
1537  AbbrevToUse = AggregateAbbrev;
1538  } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
1539  switch (CE->getOpcode()) {
1540  default:
1541  if (Instruction::isCast(CE->getOpcode())) {
1542  Code = bitc::CST_CODE_CE_CAST;
1543  Record.push_back(GetEncodedCastOpcode(CE->getOpcode()));
1544  Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
1545  Record.push_back(VE.getValueID(C->getOperand(0)));
1546  AbbrevToUse = CONSTANTS_CE_CAST_Abbrev;
1547  } else {
1548  assert(CE->getNumOperands() == 2 && "Unknown constant expr!");
1549  Code = bitc::CST_CODE_CE_BINOP;
1550  Record.push_back(GetEncodedBinaryOpcode(CE->getOpcode()));
1551  Record.push_back(VE.getValueID(C->getOperand(0)));
1552  Record.push_back(VE.getValueID(C->getOperand(1)));
1553  uint64_t Flags = GetOptimizationFlags(CE);
1554  if (Flags != 0)
1555  Record.push_back(Flags);
1556  }
1557  break;
1558  case Instruction::GetElementPtr: {
1559  Code = bitc::CST_CODE_CE_GEP;
1560  const auto *GO = cast<GEPOperator>(C);
1561  if (GO->isInBounds())
1563  Record.push_back(VE.getTypeID(GO->getSourceElementType()));
1564  for (unsigned i = 0, e = CE->getNumOperands(); i != e; ++i) {
1565  Record.push_back(VE.getTypeID(C->getOperand(i)->getType()));
1566  Record.push_back(VE.getValueID(C->getOperand(i)));
1567  }
1568  break;
1569  }
1570  case Instruction::Select:
1571  Code = bitc::CST_CODE_CE_SELECT;
1572  Record.push_back(VE.getValueID(C->getOperand(0)));
1573  Record.push_back(VE.getValueID(C->getOperand(1)));
1574  Record.push_back(VE.getValueID(C->getOperand(2)));
1575  break;
1578  Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
1579  Record.push_back(VE.getValueID(C->getOperand(0)));
1580  Record.push_back(VE.getTypeID(C->getOperand(1)->getType()));
1581  Record.push_back(VE.getValueID(C->getOperand(1)));
1582  break;
1583  case Instruction::InsertElement:
1585  Record.push_back(VE.getValueID(C->getOperand(0)));
1586  Record.push_back(VE.getValueID(C->getOperand(1)));
1587  Record.push_back(VE.getTypeID(C->getOperand(2)->getType()));
1588  Record.push_back(VE.getValueID(C->getOperand(2)));
1589  break;
1590  case Instruction::ShuffleVector:
1591  // If the return type and argument types are the same, this is a
1592  // standard shufflevector instruction. If the types are different,
1593  // then the shuffle is widening or truncating the input vectors, and
1594  // the argument type must also be encoded.
1595  if (C->getType() == C->getOperand(0)->getType()) {
1597  } else {
1599  Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
1600  }
1601  Record.push_back(VE.getValueID(C->getOperand(0)));
1602  Record.push_back(VE.getValueID(C->getOperand(1)));
1603  Record.push_back(VE.getValueID(C->getOperand(2)));
1604  break;
1605  case Instruction::ICmp:
1606  case Instruction::FCmp:
1607  Code = bitc::CST_CODE_CE_CMP;
1608  Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
1609  Record.push_back(VE.getValueID(C->getOperand(0)));
1610  Record.push_back(VE.getValueID(C->getOperand(1)));
1611  Record.push_back(CE->getPredicate());
1612  break;
1613  }
1614  } else if (const BlockAddress *BA = dyn_cast<BlockAddress>(C)) {
1616  Record.push_back(VE.getTypeID(BA->getFunction()->getType()));
1617  Record.push_back(VE.getValueID(BA->getFunction()));
1618  Record.push_back(VE.getGlobalBasicBlockID(BA->getBasicBlock()));
1619  } else {
1620 #ifndef NDEBUG
1621  C->dump();
1622 #endif
1623  llvm_unreachable("Unknown constant!");
1624  }
1625  Stream.EmitRecord(Code, Record, AbbrevToUse);
1626  Record.clear();
1627  }
1628 
1629  Stream.ExitBlock();
1630 }
1631 
1633  BitstreamWriter &Stream) {
1634  const ValueEnumerator::ValueList &Vals = VE.getValues();
1635 
1636  // Find the first constant to emit, which is the first non-globalvalue value.
1637  // We know globalvalues have been emitted by WriteModuleInfo.
1638  for (unsigned i = 0, e = Vals.size(); i != e; ++i) {
1639  if (!isa<GlobalValue>(Vals[i].first)) {
1640  WriteConstants(i, Vals.size(), VE, Stream, true);
1641  return;
1642  }
1643  }
1644 }
1645 
1646 /// PushValueAndType - The file has to encode both the value and type id for
1647 /// many values, because we need to know what type to create for forward
1648 /// references. However, most operands are not forward references, so this type
1649 /// field is not needed.
1650 ///
1651 /// This function adds V's value ID to Vals. If the value ID is higher than the
1652 /// instruction ID, then it is a forward reference, and it also includes the
1653 /// type ID. The value ID that is written is encoded relative to the InstID.
1654 static bool PushValueAndType(const Value *V, unsigned InstID,
1656  ValueEnumerator &VE) {
1657  unsigned ValID = VE.getValueID(V);
1658  // Make encoding relative to the InstID.
1659  Vals.push_back(InstID - ValID);
1660  if (ValID >= InstID) {
1661  Vals.push_back(VE.getTypeID(V->getType()));
1662  return true;
1663  }
1664  return false;
1665 }
1666 
1667 /// pushValue - Like PushValueAndType, but where the type of the value is
1668 /// omitted (perhaps it was already encoded in an earlier operand).
1669 static void pushValue(const Value *V, unsigned InstID,
1671  ValueEnumerator &VE) {
1672  unsigned ValID = VE.getValueID(V);
1673  Vals.push_back(InstID - ValID);
1674 }
1675 
1676 static void pushValueSigned(const Value *V, unsigned InstID,
1678  ValueEnumerator &VE) {
1679  unsigned ValID = VE.getValueID(V);
1680  int64_t diff = ((int32_t)InstID - (int32_t)ValID);
1681  emitSignedInt64(Vals, diff);
1682 }
1683 
1684 /// WriteInstruction - Emit an instruction to the specified stream.
1685 static void WriteInstruction(const Instruction &I, unsigned InstID,
1686  ValueEnumerator &VE, BitstreamWriter &Stream,
1687  SmallVectorImpl<unsigned> &Vals) {
1688  unsigned Code = 0;
1689  unsigned AbbrevToUse = 0;
1690  VE.setInstructionID(&I);
1691  switch (I.getOpcode()) {
1692  default:
1693  if (Instruction::isCast(I.getOpcode())) {
1695  if (!PushValueAndType(I.getOperand(0), InstID, Vals, VE))
1696  AbbrevToUse = FUNCTION_INST_CAST_ABBREV;
1697  Vals.push_back(VE.getTypeID(I.getType()));
1698  Vals.push_back(GetEncodedCastOpcode(I.getOpcode()));
1699  } else {
1700  assert(isa<BinaryOperator>(I) && "Unknown instruction!");
1702  if (!PushValueAndType(I.getOperand(0), InstID, Vals, VE))
1703  AbbrevToUse = FUNCTION_INST_BINOP_ABBREV;
1704  pushValue(I.getOperand(1), InstID, Vals, VE);
1705  Vals.push_back(GetEncodedBinaryOpcode(I.getOpcode()));
1706  uint64_t Flags = GetOptimizationFlags(&I);
1707  if (Flags != 0) {
1708  if (AbbrevToUse == FUNCTION_INST_BINOP_ABBREV)
1709  AbbrevToUse = FUNCTION_INST_BINOP_FLAGS_ABBREV;
1710  Vals.push_back(Flags);
1711  }
1712  }
1713  break;
1714 
1715  case Instruction::GetElementPtr: {
1716  Code = bitc::FUNC_CODE_INST_GEP;
1717  AbbrevToUse = FUNCTION_INST_GEP_ABBREV;
1718  auto &GEPInst = cast<GetElementPtrInst>(I);
1719  Vals.push_back(GEPInst.isInBounds());
1720  Vals.push_back(VE.getTypeID(GEPInst.getSourceElementType()));
1721  for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
1722  PushValueAndType(I.getOperand(i), InstID, Vals, VE);
1723  break;
1724  }
1725  case Instruction::ExtractValue: {
1727  PushValueAndType(I.getOperand(0), InstID, Vals, VE);
1728  const ExtractValueInst *EVI = cast<ExtractValueInst>(&I);
1729  Vals.append(EVI->idx_begin(), EVI->idx_end());
1730  break;
1731  }
1732  case Instruction::InsertValue: {
1734  PushValueAndType(I.getOperand(0), InstID, Vals, VE);
1735  PushValueAndType(I.getOperand(1), InstID, Vals, VE);
1736  const InsertValueInst *IVI = cast<InsertValueInst>(&I);
1737  Vals.append(IVI->idx_begin(), IVI->idx_end());
1738  break;
1739  }
1740  case Instruction::Select:
1742  PushValueAndType(I.getOperand(1), InstID, Vals, VE);
1743  pushValue(I.getOperand(2), InstID, Vals, VE);
1744  PushValueAndType(I.getOperand(0), InstID, Vals, VE);
1745  break;
1748  PushValueAndType(I.getOperand(0), InstID, Vals, VE);
1749  PushValueAndType(I.getOperand(1), InstID, Vals, VE);
1750  break;
1751  case Instruction::InsertElement:
1753  PushValueAndType(I.getOperand(0), InstID, Vals, VE);
1754  pushValue(I.getOperand(1), InstID, Vals, VE);
1755  PushValueAndType(I.getOperand(2), InstID, Vals, VE);
1756  break;
1757  case Instruction::ShuffleVector:
1759  PushValueAndType(I.getOperand(0), InstID, Vals, VE);
1760  pushValue(I.getOperand(1), InstID, Vals, VE);
1761  pushValue(I.getOperand(2), InstID, Vals, VE);
1762  break;
1763  case Instruction::ICmp:
1764  case Instruction::FCmp: {
1765  // compare returning Int1Ty or vector of Int1Ty
1767  PushValueAndType(I.getOperand(0), InstID, Vals, VE);
1768  pushValue(I.getOperand(1), InstID, Vals, VE);
1769  Vals.push_back(cast<CmpInst>(I).getPredicate());
1770  uint64_t Flags = GetOptimizationFlags(&I);
1771  if (Flags != 0)
1772  Vals.push_back(Flags);
1773  break;
1774  }
1775 
1776  case Instruction::Ret:
1777  {
1778  Code = bitc::FUNC_CODE_INST_RET;
1779  unsigned NumOperands = I.getNumOperands();
1780  if (NumOperands == 0)
1781  AbbrevToUse = FUNCTION_INST_RET_VOID_ABBREV;
1782  else if (NumOperands == 1) {
1783  if (!PushValueAndType(I.getOperand(0), InstID, Vals, VE))
1784  AbbrevToUse = FUNCTION_INST_RET_VAL_ABBREV;
1785  } else {
1786  for (unsigned i = 0, e = NumOperands; i != e; ++i)
1787  PushValueAndType(I.getOperand(i), InstID, Vals, VE);
1788  }
1789  }
1790  break;
1791  case Instruction::Br:
1792  {
1793  Code = bitc::FUNC_CODE_INST_BR;
1794  const BranchInst &II = cast<BranchInst>(I);
1795  Vals.push_back(VE.getValueID(II.getSuccessor(0)));
1796  if (II.isConditional()) {
1797  Vals.push_back(VE.getValueID(II.getSuccessor(1)));
1798  pushValue(II.getCondition(), InstID, Vals, VE);
1799  }
1800  }
1801  break;
1802  case Instruction::Switch:
1803  {
1805  const SwitchInst &SI = cast<SwitchInst>(I);
1806  Vals.push_back(VE.getTypeID(SI.getCondition()->getType()));
1807  pushValue(SI.getCondition(), InstID, Vals, VE);
1808  Vals.push_back(VE.getValueID(SI.getDefaultDest()));
1809  for (SwitchInst::ConstCaseIt i = SI.case_begin(), e = SI.case_end();
1810  i != e; ++i) {
1811  Vals.push_back(VE.getValueID(i.getCaseValue()));
1812  Vals.push_back(VE.getValueID(i.getCaseSuccessor()));
1813  }
1814  }
1815  break;
1816  case Instruction::IndirectBr:
1818  Vals.push_back(VE.getTypeID(I.getOperand(0)->getType()));
1819  // Encode the address operand as relative, but not the basic blocks.
1820  pushValue(I.getOperand(0), InstID, Vals, VE);
1821  for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i)
1822  Vals.push_back(VE.getValueID(I.getOperand(i)));
1823  break;
1824 
1825  case Instruction::Invoke: {
1826  const InvokeInst *II = cast<InvokeInst>(&I);
1827  const Value *Callee = II->getCalledValue();
1828  FunctionType *FTy = II->getFunctionType();
1830 
1831  Vals.push_back(VE.getAttributeID(II->getAttributes()));
1832  Vals.push_back(II->getCallingConv() | 1 << 13);
1833  Vals.push_back(VE.getValueID(II->getNormalDest()));
1834  Vals.push_back(VE.getValueID(II->getUnwindDest()));
1835  Vals.push_back(VE.getTypeID(FTy));
1836  PushValueAndType(Callee, InstID, Vals, VE);
1837 
1838  // Emit value #'s for the fixed parameters.
1839  for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
1840  pushValue(I.getOperand(i), InstID, Vals, VE); // fixed param.
1841 
1842  // Emit type/value pairs for varargs params.
1843  if (FTy->isVarArg()) {
1844  for (unsigned i = FTy->getNumParams(), e = I.getNumOperands()-3;
1845  i != e; ++i)
1846  PushValueAndType(I.getOperand(i), InstID, Vals, VE); // vararg
1847  }
1848  break;
1849  }
1850  case Instruction::Resume:
1852  PushValueAndType(I.getOperand(0), InstID, Vals, VE);
1853  break;
1854  case Instruction::Unreachable:
1856  AbbrevToUse = FUNCTION_INST_UNREACHABLE_ABBREV;
1857  break;
1858 
1859  case Instruction::PHI: {
1860  const PHINode &PN = cast<PHINode>(I);
1861  Code = bitc::FUNC_CODE_INST_PHI;
1862  // With the newer instruction encoding, forward references could give
1863  // negative valued IDs. This is most common for PHIs, so we use
1864  // signed VBRs.
1866  Vals64.push_back(VE.getTypeID(PN.getType()));
1867  for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
1868  pushValueSigned(PN.getIncomingValue(i), InstID, Vals64, VE);
1869  Vals64.push_back(VE.getValueID(PN.getIncomingBlock(i)));
1870  }
1871  // Emit a Vals64 vector and exit.
1872  Stream.EmitRecord(Code, Vals64, AbbrevToUse);
1873  Vals64.clear();
1874  return;
1875  }
1876 
1877  case Instruction::LandingPad: {
1878  const LandingPadInst &LP = cast<LandingPadInst>(I);
1880  Vals.push_back(VE.getTypeID(LP.getType()));
1881  Vals.push_back(LP.isCleanup());
1882  Vals.push_back(LP.getNumClauses());
1883  for (unsigned I = 0, E = LP.getNumClauses(); I != E; ++I) {
1884  if (LP.isCatch(I))
1885  Vals.push_back(LandingPadInst::Catch);
1886  else
1887  Vals.push_back(LandingPadInst::Filter);
1888  PushValueAndType(LP.getClause(I), InstID, Vals, VE);
1889  }
1890  break;
1891  }
1892 
1893  case Instruction::Alloca: {
1895  const AllocaInst &AI = cast<AllocaInst>(I);
1896  Vals.push_back(VE.getTypeID(AI.getAllocatedType()));
1897  Vals.push_back(VE.getTypeID(I.getOperand(0)->getType()));
1898  Vals.push_back(VE.getValueID(I.getOperand(0))); // size.
1899  unsigned AlignRecord = Log2_32(AI.getAlignment()) + 1;
1900  assert(Log2_32(Value::MaximumAlignment) + 1 < 1 << 5 &&
1901  "not enough bits for maximum alignment");
1902  assert(AlignRecord < 1 << 5 && "alignment greater than 1 << 64");
1903  AlignRecord |= AI.isUsedWithInAlloca() << 5;
1904  AlignRecord |= 1 << 6;
1905  Vals.push_back(AlignRecord);
1906  break;
1907  }
1908 
1909  case Instruction::Load:
1910  if (cast<LoadInst>(I).isAtomic()) {
1912  PushValueAndType(I.getOperand(0), InstID, Vals, VE);
1913  } else {
1915  if (!PushValueAndType(I.getOperand(0), InstID, Vals, VE)) // ptr
1916  AbbrevToUse = FUNCTION_INST_LOAD_ABBREV;
1917  }
1918  Vals.push_back(VE.getTypeID(I.getType()));
1919  Vals.push_back(Log2_32(cast<LoadInst>(I).getAlignment())+1);
1920  Vals.push_back(cast<LoadInst>(I).isVolatile());
1921  if (cast<LoadInst>(I).isAtomic()) {
1922  Vals.push_back(GetEncodedOrdering(cast<LoadInst>(I).getOrdering()));
1923  Vals.push_back(GetEncodedSynchScope(cast<LoadInst>(I).getSynchScope()));
1924  }
1925  break;
1926  case Instruction::Store:
1927  if (cast<StoreInst>(I).isAtomic())
1929  else
1931  PushValueAndType(I.getOperand(1), InstID, Vals, VE); // ptrty + ptr
1932  PushValueAndType(I.getOperand(0), InstID, Vals, VE); // valty + val
1933  Vals.push_back(Log2_32(cast<StoreInst>(I).getAlignment())+1);
1934  Vals.push_back(cast<StoreInst>(I).isVolatile());
1935  if (cast<StoreInst>(I).isAtomic()) {
1936  Vals.push_back(GetEncodedOrdering(cast<StoreInst>(I).getOrdering()));
1937  Vals.push_back(GetEncodedSynchScope(cast<StoreInst>(I).getSynchScope()));
1938  }
1939  break;
1940  case Instruction::AtomicCmpXchg:
1942  PushValueAndType(I.getOperand(0), InstID, Vals, VE); // ptrty + ptr
1943  PushValueAndType(I.getOperand(1), InstID, Vals, VE); // cmp.
1944  pushValue(I.getOperand(2), InstID, Vals, VE); // newval.
1945  Vals.push_back(cast<AtomicCmpXchgInst>(I).isVolatile());
1946  Vals.push_back(GetEncodedOrdering(
1947  cast<AtomicCmpXchgInst>(I).getSuccessOrdering()));
1948  Vals.push_back(GetEncodedSynchScope(
1949  cast<AtomicCmpXchgInst>(I).getSynchScope()));
1950  Vals.push_back(GetEncodedOrdering(
1951  cast<AtomicCmpXchgInst>(I).getFailureOrdering()));
1952  Vals.push_back(cast<AtomicCmpXchgInst>(I).isWeak());
1953  break;
1954  case Instruction::AtomicRMW:
1956  PushValueAndType(I.getOperand(0), InstID, Vals, VE); // ptrty + ptr
1957  pushValue(I.getOperand(1), InstID, Vals, VE); // val.
1958  Vals.push_back(GetEncodedRMWOperation(
1959  cast<AtomicRMWInst>(I).getOperation()));
1960  Vals.push_back(cast<AtomicRMWInst>(I).isVolatile());
1961  Vals.push_back(GetEncodedOrdering(cast<AtomicRMWInst>(I).getOrdering()));
1962  Vals.push_back(GetEncodedSynchScope(
1963  cast<AtomicRMWInst>(I).getSynchScope()));
1964  break;
1965  case Instruction::Fence:
1967  Vals.push_back(GetEncodedOrdering(cast<FenceInst>(I).getOrdering()));
1968  Vals.push_back(GetEncodedSynchScope(cast<FenceInst>(I).getSynchScope()));
1969  break;
1970  case Instruction::Call: {
1971  const CallInst &CI = cast<CallInst>(I);
1972  FunctionType *FTy = CI.getFunctionType();
1973 
1975 
1976  Vals.push_back(VE.getAttributeID(CI.getAttributes()));
1977  Vals.push_back((CI.getCallingConv() << 1) | unsigned(CI.isTailCall()) |
1978  unsigned(CI.isMustTailCall()) << 14 | 1 << 15);
1979  Vals.push_back(VE.getTypeID(FTy));
1980  PushValueAndType(CI.getCalledValue(), InstID, Vals, VE); // Callee
1981 
1982  // Emit value #'s for the fixed parameters.
1983  for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i) {
1984  // Check for labels (can happen with asm labels).
1985  if (FTy->getParamType(i)->isLabelTy())
1986  Vals.push_back(VE.getValueID(CI.getArgOperand(i)));
1987  else
1988  pushValue(CI.getArgOperand(i), InstID, Vals, VE); // fixed param.
1989  }
1990 
1991  // Emit type/value pairs for varargs params.
1992  if (FTy->isVarArg()) {
1993  for (unsigned i = FTy->getNumParams(), e = CI.getNumArgOperands();
1994  i != e; ++i)
1995  PushValueAndType(CI.getArgOperand(i), InstID, Vals, VE); // varargs
1996  }
1997  break;
1998  }
1999  case Instruction::VAArg:
2001  Vals.push_back(VE.getTypeID(I.getOperand(0)->getType())); // valistty
2002  pushValue(I.getOperand(0), InstID, Vals, VE); // valist.
2003  Vals.push_back(VE.getTypeID(I.getType())); // restype.
2004  break;
2005  }
2006 
2007  Stream.EmitRecord(Code, Vals, AbbrevToUse);
2008  Vals.clear();
2009 }
2010 
2011 // Emit names for globals/functions etc.
2013  const ValueEnumerator &VE,
2014  BitstreamWriter &Stream) {
2015  if (VST.empty()) return;
2017 
2018  // FIXME: Set up the abbrev, we know how many values there are!
2019  // FIXME: We know if the type names can use 7-bit ascii.
2020  SmallVector<unsigned, 64> NameVals;
2021 
2022  for (ValueSymbolTable::const_iterator SI = VST.begin(), SE = VST.end();
2023  SI != SE; ++SI) {
2024 
2025  const ValueName &Name = *SI;
2026 
2027  // Figure out the encoding to use for the name.
2028  bool is7Bit = true;
2029  bool isChar6 = true;
2030  for (const char *C = Name.getKeyData(), *E = C+Name.getKeyLength();
2031  C != E; ++C) {
2032  if (isChar6)
2033  isChar6 = BitCodeAbbrevOp::isChar6(*C);
2034  if ((unsigned char)*C & 128) {
2035  is7Bit = false;
2036  break; // don't bother scanning the rest.
2037  }
2038  }
2039 
2040  unsigned AbbrevToUse = VST_ENTRY_8_ABBREV;
2041 
2042  // VST_ENTRY: [valueid, namechar x N]
2043  // VST_BBENTRY: [bbid, namechar x N]
2044  unsigned Code;
2045  if (isa<BasicBlock>(SI->getValue())) {
2046  Code = bitc::VST_CODE_BBENTRY;
2047  if (isChar6)
2048  AbbrevToUse = VST_BBENTRY_6_ABBREV;
2049  } else {
2050  Code = bitc::VST_CODE_ENTRY;
2051  if (isChar6)
2052  AbbrevToUse = VST_ENTRY_6_ABBREV;
2053  else if (is7Bit)
2054  AbbrevToUse = VST_ENTRY_7_ABBREV;
2055  }
2056 
2057  NameVals.push_back(VE.getValueID(SI->getValue()));
2058  for (const char *P = Name.getKeyData(),
2059  *E = Name.getKeyData()+Name.getKeyLength(); P != E; ++P)
2060  NameVals.push_back((unsigned char)*P);
2061 
2062  // Emit the finished record.
2063  Stream.EmitRecord(Code, NameVals, AbbrevToUse);
2064  NameVals.clear();
2065  }
2066  Stream.ExitBlock();
2067 }
2068 
2069 static void WriteUseList(ValueEnumerator &VE, UseListOrder &&Order,
2070  BitstreamWriter &Stream) {
2071  assert(Order.Shuffle.size() >= 2 && "Shuffle too small");
2072  unsigned Code;
2073  if (isa<BasicBlock>(Order.V))
2074  Code = bitc::USELIST_CODE_BB;
2075  else
2077 
2078  SmallVector<uint64_t, 64> Record(Order.Shuffle.begin(), Order.Shuffle.end());
2079  Record.push_back(VE.getValueID(Order.V));
2080  Stream.EmitRecord(Code, Record);
2081 }
2082 
2084  BitstreamWriter &Stream) {
2085  assert(VE.shouldPreserveUseListOrder() &&
2086  "Expected to be preserving use-list order");
2087 
2088  auto hasMore = [&]() {
2089  return !VE.UseListOrders.empty() && VE.UseListOrders.back().F == F;
2090  };
2091  if (!hasMore())
2092  // Nothing to do.
2093  return;
2094 
2096  while (hasMore()) {
2097  WriteUseList(VE, std::move(VE.UseListOrders.back()), Stream);
2098  VE.UseListOrders.pop_back();
2099  }
2100  Stream.ExitBlock();
2101 }
2102 
2103 /// WriteFunction - Emit a function body to the module stream.
2104 static void WriteFunction(const Function &F, ValueEnumerator &VE,
2105  BitstreamWriter &Stream) {
2107  VE.incorporateFunction(F);
2108 
2110 
2111  // Emit the number of basic blocks, so the reader can create them ahead of
2112  // time.
2113  Vals.push_back(VE.getBasicBlocks().size());
2115  Vals.clear();
2116 
2117  // If there are function-local constants, emit them now.
2118  unsigned CstStart, CstEnd;
2119  VE.getFunctionConstantRange(CstStart, CstEnd);
2120  WriteConstants(CstStart, CstEnd, VE, Stream, false);
2121 
2122  // If there is function-local metadata, emit it now.
2123  WriteFunctionLocalMetadata(F, VE, Stream);
2124 
2125  // Keep a running idea of what the instruction ID is.
2126  unsigned InstID = CstEnd;
2127 
2128  bool NeedsMetadataAttachment = F.hasMetadata();
2129 
2130  DILocation *LastDL = nullptr;
2131 
2132  // Finally, emit all the instructions, in order.
2133  for (Function::const_iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
2134  for (BasicBlock::const_iterator I = BB->begin(), E = BB->end();
2135  I != E; ++I) {
2136  WriteInstruction(*I, InstID, VE, Stream, Vals);
2137 
2138  if (!I->getType()->isVoidTy())
2139  ++InstID;
2140 
2141  // If the instruction has metadata, write a metadata attachment later.
2142  NeedsMetadataAttachment |= I->hasMetadataOtherThanDebugLoc();
2143 
2144  // If the instruction has a debug location, emit it.
2145  DILocation *DL = I->getDebugLoc();
2146  if (!DL)
2147  continue;
2148 
2149  if (DL == LastDL) {
2150  // Just repeat the same debug loc as last time.
2152  continue;
2153  }
2154 
2155  Vals.push_back(DL->getLine());
2156  Vals.push_back(DL->getColumn());
2157  Vals.push_back(VE.getMetadataOrNullID(DL->getScope()));
2158  Vals.push_back(VE.getMetadataOrNullID(DL->getInlinedAt()));
2159  Stream.EmitRecord(bitc::FUNC_CODE_DEBUG_LOC, Vals);
2160  Vals.clear();
2161 
2162  LastDL = DL;
2163  }
2164 
2165  // Emit names for all the instructions etc.
2166  WriteValueSymbolTable(F.getValueSymbolTable(), VE, Stream);
2167 
2168  if (NeedsMetadataAttachment)
2169  WriteMetadataAttachment(F, VE, Stream);
2170  if (VE.shouldPreserveUseListOrder())
2171  WriteUseListBlock(&F, VE, Stream);
2172  VE.purgeFunction();
2173  Stream.ExitBlock();
2174 }
2175 
2176 // Emit blockinfo, which defines the standard abbreviations etc.
2177 static void WriteBlockInfo(const ValueEnumerator &VE, BitstreamWriter &Stream) {
2178  // We only want to emit block info records for blocks that have multiple
2179  // instances: CONSTANTS_BLOCK, FUNCTION_BLOCK and VALUE_SYMTAB_BLOCK.
2180  // Other blocks can define their abbrevs inline.
2181  Stream.EnterBlockInfoBlock(2);
2182 
2183  { // 8-bit fixed-width VST_ENTRY/VST_BBENTRY strings.
2184  BitCodeAbbrev *Abbv = new BitCodeAbbrev();
2190  Abbv) != VST_ENTRY_8_ABBREV)
2191  llvm_unreachable("Unexpected abbrev ordering!");
2192  }
2193 
2194  { // 7-bit fixed width VST_ENTRY strings.
2195  BitCodeAbbrev *Abbv = new BitCodeAbbrev();
2201  Abbv) != VST_ENTRY_7_ABBREV)
2202  llvm_unreachable("Unexpected abbrev ordering!");
2203  }
2204  { // 6-bit char6 VST_ENTRY strings.
2205  BitCodeAbbrev *Abbv = new BitCodeAbbrev();
2211  Abbv) != VST_ENTRY_6_ABBREV)
2212  llvm_unreachable("Unexpected abbrev ordering!");
2213  }
2214  { // 6-bit char6 VST_BBENTRY strings.
2215  BitCodeAbbrev *Abbv = new BitCodeAbbrev();
2221  Abbv) != VST_BBENTRY_6_ABBREV)
2222  llvm_unreachable("Unexpected abbrev ordering!");
2223  }
2224 
2225 
2226 
2227  { // SETTYPE abbrev for CONSTANTS_BLOCK.
2228  BitCodeAbbrev *Abbv = new BitCodeAbbrev();
2233  Abbv) != CONSTANTS_SETTYPE_ABBREV)
2234  llvm_unreachable("Unexpected abbrev ordering!");
2235  }
2236 
2237  { // INTEGER abbrev for CONSTANTS_BLOCK.
2238  BitCodeAbbrev *Abbv = new BitCodeAbbrev();
2242  Abbv) != CONSTANTS_INTEGER_ABBREV)
2243  llvm_unreachable("Unexpected abbrev ordering!");
2244  }
2245 
2246  { // CE_CAST abbrev for CONSTANTS_BLOCK.
2247  BitCodeAbbrev *Abbv = new BitCodeAbbrev();
2249  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // cast opc
2250  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, // typeid
2252  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // value id
2253 
2255  Abbv) != CONSTANTS_CE_CAST_Abbrev)
2256  llvm_unreachable("Unexpected abbrev ordering!");
2257  }
2258  { // NULL abbrev for CONSTANTS_BLOCK.
2259  BitCodeAbbrev *Abbv = new BitCodeAbbrev();
2262  Abbv) != CONSTANTS_NULL_Abbrev)
2263  llvm_unreachable("Unexpected abbrev ordering!");
2264  }
2265 
2266  // FIXME: This should only use space for first class types!
2267 
2268  { // INST_LOAD abbrev for FUNCTION_BLOCK.
2269  BitCodeAbbrev *Abbv = new BitCodeAbbrev();
2271  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Ptr
2272  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, // dest ty
2274  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // Align
2275  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // volatile
2277  Abbv) != FUNCTION_INST_LOAD_ABBREV)
2278  llvm_unreachable("Unexpected abbrev ordering!");
2279  }
2280  { // INST_BINOP abbrev for FUNCTION_BLOCK.
2281  BitCodeAbbrev *Abbv = new BitCodeAbbrev();
2283  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // LHS
2284  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // RHS
2285  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
2287  Abbv) != FUNCTION_INST_BINOP_ABBREV)
2288  llvm_unreachable("Unexpected abbrev ordering!");
2289  }
2290  { // INST_BINOP_FLAGS abbrev for FUNCTION_BLOCK.
2291  BitCodeAbbrev *Abbv = new BitCodeAbbrev();
2293  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // LHS
2294  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // RHS
2295  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
2296  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7)); // flags
2299  llvm_unreachable("Unexpected abbrev ordering!");
2300  }
2301  { // INST_CAST abbrev for FUNCTION_BLOCK.
2302  BitCodeAbbrev *Abbv = new BitCodeAbbrev();
2304  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // OpVal
2305  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, // dest ty
2307  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
2309  Abbv) != FUNCTION_INST_CAST_ABBREV)
2310  llvm_unreachable("Unexpected abbrev ordering!");
2311  }
2312 
2313  { // INST_RET abbrev for FUNCTION_BLOCK.
2314  BitCodeAbbrev *Abbv = new BitCodeAbbrev();
2318  llvm_unreachable("Unexpected abbrev ordering!");
2319  }
2320  { // INST_RET abbrev for FUNCTION_BLOCK.
2321  BitCodeAbbrev *Abbv = new BitCodeAbbrev();
2323  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // ValID
2326  llvm_unreachable("Unexpected abbrev ordering!");
2327  }
2328  { // INST_UNREACHABLE abbrev for FUNCTION_BLOCK.
2329  BitCodeAbbrev *Abbv = new BitCodeAbbrev();
2333  llvm_unreachable("Unexpected abbrev ordering!");
2334  }
2335  {
2336  BitCodeAbbrev *Abbv = new BitCodeAbbrev();
2339  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, // dest ty
2340  Log2_32_Ceil(VE.getTypes().size() + 1)));
2343  if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
2345  llvm_unreachable("Unexpected abbrev ordering!");
2346  }
2347 
2348  Stream.ExitBlock();
2349 }
2350 
2351 /// WriteModule - Emit the specified module to the bitstream.
2352 static void WriteModule(const Module *M, BitstreamWriter &Stream,
2353  bool ShouldPreserveUseListOrder) {
2355 
2357  unsigned CurVersion = 1;
2358  Vals.push_back(CurVersion);
2359  Stream.EmitRecord(bitc::MODULE_CODE_VERSION, Vals);
2360 
2361  // Analyze the module, enumerating globals, functions, etc.
2362  ValueEnumerator VE(*M, ShouldPreserveUseListOrder);
2363 
2364  // Emit blockinfo, which defines the standard abbreviations etc.
2365  WriteBlockInfo(VE, Stream);
2366 
2367  // Emit information about attribute groups.
2368  WriteAttributeGroupTable(VE, Stream);
2369 
2370  // Emit information about parameter attributes.
2371  WriteAttributeTable(VE, Stream);
2372 
2373  // Emit information describing all of the types in the module.
2374  WriteTypeTable(VE, Stream);
2375 
2376  writeComdats(VE, Stream);
2377 
2378  // Emit top-level description of module, including target triple, inline asm,
2379  // descriptors for global variables, and function prototype info.
2380  WriteModuleInfo(M, VE, Stream);
2381 
2382  // Emit constants.
2383  WriteModuleConstants(VE, Stream);
2384 
2385  // Emit metadata.
2386  WriteModuleMetadata(M, VE, Stream);
2387 
2388  // Emit metadata.
2389  WriteModuleMetadataStore(M, Stream);
2390 
2391  // Emit names for globals/functions etc.
2392  WriteValueSymbolTable(M->getValueSymbolTable(), VE, Stream);
2393 
2394  // Emit module-level use-lists.
2395  if (VE.shouldPreserveUseListOrder())
2396  WriteUseListBlock(nullptr, VE, Stream);
2397 
2398  // Emit function bodies.
2399  for (Module::const_iterator F = M->begin(), E = M->end(); F != E; ++F)
2400  if (!F->isDeclaration())
2401  WriteFunction(*F, VE, Stream);
2402 
2403  Stream.ExitBlock();
2404 }
2405 
2406 /// EmitDarwinBCHeader - If generating a bc file on darwin, we have to emit a
2407 /// header and trailer to make it compatible with the system archiver. To do
2408 /// this we emit the following header, and then emit a trailer that pads the
2409 /// file out to be a multiple of 16 bytes.
2410 ///
2411 /// struct bc_header {
2412 /// uint32_t Magic; // 0x0B17C0DE
2413 /// uint32_t Version; // Version, currently always 0.
2414 /// uint32_t BitcodeOffset; // Offset to traditional bitcode file.
2415 /// uint32_t BitcodeSize; // Size of traditional bitcode file.
2416 /// uint32_t CPUType; // CPU specifier.
2417 /// ... potentially more later ...
2418 /// };
2419 enum {
2420  DarwinBCSizeFieldOffset = 3*4, // Offset to bitcode_size.
2422 };
2423 
2424 static void WriteInt32ToBuffer(uint32_t Value, SmallVectorImpl<char> &Buffer,
2425  uint32_t &Position) {
2426  support::endian::write32le(&Buffer[Position], Value);
2427  Position += 4;
2428 }
2429 
2431  const Triple &TT) {
2432  unsigned CPUType = ~0U;
2433 
2434  // Match x86_64-*, i[3-9]86-*, powerpc-*, powerpc64-*, arm-*, thumb-*,
2435  // armv[0-9]-*, thumbv[0-9]-*, armv5te-*, or armv6t2-*. The CPUType is a magic
2436  // number from /usr/include/mach/machine.h. It is ok to reproduce the
2437  // specific constants here because they are implicitly part of the Darwin ABI.
2438  enum {
2439  DARWIN_CPU_ARCH_ABI64 = 0x01000000,
2440  DARWIN_CPU_TYPE_X86 = 7,
2441  DARWIN_CPU_TYPE_ARM = 12,
2442  DARWIN_CPU_TYPE_POWERPC = 18
2443  };
2444 
2445  Triple::ArchType Arch = TT.getArch();
2446  if (Arch == Triple::x86_64)
2447  CPUType = DARWIN_CPU_TYPE_X86 | DARWIN_CPU_ARCH_ABI64;
2448  else if (Arch == Triple::x86)
2449  CPUType = DARWIN_CPU_TYPE_X86;
2450  else if (Arch == Triple::ppc)
2451  CPUType = DARWIN_CPU_TYPE_POWERPC;
2452  else if (Arch == Triple::ppc64)
2453  CPUType = DARWIN_CPU_TYPE_POWERPC | DARWIN_CPU_ARCH_ABI64;
2454  else if (Arch == Triple::arm || Arch == Triple::thumb)
2455  CPUType = DARWIN_CPU_TYPE_ARM;
2456 
2457  // Traditional Bitcode starts after header.
2458  assert(Buffer.size() >= DarwinBCHeaderSize &&
2459  "Expected header size to be reserved");
2460  unsigned BCOffset = DarwinBCHeaderSize;
2461  unsigned BCSize = Buffer.size()-DarwinBCHeaderSize;
2462 
2463  // Write the magic and version.
2464  unsigned Position = 0;
2465  WriteInt32ToBuffer(0x0B17C0DE , Buffer, Position);
2466  WriteInt32ToBuffer(0 , Buffer, Position); // Version.
2467  WriteInt32ToBuffer(BCOffset , Buffer, Position);
2468  WriteInt32ToBuffer(BCSize , Buffer, Position);
2469  WriteInt32ToBuffer(CPUType , Buffer, Position);
2470 
2471  // If the file is not a multiple of 16 bytes, insert dummy padding.
2472  while (Buffer.size() & 15)
2473  Buffer.push_back(0);
2474 }
2475 
2476 /// WriteBitcodeToFile - Write the specified module to the specified output
2477 /// stream.
2479  bool ShouldPreserveUseListOrder) {
2480  SmallVector<char, 0> Buffer;
2481  Buffer.reserve(256*1024);
2482 
2483  // If this is darwin or another generic macho target, reserve space for the
2484  // header.
2485  Triple TT(M->getTargetTriple());
2486  if (TT.isOSDarwin())
2487  Buffer.insert(Buffer.begin(), DarwinBCHeaderSize, 0);
2488 
2489  // Emit the module into the buffer.
2490  {
2491  BitstreamWriter Stream(Buffer);
2492 
2493  // Emit the file header.
2494  Stream.Emit((unsigned)'B', 8);
2495  Stream.Emit((unsigned)'C', 8);
2496  Stream.Emit(0x0, 4);
2497  Stream.Emit(0xC, 4);
2498  Stream.Emit(0xE, 4);
2499  Stream.Emit(0xD, 4);
2500 
2501  // Emit the module.
2502  WriteModule(M, Stream, ShouldPreserveUseListOrder);
2503  }
2504 
2505  if (TT.isOSDarwin())
2506  EmitDarwinBCHeaderAndTrailer(Buffer, TT);
2507 
2508  // Write the generated bitstream to "Out".
2509  Out.write((char*)&Buffer.front(), Buffer.size());
2510 }
MDString * getRawGetterName() const
static unsigned getBitWidth(Type *Ty, const DataLayout &DL)
Returns the bitwidth of the given scalar or pointer type (if unknown returns 0).
DISubprogramArray getSubprograms() const
const Value * getCalledValue() const
getCalledValue - Get a pointer to the function that is invoked by this instruction.
static unsigned GetEncodedSynchScope(SynchronizationScope SynchScope)
7: Labels
Definition: Type.h:63
unsigned Log2_32_Ceil(uint32_t Value)
Log2_32_Ceil - This function returns the ceil log base 2 of the specified value, 32 if the value is z...
Definition: MathExtras.h:481
static void WriteDIExpression(const DIExpression *N, const ValueEnumerator &, BitstreamWriter &Stream, SmallVectorImpl< uint64_t > &Record, unsigned Abbrev)
LinkageTypes getLinkage() const
Definition: GlobalValue.h:289
This class provides a symbol table of name/value pairs.
const ComdatSetType & getComdats() const
CaseIt case_end()
Returns a read/write iterator that points one past the last in the SwitchInst.
const ValueSymbolTable & getValueSymbolTable() const
Get the symbol table of global variable and function identifiers.
Definition: Module.h:540
static void WriteAttributeTable(const ValueEnumerator &VE, BitstreamWriter &Stream)
ExtractValueInst - This instruction extracts a struct member or array element value from an aggregate...
Special purpose, only applies to global arrays.
Definition: GlobalValue.h:46
VisibilityTypes getVisibility() const
Definition: GlobalValue.h:139
*p = old <signed v ? old : v
Definition: Instructions.h:704
DILocalScope * getScope() const
iterator begin()
Get an iterator that from the beginning of the symbol table.
Alignment of stack for function (3 bits) stored as log2 of alignment with +1 bias 0 means unaligned (...
Definition: Attributes.h:106
size_t size() const
size - Get the string size.
Definition: StringRef.h:113
static uint64_t GetOptimizationFlags(const Value *V)
static void WriteFunction(const Function &F, ValueEnumerator &VE, BitstreamWriter &Stream)
WriteFunction - Emit a function body to the module stream.
Sign extended before/after call.
Definition: Attributes.h:105
bool isOpaque() const
isOpaque - Return true if this is a type with an identity that has no body specified yet...
Definition: DerivedTypes.h:250
StringMapEntry - This is used to represent one value that is inserted into a StringMap.
Definition: StringMap.h:28
static void WriteDISubprogram(const DISubprogram *N, const ValueEnumerator &VE, BitstreamWriter &Stream, SmallVectorImpl< uint64_t > &Record, unsigned Abbrev)
bool hasMDString() const
Force argument to be passed in register.
Definition: Attributes.h:78
static void WriteDICompileUnit(const DICompileUnit *N, const ValueEnumerator &VE, BitstreamWriter &Stream, SmallVectorImpl< uint64_t > &Record, unsigned Abbrev)
A Module instance is used to store all the information related to an LLVM module. ...
Definition: Module.h:114
Constant * getClause(unsigned Idx) const
Get the value of the clause at index Idx.
unsigned getNumParams() const
getNumParams - Return the number of fixed parameters this function type requires. ...
Definition: DerivedTypes.h:136
Function is called early and/or often, so lazy binding isn't worthwhile.
Definition: Attributes.h:89
2: 32-bit floating point type
Definition: Type.h:58
iterator end()
Definition: Function.h:459
Same, but only replaced by something equivalent.
Definition: GlobalValue.h:45
static bool PushValueAndType(const Value *V, unsigned InstID, SmallVectorImpl< unsigned > &Vals, ValueEnumerator &VE)
PushValueAndType - The file has to encode both the value and type id for many values, because we need to know what type to create for forward references.
static void WriteModuleMetadata(const Module *M, const ValueEnumerator &VE, BitstreamWriter &Stream)
static unsigned getEncodedThreadLocalMode(const GlobalValue &GV)
static void writeComdats(const ValueEnumerator &VE, BitstreamWriter &Stream)
static void WriteStringRecord(unsigned Code, StringRef Str, unsigned AbbrevToUse, BitstreamWriter &Stream)
static void WriteDISubrange(const DISubrange *N, const ValueEnumerator &, BitstreamWriter &Stream, SmallVectorImpl< uint64_t > &Record, unsigned Abbrev)
DILocalScope * getScope() const
Get the local scope for this variable.
unsigned getNumOperands() const
Definition: User.h:138
Available for inspection, not emission.
Definition: GlobalValue.h:41
MDString * getRawName() const
Nested function static chain.
Definition: Attributes.h:82
unsigned getNumOperands() const
Return number of MDNode operands.
Definition: Metadata.h:942
BitCodeAbbrev - This class represents an abbreviation record.
Definition: BitCodes.h:165
uint64_t getAlignInBits() const
int64_t getCount() const
CallInst - This class represents a function call, abstracting a target machine's calling convention...
void setInstructionID(const Instruction *I)
CaseIt case_begin()
Returns a read/write iterator that points to the first case in SwitchInst.
uint64_t getValueAsInt() const
Return the attribute's value as an integer.
Definition: Attributes.cpp:126
*p = old <unsigned v ? old : v
Definition: Instructions.h:708
Like Internal, but omit from symbol table.
Definition: GlobalValue.h:48
Source said inlining was desirable.
Definition: Attributes.h:77
*p = old >unsigned v ? old : v
Definition: Instructions.h:706
Externally visible function.
Definition: GlobalValue.h:40
const unsigned char * bytes_end() const
Definition: StringRef.h:97
bool isDoubleTy() const
isDoubleTy - Return true if this is 'double', a 64-bit IEEE fp type.
Definition: Type.h:146
void Add(const BitCodeAbbrevOp &OpInfo)
Definition: BitCodes.h:179
iterator begin(unsigned Slot) const
unsigned getEmissionKind() const
The data referenced by the COMDAT must be the same size.
Definition: Comdat.h:38
12: Structures
Definition: Type.h:71
static void WriteConstants(unsigned FirstVal, unsigned LastVal, const ValueEnumerator &VE, BitstreamWriter &Stream, bool isGlobal)
Metadata node.
Definition: Metadata.h:740
F(f)
4: 80-bit floating point type (X87)
Definition: Type.h:60
DINodeArray getElements() const
Get the elements of the composite type.
unsigned getAddressSpace() const
Return the address space of the Pointer type.
Definition: DerivedTypes.h:472
1: 16-bit floating point type
Definition: Type.h:57
DIScope * getScope() const
std::vector< std::pair< const Value *, unsigned > > ValueList
14: Pointers
Definition: Type.h:73
void reserve(size_type N)
Definition: SmallVector.h:401
static void WriteDILocalVariable(const DILocalVariable *N, const ValueEnumerator &VE, BitstreamWriter &Stream, SmallVectorImpl< uint64_t > &Record, unsigned Abbrev)
11: Functions
Definition: Type.h:70
*p = old >signed v ? old : v
Definition: Instructions.h:702
const std::string & getTargetTriple() const
Get the target triple which is a string describing the target host.
Definition: Module.h:261
Naked function.
Definition: Attributes.h:81
void EmitRecord(unsigned Code, SmallVectorImpl< uintty > &Vals, unsigned Abbrev=0)
EmitRecord - Emit the specified record to the stream, using an abbrev if we have one to compress the ...
Tentative definitions.
Definition: GlobalValue.h:50
static void WriteModuleConstants(const ValueEnumerator &VE, BitstreamWriter &Stream)
Tuple of metadata.
Definition: Metadata.h:972
unsigned getColumn() const
MDString * getRawName() const
void EnterBlockInfoBlock(unsigned CodeWidth)
EnterBlockInfoBlock - Start emitting the BLOCKINFO_BLOCK.
MDString * getRawName() const
bool isCast() const
Definition: Instruction.h:118
MDString * getRawDirectory() const
void incorporateFunction(const Function &F)
incorporateFunction/purgeFunction - If you'd like to deal with a function, use these two methods to g...
element_iterator element_end() const
Definition: DerivedTypes.h:280
static void WriteDILexicalBlock(const DILexicalBlock *N, const ValueEnumerator &VE, BitstreamWriter &Stream, SmallVectorImpl< uint64_t > &Record, unsigned Abbrev)
void getMDKindNames(SmallVectorImpl< StringRef > &Result) const
Populate client supplied SmallVector with the name for custom metadata IDs registered in this LLVMCon...
Definition: Module.cpp:101
BlockAddress - The address of a basic block.
Definition: Constants.h:802
static void pushValueSigned(const Value *V, unsigned InstID, SmallVectorImpl< uint64_t > &Vals, ValueEnumerator &VE)
StringRef getKindAsString() const
Return the attribute's kind as a string.
Definition: Attributes.cpp:133
bool isPacked() const
Definition: DerivedTypes.h:242
A tuple of MDNodes.
Definition: Metadata.h:1127
unsigned getComdatID(const Comdat *C) const
DIScope * getScope() const
Type::subtype_iterator element_iterator
Definition: DerivedTypes.h:278
unsigned getTag() const
bool hasGenericDINode() const
const unsigned char * bytes_end() const
Definition: Metadata.h:538
StructType - Class to represent struct types.
Definition: DerivedTypes.h:191
MDString * getRawName() const
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
Definition: ErrorHandling.h:98
Array subrange.
unsigned getNumArgOperands() const
getNumArgOperands - Return the number of call arguments.
static void WriteAttributeGroupTable(const ValueEnumerator &VE, BitstreamWriter &Stream)
const unsigned char * bytes_begin() const
Definition: Metadata.h:537
unsigned getLine() const
const Value * getCalledValue() const
getCalledValue - Get a pointer to the function that is invoked by this instruction ...
bool isLiteral() const
isLiteral - Return true if this type is uniqued by structural equivalence, false if it is a struct de...
Definition: DerivedTypes.h:246
No attributes have been set.
Definition: Attributes.h:66
void Emit(uint32_t Val, unsigned NumBits)
The linker may choose any COMDAT.
Definition: Comdat.h:34
MDString * getRawFlags() const
DITypeArray getRetainedTypes() const
SynchronizationScope
Definition: Instructions.h:49
bool isMustTailCall() const
Function must be in a unwind table.
Definition: Attributes.h:118
element_iterator element_begin() const
Definition: DerivedTypes.h:279
static ConstantInt * ExtractElement(Constant *V, Constant *Idx)
static const unsigned MaximumAlignment
Definition: Value.h:463
uint64_t computeBitsRequiredForTypeIndicies() const
Function does not access memory.
Definition: Attributes.h:99
Hidden pointer to structure to return.
Definition: Attributes.h:114
DITypeRefArray getTypeArray() const
Function creates no aliases of pointer.
Definition: Attributes.h:85
AtomicOrdering
Definition: Instructions.h:38
unsigned getAttributeID(AttributeSet PAL) const
Subprogram description.
ConstantExpr - a constant value that is initialized with an expression using other constant values...
Definition: Constants.h:852
FunctionType - Class to represent function types.
Definition: DerivedTypes.h:96
bool hasDILocation() const
DITemplateParameterArray getTemplateParams() const
const TypeList & getTypes() const
Safe Stack protection.
Definition: Attributes.h:113
bool LLVM_ATTRIBUTE_UNUSED_RESULT empty() const
Definition: SmallVector.h:57
ConstantDataSequential - A vector or array constant whose element type is a simple 1/2/4/8-byte integ...
Definition: Constants.h:557
BinOp
This enumeration lists the possible modifications atomicrmw can make.
Definition: Instructions.h:686
unsigned getInstructionID(const Instruction *I) const
static void WriteDIObjCProperty(const DIObjCProperty *N, const ValueEnumerator &VE, BitstreamWriter &Stream, SmallVectorImpl< uint64_t > &Record, unsigned Abbrev)
unsigned getValueID(const Value *V) const
bool isHalfTy() const
isHalfTy - Return true if this is 'half', a 16-bit IEEE fp type.
Definition: Type.h:140
#define T
ArrayType - Class to represent array types.
Definition: DerivedTypes.h:336
static void WriteDIBasicType(const DIBasicType *N, const ValueEnumerator &VE, BitstreamWriter &Stream, SmallVectorImpl< uint64_t > &Record, unsigned Abbrev)
Enumeration value.
BasicBlock * getSuccessor(unsigned i) const
bool named_metadata_empty() const
Definition: Module.h:620
TypeID getTypeID() const
getTypeID - Return the type id for the type.
Definition: Type.h:134
DIScopeRef getScope() const
Pass structure by value.
Definition: Attributes.h:73
unsigned getNumClauses() const
getNumClauses - Get the number of clauses for this landing pad.
ArchType getArch() const
getArch - Get the parsed architecture type of this triple.
Definition: Triple.h:242
DITypeRef getVTableHolder() const
void getFunctionConstantRange(unsigned &Start, unsigned &End) const
getFunctionConstantRange - Return the range of values that corresponds to function-local constants...
Value wrapper in the Metadata hierarchy.
Definition: Metadata.h:252
iterator end()
Get an iterator to the end of the symbol table.
MDString * getRawName() const
unsigned getNumElements() const
Return the number of elements in the Vector type.
Definition: DerivedTypes.h:432
element_iterator elements_begin() const
Debug location.
Structure to hold a use-list order.
Definition: UseListOrder.h:29
iterator begin()
Definition: Function.h:457
Stack protection.
Definition: Attributes.h:110
ValueSymbolTable & getValueSymbolTable()
getSymbolTable() - Return the symbol table...
Definition: Function.h:450
DIScopeRef getScope() const
void EnterSubblock(unsigned BlockID, unsigned CodeLen)
bool isPPC_FP128Ty() const
isPPC_FP128Ty - Return true if this is powerpc long double.
Definition: Type.h:155
Type * getElementType() const
Definition: DerivedTypes.h:323
size_t size() const
size - Get the array size.
Definition: ArrayRef.h:134
Considered to not alias after call.
Definition: Attributes.h:83
unsigned getLine() const
BasicBlock * getNormalDest() const
PointerType - Class to represent pointers.
Definition: DerivedTypes.h:449
DIScope * getScope() const
DIFile * getFile() const
unsigned getNumIncomingValues() const
getNumIncomingValues - Return the number of incoming edges
iterator begin() const
Definition: StringRef.h:90
static unsigned getEncodedLinkage(const GlobalValue &GV)
10: Arbitrary bit width integers
Definition: Type.h:69
MDString * getRawName() const
unsigned getRuntimeVersion() const
unsigned getLine() const
static void WriteDISubroutineType(const DISubroutineType *N, const ValueEnumerator &VE, BitstreamWriter &Stream, SmallVectorImpl< uint64_t > &Record, unsigned Abbrev)
ExternalWeak linkage description.
Definition: GlobalValue.h:49
const ValueList & getValues() const
bool shouldPreserveUseListOrder() const
0: type with no size
Definition: Type.h:56
#define P(N)
Same, but only replaced by something equivalent.
Definition: GlobalValue.h:43
const std::vector< AttributeSet > & getAttributes() const
unsigned getNumSlots() const
Return the number of slots used in this attribute list.
Type * getParamType(unsigned i) const
Parameter type accessors.
Definition: DerivedTypes.h:131
MDString * getRawSplitDebugFilename() const
DITypeRef getType() const
element_iterator elements_end() const
No other Module may specify this COMDAT.
Definition: Comdat.h:37
unsigned getTypeID(Type *T) const
MDString * getRawFilename() const
LandingPadInst - The landingpad instruction holds all of the information necessary to generate correc...
unsigned EmitAbbrev(BitCodeAbbrev *Abbv)
EmitAbbrev - This emits an abbreviation to the stream.
static void WriteDILocation(const DILocation *N, const ValueEnumerator &VE, BitstreamWriter &Stream, SmallVectorImpl< uint64_t > &Record, unsigned Abbrev)
The instances of the Type class are immutable: once they are created, they are never changed...
Definition: Type.h:45
static uint64_t getAttrKindEncoding(Attribute::AttrKind Kind)
BranchInst - Conditional or Unconditional Branch instruction.
AttributeSet getSlotAttributes(unsigned Slot) const
Return the attributes at the given slot.
This is an important base class in LLVM.
Definition: Constant.h:41
void WriteBitcodeToFile(const Module *M, raw_ostream &Out, bool ShouldPreserveUseListOrder=false)
Write the specified module to the specified raw output stream.
DIFile * getFile() const
This file contains the declarations for the subclasses of Constant, which represent the different fla...
bool isFloatTy() const
isFloatTy - Return true if this is 'float', a 32-bit IEEE fp type.
Definition: Type.h:143
APInt Or(const APInt &LHS, const APInt &RHS)
Bitwise OR function for APInt.
Definition: APInt.h:1895
static unsigned getEncodedDLLStorageClass(const GlobalValue &GV)
BitCodeAbbrevOp - This describes one or more operands in an abbreviation.
Definition: BitCodes.h:87
unsigned getAlignment() const
getAlignment - Return the alignment of the memory that is being allocated by the instruction.
Definition: Instructions.h:130
ConstantFP - Floating Point Values [float, double].
Definition: Constants.h:233
APInt Xor(const APInt &LHS, const APInt &RHS)
Bitwise XOR function for APInt.
Definition: APInt.h:1900
unsigned getLine() const
static void WriteMetadataAttachment(const Function &F, const ValueEnumerator &VE, BitstreamWriter &Stream)
unsigned getSourceLanguage() const
Return value is always equal to this argument.
Definition: Attributes.h:103
iterator_range< named_metadata_iterator > named_metadata()
Definition: Module.h:622
bool hasMetadata() const
Check if this has any metadata.
Definition: Function.h:571
unsigned getAttributeGroupID(AttributeSet PAL) const
static void WriteBlockInfo(const ValueEnumerator &VE, BitstreamWriter &Stream)
unsigned EmitBlockInfoAbbrev(unsigned BlockID, BitCodeAbbrev *Abbv)
EmitBlockInfoAbbrev - Emit a DEFINE_ABBREV record for the specified BlockID.
Pass structure in an alloca.
Definition: Attributes.h:74
static void WriteDIFile(const DIFile *N, const ValueEnumerator &VE, BitstreamWriter &Stream, SmallVectorImpl< uint64_t > &Record, unsigned Abbrev)
BasicBlock * getIncomingBlock(unsigned i) const
getIncomingBlock - Return incoming basic block number i.
bool isUsedWithInAlloca() const
Return true if this alloca is used as an inalloca argument to a call.
Definition: Instructions.h:143
uint64_t getNumElements() const
Definition: DerivedTypes.h:352
6: 128-bit floating point type (two 64-bits, PowerPC)
Definition: Type.h:62
Value * getOperand(unsigned i) const
Definition: User.h:118
Zero extended before/after call.
Definition: Attributes.h:119
op_range operands()
Definition: User.h:191
static void EmitDarwinBCHeaderAndTrailer(SmallVectorImpl< char > &Buffer, const Triple &TT)
static void WriteDIDerivedType(const DIDerivedType *N, const ValueEnumerator &VE, BitstreamWriter &Stream, SmallVectorImpl< uint64_t > &Record, unsigned Abbrev)
unsigned getDWOId() const
unsigned getEncoding() const
SelectionKind getSelectionKind() const
Definition: Comdat.h:42
unsigned getArg() const
Function doesn't unwind stack.
Definition: Attributes.h:96
uint64_t getOffsetInBits() const
DITypeRef getBaseType() const
void write32le(void *p, uint32_t v)
Definition: Endian.h:219
The data referenced by the COMDAT must be the same.
Definition: Comdat.h:35
unsigned getAttributes() const
bool isEnumAttribute() const
Return true if the attribute is an Attribute::AttrKind type.
Definition: Attributes.cpp:107
Marks function as being in a cold path.
Definition: Attributes.h:75
Sentinal value useful for loops.
Definition: Attributes.h:121
static void WriteGenericDINode(const GenericDINode *N, const ValueEnumerator &VE, BitstreamWriter &Stream, SmallVectorImpl< uint64_t > &Record, unsigned Abbrev)
Mark the function as not returning.
Definition: Attributes.h:95
static unsigned getEncodedComdatSelectionKind(const Comdat &C)
uint64_t getElementAsInteger(unsigned i) const
getElementAsInteger - If this is a sequential container of integers (of any size), return the specified element in the low bits of a uint64_t.
Definition: Constants.cpp:2723
DINodeRef getEntity() const
void append(in_iter in_start, in_iter in_end)
Add the specified range to the end of the SmallVector.
Definition: SmallVector.h:416
bool isFP128Ty() const
isFP128Ty - Return true if this is 'fp128'.
Definition: Type.h:152
FunctionType * getFunctionType() const
static bool isAtomic(Instruction *I)
static uint64_t rotateSign(int64_t I)
static unsigned GetEncodedRMWOperation(AtomicRMWInst::BinOp Op)
Call cannot be duplicated.
Definition: Attributes.h:86
bool isCString() const
isCString - This method returns true if the array "isString", ends with a nul byte, and does not contains any other nul bytes.
Definition: Constants.cpp:2798
Triple - Helper class for working with autoconf configuration names.
Definition: Triple.h:44
DITypeRef getType() const
Pointer is known to be not null.
Definition: Attributes.h:91
FunctionType * getFunctionType() const
An imported module (C++ using directive or similar).
raw_ostream & write(unsigned char C)
CallingConv::ID getCallingConv() const
getCallingConv/setCallingConv - Get or set the calling convention of this function call...
static void WriteModuleInfo(const Module *M, const ValueEnumerator &VE, BitstreamWriter &Stream)
void dump() const
Support for debugging, callable in GDB: V->dump()
Definition: AsmWriter.cpp:3353
const std::vector< const Metadata * > & getMDs() const
const std::string & getModuleInlineAsm() const
Get any module-scope inline assembly blocks.
Definition: Module.h:269
bool isConditional() const
ArrayRef< uint64_t > getElements() const
13: Arrays
Definition: Type.h:72
DIImportedEntityArray getImportedEntities() const
static void WriteInstruction(const Instruction &I, unsigned InstID, ValueEnumerator &VE, BitstreamWriter &Stream, SmallVectorImpl< unsigned > &Vals)
WriteInstruction - Emit an instruction to the specified stream.
const MDOperand & getOperand(unsigned I) const
Definition: Metadata.h:936
static void emitSignedInt64(SmallVectorImpl< uint64_t > &Vals, uint64_t V)
BasicBlock * getUnwindDest() const
unsigned getTag() const
This is the shared class of boolean and integer constants.
Definition: Constants.h:47
static void WriteDIEnumerator(const DIEnumerator *N, const ValueEnumerator &VE, BitstreamWriter &Stream, SmallVectorImpl< uint64_t > &Record, unsigned Abbrev)
Value * getIncomingValue(unsigned i) const
getIncomingValue - Return incoming value number x
15: SIMD 'packed' format, or other vector type
Definition: Type.h:74
static void WriteModule(const Module *M, BitstreamWriter &Stream, bool ShouldPreserveUseListOrder)
WriteModule - Emit the specified module to the bitstream.
static void WriteDIModule(const DIModule *N, const ValueEnumerator &VE, BitstreamWriter &Stream, SmallVectorImpl< uint64_t > &Record, unsigned Abbrev)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small...
Definition: SmallVector.h:861
Keep one copy of function when linking (inline)
Definition: GlobalValue.h:42
Module.h This file contains the declarations for the Module class.
Type * getType() const
All values are typed, get the type of this value.
Definition: Value.h:222
const SmallVectorImpl< const LocalAsMetadata * > & getFunctionLocalMDs() const
Callee is recognized as a builtin, despite nobuiltin attribute on its declaration.
Definition: Attributes.h:71
Attribute::AttrKind getKindAsEnum() const
Return the attribute's kind as an enum (Attribute::AttrKind).
Definition: Attributes.cpp:119
AddressSpace
Definition: NVPTXBaseInfo.h:22
iterator end(unsigned Slot) const
void getAllMetadata(SmallVectorImpl< std::pair< unsigned, MDNode * >> &MDs) const
Get all current metadata attachments.
Definition: Metadata.cpp:1216
MDString * getRawLinkageName() const
static void WriteTypeTable(const ValueEnumerator &VE, BitstreamWriter &Stream)
WriteTypeTable - Write out the type table for a module.
const std::vector< AttributeSet > & getAttributeGroups() const
bool isIntAttribute() const
Return true if the attribute is an integer attribute.
Definition: Attributes.cpp:111
static void WriteMDTuple(const MDTuple *N, const ValueEnumerator &VE, BitstreamWriter &Stream, SmallVectorImpl< uint64_t > &Record, unsigned Abbrev)
static unsigned GetEncodedOrdering(AtomicOrdering Ordering)
int64_t getValue() const
const char * getKeyData() const
getKeyData - Return the start of the string data that is the key for this value.
Definition: StringMap.h:136
The linker will choose the largest COMDAT.
Definition: Comdat.h:36
const std::vector< const BasicBlock * > & getBasicBlocks() const
bool isNullValue() const
isNullValue - Return true if this is the value that would be returned by getNullValue.
Definition: Constants.cpp:75
DWARF expression.
8: Metadata
Definition: Type.h:64
unsigned Log2_32(uint32_t Value)
Log2_32 - This function returns the floor log base 2 of the specified value, -1 if the value is zero...
Definition: MathExtras.h:468
Alignment of parameter (5 bits) stored as log2 of alignment with +1 bias 0 means unaligned (different...
Definition: Attributes.h:67
static void pushValue(const Value *V, unsigned InstID, SmallVectorImpl< unsigned > &Vals, ValueEnumerator &VE)
pushValue - Like PushValueAndType, but where the type of the value is omitted (perhaps it was already...
Value * getArgOperand(unsigned i) const
getArgOperand/setArgOperand - Return/set the i-th call argument.
VectorType - Class to represent vector types.
Definition: DerivedTypes.h:362
static void WriteDICompositeType(const DICompositeType *N, const ValueEnumerator &VE, BitstreamWriter &Stream, SmallVectorImpl< uint64_t > &Record, unsigned Abbrev)
Class for arbitrary precision integers.
Definition: APInt.h:73
unsigned getDiscriminator() const
unsigned getMetadataID(const Metadata *MD) const
static bool isWeak(const MCSymbolELF &Sym)
A (clang) module that has been imported by the compile unit.
Function must not be optimized.
Definition: Attributes.h:98
StringRef getName() const
getName - Return the name for this struct type if it has an identity.
Definition: Type.cpp:583
Function only reads from memory.
Definition: Attributes.h:100
UseListOrderStack UseListOrders
MDString * getRawIdentifier() const
Generic tagged DWARF-like metadata node.
Value * getCondition() const
iterator insert(iterator I, T &&Elt)
Definition: SmallVector.h:481
const AttributeSet & getAttributes() const
getAttributes - Return the parameter attributes for this call.
static void WriteUseListBlock(const Function *F, ValueEnumerator &VE, BitstreamWriter &Stream)
APInt And(const APInt &LHS, const APInt &RHS)
Bitwise AND function for APInt.
Definition: APInt.h:1890
unsigned getMetadataOrNullID(const Metadata *MD) const
Metadata * getRawVariable() const
Disable redzone.
Definition: Attributes.h:94
ThreadLocalMode getThreadLocalMode() const
Definition: GlobalValue.h:160
bool isDistinct() const
Definition: Metadata.h:818
static void WriteDIImportedEntity(const DIImportedEntity *N, const ValueEnumerator &VE, BitstreamWriter &Stream, SmallVectorImpl< uint64_t > &Record, unsigned Abbrev)
Type array for a subprogram.
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Definition: Metadata.h:1030
ThreadSanitizer is on.
Definition: Attributes.h:116
unsigned getRuntimeLang() const
static void WriteUseList(ValueEnumerator &VE, UseListOrder &&Order, BitstreamWriter &Stream)
Function to be accessible from DLL.
Definition: GlobalValue.h:64
static void WriteDIGlobalVariable(const DIGlobalVariable *N, const ValueEnumerator &VE, BitstreamWriter &Stream, SmallVectorImpl< uint64_t > &Record, unsigned Abbrev)
Value * getCondition() const
const AttributeSet & getAttributes() const
getAttributes - Return the parameter attributes for this invoke.
bool isX86_FP80Ty() const
isX86_FP80Ty - Return true if this is x86 long double.
Definition: Type.h:149
ValID - Represents a reference of a definition of some sort with no type.
Definition: LLParser.h:47
BasicBlock * getDefaultDest() const
static unsigned GetEncodedBinaryOpcode(unsigned Opcode)
static void WriteDITemplateValueParameter(const DITemplateValueParameter *N, const ValueEnumerator &VE, BitstreamWriter &Stream, SmallVectorImpl< uint64_t > &Record, unsigned Abbrev)
static void WriteDINamespace(const DINamespace *N, const ValueEnumerator &VE, BitstreamWriter &Stream, SmallVectorImpl< uint64_t > &Record, unsigned Abbrev)
iterator end()
Definition: Module.h:571
const uint64_t * getRawData() const
This function returns a pointer to the internal storage of the APInt.
Definition: APInt.h:573
unsigned getSlotIndex(unsigned Slot) const
Return the index for the given slot.
Value * getValue() const
Definition: Metadata.h:287
Callee isn't recognized as a builtin.
Definition: Attributes.h:84
bool isCatch(unsigned Idx) const
isCatch - Return 'true' if the clause and index Idx is a catch clause.
AddressSanitizer is on.
Definition: Attributes.h:115
#define I(x, y, z)
Definition: MD5.cpp:54
#define N
Strong Stack protection.
Definition: Attributes.h:112
bool empty() const
Determine if the symbol table is empty.
unsigned getKeyLength() const
Definition: StringMap.h:36
unsigned getNumElements() const
getNumElements - Return the number of elements in the array or vector.
Definition: Constants.cpp:2449
iterator begin()
Definition: Module.h:569
bool isTailCall() const
uint64_t getSizeInBits() const
Keep one copy of named function when linking (weak)
Definition: GlobalValue.h:44
Rename collisions when linking (static functions).
Definition: GlobalValue.h:47
op_range operands() const
Definition: Metadata.h:934
static bool isChar6(char C)
isChar6 - Return true if this character is legal in the Char6 encoding.
Definition: BitCodes.h:132
static void WriteValueSymbolTable(const ValueSymbolTable &VST, const ValueEnumerator &VE, BitstreamWriter &Stream)
static void WriteDITemplateTypeParameter(const DITemplateTypeParameter *N, const ValueEnumerator &VE, BitstreamWriter &Stream, SmallVectorImpl< uint64_t > &Record, unsigned Abbrev)
Function to be imported from DLL.
Definition: GlobalValue.h:63
Funciton can access memory only using pointers based on its arguments.
Definition: Attributes.h:101
bool isVarArg() const
Definition: DerivedTypes.h:120
3: 64-bit floating point type
Definition: Type.h:59
SwitchInst - Multiway switch.
StringRef getValueAsString() const
Return the attribute's value as a string.
Definition: Attributes.cpp:140
Type * getReturnType() const
Definition: DerivedTypes.h:121
Function can return twice.
Definition: Attributes.h:104
unsigned getFlags() const
unsigned getGlobalBasicBlockID(const BasicBlock *BB) const
getGlobalBasicBlockID - This returns the function-specific ID for the specified basic block...
const ARM::ArchExtKind Kind
MDString * getRawName() const
const unsigned char * bytes_begin() const
Definition: StringRef.h:94
DICompositeTypeArray getEnumTypes() const
Pointer is known to be dereferenceable.
Definition: Attributes.h:92
LLVM Value Representation.
Definition: Value.h:69
DIDerivedType * getStaticDataMemberDeclaration() const
unsigned getOpcode() const
getOpcode() returns a member of one of the enums like Instruction::Add.
Definition: Instruction.h:112
unsigned getLine() const
unsigned getLine() const
Disable implicit floating point insts.
Definition: Attributes.h:87
static void WriteDILexicalBlockFile(const DILexicalBlockFile *N, const ValueEnumerator &VE, BitstreamWriter &Stream, SmallVectorImpl< uint64_t > &Record, unsigned Abbrev)
DLLStorageClassTypes getDLLStorageClass() const
Definition: GlobalValue.h:164
bool isUInt< 16 >(uint64_t x)
Definition: MathExtras.h:298
iterator end() const
Definition: StringRef.h:92
This class implements an extremely fast bulk output stream that can only output to a stream...
Definition: raw_ostream.h:38
InvokeInst - Invoke instruction.
std::vector< Type * > TypeList
bool isCleanup() const
isCleanup - Return 'true' if this landingpad instruction is a cleanup.
iterator_range< global_iterator > globals()
Definition: Module.h:558
DIFile * getFile() const
C - The default llvm calling convention, compatible with C.
Definition: CallingConv.h:34
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:40
A single uniqued string.
Definition: Metadata.h:508
CallingConv::ID getCallingConv() const
getCallingConv/setCallingConv - Get or set the calling convention of this function call...
const std::string & getDataLayoutStr() const
Get the data layout string for the module's target platform.
Definition: Module.h:252
int64_t getLowerBound() const
MDString * getRawSetterName() const
static void WriteInt32ToBuffer(uint32_t Value, SmallVectorImpl< char > &Buffer, uint32_t &Position)
static bool isVolatile(Instruction *Inst)
unsigned getFlags() const
9: MMX vectors (64 bits, X86 specific)
Definition: Type.h:65
DIGlobalVariableArray getGlobalVariables() const
Type * getAllocatedType() const
getAllocatedType - Return the type that is being allocated by the instruction.
Definition: Instructions.h:122
Can only be moved to control-equivalent blocks.
Definition: Attributes.h:76
Stack protection required.
Definition: Attributes.h:111
Root of the metadata hierarchy.
Definition: Metadata.h:45
MemorySanitizer is on.
Definition: Attributes.h:117
Build jump-instruction tables and replace refs.
Definition: Attributes.h:79
Pointer is either null or dereferenceable.
Definition: Attributes.h:93
static unsigned GetEncodedCastOpcode(unsigned Opcode)
MDString * getRawProducer() const
AllocaInst - an instruction to allocate memory on the stack.
Definition: Instructions.h:76
InsertValueInst - This instruction inserts a struct field of array element value into an aggregate va...
MDTuple * get() const
static void WriteModuleMetadataStore(const Module *M, BitstreamWriter &Stream)
AttrKind
This enumeration lists the attributes that can be associated with parameters, function results...
Definition: Attributes.h:64
bool empty() const
empty - Check if the string is empty.
Definition: StringRef.h:110
5: 128-bit floating point type (112-bit mantissa)
Definition: Type.h:61
Basic type, like 'int' or 'float'.
static unsigned getEncodedVisibility(const GlobalValue &GV)
static void WriteValueAsMetadata(const ValueAsMetadata *MD, const ValueEnumerator &VE, BitstreamWriter &Stream, SmallVectorImpl< uint64_t > &Record)
static void WriteFunctionLocalMetadata(const Function &F, const ValueEnumerator &VE, BitstreamWriter &Stream)
Function must be optimized for size first.
Definition: Attributes.h:80