LLVM API Documentation

BitcodeWriter.cpp
Go to the documentation of this file.
00001 //===--- Bitcode/Writer/BitcodeWriter.cpp - Bitcode Writer ----------------===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // Bitcode writer implementation.
00011 //
00012 //===----------------------------------------------------------------------===//
00013 
00014 #include "llvm/Bitcode/ReaderWriter.h"
00015 #include "ValueEnumerator.h"
00016 #include "llvm/ADT/Triple.h"
00017 #include "llvm/Bitcode/BitstreamWriter.h"
00018 #include "llvm/Bitcode/LLVMBitCodes.h"
00019 #include "llvm/IR/Constants.h"
00020 #include "llvm/IR/DerivedTypes.h"
00021 #include "llvm/IR/InlineAsm.h"
00022 #include "llvm/IR/Instructions.h"
00023 #include "llvm/IR/Module.h"
00024 #include "llvm/IR/Operator.h"
00025 #include "llvm/IR/UseListOrder.h"
00026 #include "llvm/IR/ValueSymbolTable.h"
00027 #include "llvm/Support/CommandLine.h"
00028 #include "llvm/Support/ErrorHandling.h"
00029 #include "llvm/Support/MathExtras.h"
00030 #include "llvm/Support/Program.h"
00031 #include "llvm/Support/raw_ostream.h"
00032 #include <cctype>
00033 #include <map>
00034 using namespace llvm;
00035 
00036 /// These are manifest constants used by the bitcode writer. They do not need to
00037 /// be kept in sync with the reader, but need to be consistent within this file.
00038 enum {
00039   // VALUE_SYMTAB_BLOCK abbrev id's.
00040   VST_ENTRY_8_ABBREV = bitc::FIRST_APPLICATION_ABBREV,
00041   VST_ENTRY_7_ABBREV,
00042   VST_ENTRY_6_ABBREV,
00043   VST_BBENTRY_6_ABBREV,
00044 
00045   // CONSTANTS_BLOCK abbrev id's.
00046   CONSTANTS_SETTYPE_ABBREV = bitc::FIRST_APPLICATION_ABBREV,
00047   CONSTANTS_INTEGER_ABBREV,
00048   CONSTANTS_CE_CAST_Abbrev,
00049   CONSTANTS_NULL_Abbrev,
00050 
00051   // FUNCTION_BLOCK abbrev id's.
00052   FUNCTION_INST_LOAD_ABBREV = bitc::FIRST_APPLICATION_ABBREV,
00053   FUNCTION_INST_BINOP_ABBREV,
00054   FUNCTION_INST_BINOP_FLAGS_ABBREV,
00055   FUNCTION_INST_CAST_ABBREV,
00056   FUNCTION_INST_RET_VOID_ABBREV,
00057   FUNCTION_INST_RET_VAL_ABBREV,
00058   FUNCTION_INST_UNREACHABLE_ABBREV
00059 };
00060 
00061 static unsigned GetEncodedCastOpcode(unsigned Opcode) {
00062   switch (Opcode) {
00063   default: llvm_unreachable("Unknown cast instruction!");
00064   case Instruction::Trunc   : return bitc::CAST_TRUNC;
00065   case Instruction::ZExt    : return bitc::CAST_ZEXT;
00066   case Instruction::SExt    : return bitc::CAST_SEXT;
00067   case Instruction::FPToUI  : return bitc::CAST_FPTOUI;
00068   case Instruction::FPToSI  : return bitc::CAST_FPTOSI;
00069   case Instruction::UIToFP  : return bitc::CAST_UITOFP;
00070   case Instruction::SIToFP  : return bitc::CAST_SITOFP;
00071   case Instruction::FPTrunc : return bitc::CAST_FPTRUNC;
00072   case Instruction::FPExt   : return bitc::CAST_FPEXT;
00073   case Instruction::PtrToInt: return bitc::CAST_PTRTOINT;
00074   case Instruction::IntToPtr: return bitc::CAST_INTTOPTR;
00075   case Instruction::BitCast : return bitc::CAST_BITCAST;
00076   case Instruction::AddrSpaceCast: return bitc::CAST_ADDRSPACECAST;
00077   }
00078 }
00079 
00080 static unsigned GetEncodedBinaryOpcode(unsigned Opcode) {
00081   switch (Opcode) {
00082   default: llvm_unreachable("Unknown binary instruction!");
00083   case Instruction::Add:
00084   case Instruction::FAdd: return bitc::BINOP_ADD;
00085   case Instruction::Sub:
00086   case Instruction::FSub: return bitc::BINOP_SUB;
00087   case Instruction::Mul:
00088   case Instruction::FMul: return bitc::BINOP_MUL;
00089   case Instruction::UDiv: return bitc::BINOP_UDIV;
00090   case Instruction::FDiv:
00091   case Instruction::SDiv: return bitc::BINOP_SDIV;
00092   case Instruction::URem: return bitc::BINOP_UREM;
00093   case Instruction::FRem:
00094   case Instruction::SRem: return bitc::BINOP_SREM;
00095   case Instruction::Shl:  return bitc::BINOP_SHL;
00096   case Instruction::LShr: return bitc::BINOP_LSHR;
00097   case Instruction::AShr: return bitc::BINOP_ASHR;
00098   case Instruction::And:  return bitc::BINOP_AND;
00099   case Instruction::Or:   return bitc::BINOP_OR;
00100   case Instruction::Xor:  return bitc::BINOP_XOR;
00101   }
00102 }
00103 
00104 static unsigned GetEncodedRMWOperation(AtomicRMWInst::BinOp Op) {
00105   switch (Op) {
00106   default: llvm_unreachable("Unknown RMW operation!");
00107   case AtomicRMWInst::Xchg: return bitc::RMW_XCHG;
00108   case AtomicRMWInst::Add: return bitc::RMW_ADD;
00109   case AtomicRMWInst::Sub: return bitc::RMW_SUB;
00110   case AtomicRMWInst::And: return bitc::RMW_AND;
00111   case AtomicRMWInst::Nand: return bitc::RMW_NAND;
00112   case AtomicRMWInst::Or: return bitc::RMW_OR;
00113   case AtomicRMWInst::Xor: return bitc::RMW_XOR;
00114   case AtomicRMWInst::Max: return bitc::RMW_MAX;
00115   case AtomicRMWInst::Min: return bitc::RMW_MIN;
00116   case AtomicRMWInst::UMax: return bitc::RMW_UMAX;
00117   case AtomicRMWInst::UMin: return bitc::RMW_UMIN;
00118   }
00119 }
00120 
00121 static unsigned GetEncodedOrdering(AtomicOrdering Ordering) {
00122   switch (Ordering) {
00123   case NotAtomic: return bitc::ORDERING_NOTATOMIC;
00124   case Unordered: return bitc::ORDERING_UNORDERED;
00125   case Monotonic: return bitc::ORDERING_MONOTONIC;
00126   case Acquire: return bitc::ORDERING_ACQUIRE;
00127   case Release: return bitc::ORDERING_RELEASE;
00128   case AcquireRelease: return bitc::ORDERING_ACQREL;
00129   case SequentiallyConsistent: return bitc::ORDERING_SEQCST;
00130   }
00131   llvm_unreachable("Invalid ordering");
00132 }
00133 
00134 static unsigned GetEncodedSynchScope(SynchronizationScope SynchScope) {
00135   switch (SynchScope) {
00136   case SingleThread: return bitc::SYNCHSCOPE_SINGLETHREAD;
00137   case CrossThread: return bitc::SYNCHSCOPE_CROSSTHREAD;
00138   }
00139   llvm_unreachable("Invalid synch scope");
00140 }
00141 
00142 static void WriteStringRecord(unsigned Code, StringRef Str,
00143                               unsigned AbbrevToUse, BitstreamWriter &Stream) {
00144   SmallVector<unsigned, 64> Vals;
00145 
00146   // Code: [strchar x N]
00147   for (unsigned i = 0, e = Str.size(); i != e; ++i) {
00148     if (AbbrevToUse && !BitCodeAbbrevOp::isChar6(Str[i]))
00149       AbbrevToUse = 0;
00150     Vals.push_back(Str[i]);
00151   }
00152 
00153   // Emit the finished record.
00154   Stream.EmitRecord(Code, Vals, AbbrevToUse);
00155 }
00156 
00157 static uint64_t getAttrKindEncoding(Attribute::AttrKind Kind) {
00158   switch (Kind) {
00159   case Attribute::Alignment:
00160     return bitc::ATTR_KIND_ALIGNMENT;
00161   case Attribute::AlwaysInline:
00162     return bitc::ATTR_KIND_ALWAYS_INLINE;
00163   case Attribute::Builtin:
00164     return bitc::ATTR_KIND_BUILTIN;
00165   case Attribute::ByVal:
00166     return bitc::ATTR_KIND_BY_VAL;
00167   case Attribute::InAlloca:
00168     return bitc::ATTR_KIND_IN_ALLOCA;
00169   case Attribute::Cold:
00170     return bitc::ATTR_KIND_COLD;
00171   case Attribute::InlineHint:
00172     return bitc::ATTR_KIND_INLINE_HINT;
00173   case Attribute::InReg:
00174     return bitc::ATTR_KIND_IN_REG;
00175   case Attribute::JumpTable:
00176     return bitc::ATTR_KIND_JUMP_TABLE;
00177   case Attribute::MinSize:
00178     return bitc::ATTR_KIND_MIN_SIZE;
00179   case Attribute::Naked:
00180     return bitc::ATTR_KIND_NAKED;
00181   case Attribute::Nest:
00182     return bitc::ATTR_KIND_NEST;
00183   case Attribute::NoAlias:
00184     return bitc::ATTR_KIND_NO_ALIAS;
00185   case Attribute::NoBuiltin:
00186     return bitc::ATTR_KIND_NO_BUILTIN;
00187   case Attribute::NoCapture:
00188     return bitc::ATTR_KIND_NO_CAPTURE;
00189   case Attribute::NoDuplicate:
00190     return bitc::ATTR_KIND_NO_DUPLICATE;
00191   case Attribute::NoImplicitFloat:
00192     return bitc::ATTR_KIND_NO_IMPLICIT_FLOAT;
00193   case Attribute::NoInline:
00194     return bitc::ATTR_KIND_NO_INLINE;
00195   case Attribute::NonLazyBind:
00196     return bitc::ATTR_KIND_NON_LAZY_BIND;
00197   case Attribute::NonNull:
00198     return bitc::ATTR_KIND_NON_NULL;
00199   case Attribute::Dereferenceable:
00200     return bitc::ATTR_KIND_DEREFERENCEABLE;
00201   case Attribute::NoRedZone:
00202     return bitc::ATTR_KIND_NO_RED_ZONE;
00203   case Attribute::NoReturn:
00204     return bitc::ATTR_KIND_NO_RETURN;
00205   case Attribute::NoUnwind:
00206     return bitc::ATTR_KIND_NO_UNWIND;
00207   case Attribute::OptimizeForSize:
00208     return bitc::ATTR_KIND_OPTIMIZE_FOR_SIZE;
00209   case Attribute::OptimizeNone:
00210     return bitc::ATTR_KIND_OPTIMIZE_NONE;
00211   case Attribute::ReadNone:
00212     return bitc::ATTR_KIND_READ_NONE;
00213   case Attribute::ReadOnly:
00214     return bitc::ATTR_KIND_READ_ONLY;
00215   case Attribute::Returned:
00216     return bitc::ATTR_KIND_RETURNED;
00217   case Attribute::ReturnsTwice:
00218     return bitc::ATTR_KIND_RETURNS_TWICE;
00219   case Attribute::SExt:
00220     return bitc::ATTR_KIND_S_EXT;
00221   case Attribute::StackAlignment:
00222     return bitc::ATTR_KIND_STACK_ALIGNMENT;
00223   case Attribute::StackProtect:
00224     return bitc::ATTR_KIND_STACK_PROTECT;
00225   case Attribute::StackProtectReq:
00226     return bitc::ATTR_KIND_STACK_PROTECT_REQ;
00227   case Attribute::StackProtectStrong:
00228     return bitc::ATTR_KIND_STACK_PROTECT_STRONG;
00229   case Attribute::StructRet:
00230     return bitc::ATTR_KIND_STRUCT_RET;
00231   case Attribute::SanitizeAddress:
00232     return bitc::ATTR_KIND_SANITIZE_ADDRESS;
00233   case Attribute::SanitizeThread:
00234     return bitc::ATTR_KIND_SANITIZE_THREAD;
00235   case Attribute::SanitizeMemory:
00236     return bitc::ATTR_KIND_SANITIZE_MEMORY;
00237   case Attribute::UWTable:
00238     return bitc::ATTR_KIND_UW_TABLE;
00239   case Attribute::ZExt:
00240     return bitc::ATTR_KIND_Z_EXT;
00241   case Attribute::EndAttrKinds:
00242     llvm_unreachable("Can not encode end-attribute kinds marker.");
00243   case Attribute::None:
00244     llvm_unreachable("Can not encode none-attribute.");
00245   }
00246 
00247   llvm_unreachable("Trying to encode unknown attribute");
00248 }
00249 
00250 static void WriteAttributeGroupTable(const ValueEnumerator &VE,
00251                                      BitstreamWriter &Stream) {
00252   const std::vector<AttributeSet> &AttrGrps = VE.getAttributeGroups();
00253   if (AttrGrps.empty()) return;
00254 
00255   Stream.EnterSubblock(bitc::PARAMATTR_GROUP_BLOCK_ID, 3);
00256 
00257   SmallVector<uint64_t, 64> Record;
00258   for (unsigned i = 0, e = AttrGrps.size(); i != e; ++i) {
00259     AttributeSet AS = AttrGrps[i];
00260     for (unsigned i = 0, e = AS.getNumSlots(); i != e; ++i) {
00261       AttributeSet A = AS.getSlotAttributes(i);
00262 
00263       Record.push_back(VE.getAttributeGroupID(A));
00264       Record.push_back(AS.getSlotIndex(i));
00265 
00266       for (AttributeSet::iterator I = AS.begin(0), E = AS.end(0);
00267            I != E; ++I) {
00268         Attribute Attr = *I;
00269         if (Attr.isEnumAttribute()) {
00270           Record.push_back(0);
00271           Record.push_back(getAttrKindEncoding(Attr.getKindAsEnum()));
00272         } else if (Attr.isIntAttribute()) {
00273           Record.push_back(1);
00274           Record.push_back(getAttrKindEncoding(Attr.getKindAsEnum()));
00275           Record.push_back(Attr.getValueAsInt());
00276         } else {
00277           StringRef Kind = Attr.getKindAsString();
00278           StringRef Val = Attr.getValueAsString();
00279 
00280           Record.push_back(Val.empty() ? 3 : 4);
00281           Record.append(Kind.begin(), Kind.end());
00282           Record.push_back(0);
00283           if (!Val.empty()) {
00284             Record.append(Val.begin(), Val.end());
00285             Record.push_back(0);
00286           }
00287         }
00288       }
00289 
00290       Stream.EmitRecord(bitc::PARAMATTR_GRP_CODE_ENTRY, Record);
00291       Record.clear();
00292     }
00293   }
00294 
00295   Stream.ExitBlock();
00296 }
00297 
00298 static void WriteAttributeTable(const ValueEnumerator &VE,
00299                                 BitstreamWriter &Stream) {
00300   const std::vector<AttributeSet> &Attrs = VE.getAttributes();
00301   if (Attrs.empty()) return;
00302 
00303   Stream.EnterSubblock(bitc::PARAMATTR_BLOCK_ID, 3);
00304 
00305   SmallVector<uint64_t, 64> Record;
00306   for (unsigned i = 0, e = Attrs.size(); i != e; ++i) {
00307     const AttributeSet &A = Attrs[i];
00308     for (unsigned i = 0, e = A.getNumSlots(); i != e; ++i)
00309       Record.push_back(VE.getAttributeGroupID(A.getSlotAttributes(i)));
00310 
00311     Stream.EmitRecord(bitc::PARAMATTR_CODE_ENTRY, Record);
00312     Record.clear();
00313   }
00314 
00315   Stream.ExitBlock();
00316 }
00317 
00318 /// WriteTypeTable - Write out the type table for a module.
00319 static void WriteTypeTable(const ValueEnumerator &VE, BitstreamWriter &Stream) {
00320   const ValueEnumerator::TypeList &TypeList = VE.getTypes();
00321 
00322   Stream.EnterSubblock(bitc::TYPE_BLOCK_ID_NEW, 4 /*count from # abbrevs */);
00323   SmallVector<uint64_t, 64> TypeVals;
00324 
00325   uint64_t NumBits = Log2_32_Ceil(VE.getTypes().size()+1);
00326 
00327   // Abbrev for TYPE_CODE_POINTER.
00328   BitCodeAbbrev *Abbv = new BitCodeAbbrev();
00329   Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_POINTER));
00330   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
00331   Abbv->Add(BitCodeAbbrevOp(0));  // Addrspace = 0
00332   unsigned PtrAbbrev = Stream.EmitAbbrev(Abbv);
00333 
00334   // Abbrev for TYPE_CODE_FUNCTION.
00335   Abbv = new BitCodeAbbrev();
00336   Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_FUNCTION));
00337   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));  // isvararg
00338   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
00339   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
00340 
00341   unsigned FunctionAbbrev = Stream.EmitAbbrev(Abbv);
00342 
00343   // Abbrev for TYPE_CODE_STRUCT_ANON.
00344   Abbv = new BitCodeAbbrev();
00345   Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_STRUCT_ANON));
00346   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));  // ispacked
00347   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
00348   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
00349 
00350   unsigned StructAnonAbbrev = Stream.EmitAbbrev(Abbv);
00351 
00352   // Abbrev for TYPE_CODE_STRUCT_NAME.
00353   Abbv = new BitCodeAbbrev();
00354   Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_STRUCT_NAME));
00355   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
00356   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
00357   unsigned StructNameAbbrev = Stream.EmitAbbrev(Abbv);
00358 
00359   // Abbrev for TYPE_CODE_STRUCT_NAMED.
00360   Abbv = new BitCodeAbbrev();
00361   Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_STRUCT_NAMED));
00362   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));  // ispacked
00363   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
00364   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
00365 
00366   unsigned StructNamedAbbrev = Stream.EmitAbbrev(Abbv);
00367 
00368   // Abbrev for TYPE_CODE_ARRAY.
00369   Abbv = new BitCodeAbbrev();
00370   Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_ARRAY));
00371   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));   // size
00372   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
00373 
00374   unsigned ArrayAbbrev = Stream.EmitAbbrev(Abbv);
00375 
00376   // Emit an entry count so the reader can reserve space.
00377   TypeVals.push_back(TypeList.size());
00378   Stream.EmitRecord(bitc::TYPE_CODE_NUMENTRY, TypeVals);
00379   TypeVals.clear();
00380 
00381   // Loop over all of the types, emitting each in turn.
00382   for (unsigned i = 0, e = TypeList.size(); i != e; ++i) {
00383     Type *T = TypeList[i];
00384     int AbbrevToUse = 0;
00385     unsigned Code = 0;
00386 
00387     switch (T->getTypeID()) {
00388     case Type::VoidTyID:      Code = bitc::TYPE_CODE_VOID;      break;
00389     case Type::HalfTyID:      Code = bitc::TYPE_CODE_HALF;      break;
00390     case Type::FloatTyID:     Code = bitc::TYPE_CODE_FLOAT;     break;
00391     case Type::DoubleTyID:    Code = bitc::TYPE_CODE_DOUBLE;    break;
00392     case Type::X86_FP80TyID:  Code = bitc::TYPE_CODE_X86_FP80;  break;
00393     case Type::FP128TyID:     Code = bitc::TYPE_CODE_FP128;     break;
00394     case Type::PPC_FP128TyID: Code = bitc::TYPE_CODE_PPC_FP128; break;
00395     case Type::LabelTyID:     Code = bitc::TYPE_CODE_LABEL;     break;
00396     case Type::MetadataTyID:  Code = bitc::TYPE_CODE_METADATA;  break;
00397     case Type::X86_MMXTyID:   Code = bitc::TYPE_CODE_X86_MMX;   break;
00398     case Type::IntegerTyID:
00399       // INTEGER: [width]
00400       Code = bitc::TYPE_CODE_INTEGER;
00401       TypeVals.push_back(cast<IntegerType>(T)->getBitWidth());
00402       break;
00403     case Type::PointerTyID: {
00404       PointerType *PTy = cast<PointerType>(T);
00405       // POINTER: [pointee type, address space]
00406       Code = bitc::TYPE_CODE_POINTER;
00407       TypeVals.push_back(VE.getTypeID(PTy->getElementType()));
00408       unsigned AddressSpace = PTy->getAddressSpace();
00409       TypeVals.push_back(AddressSpace);
00410       if (AddressSpace == 0) AbbrevToUse = PtrAbbrev;
00411       break;
00412     }
00413     case Type::FunctionTyID: {
00414       FunctionType *FT = cast<FunctionType>(T);
00415       // FUNCTION: [isvararg, retty, paramty x N]
00416       Code = bitc::TYPE_CODE_FUNCTION;
00417       TypeVals.push_back(FT->isVarArg());
00418       TypeVals.push_back(VE.getTypeID(FT->getReturnType()));
00419       for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i)
00420         TypeVals.push_back(VE.getTypeID(FT->getParamType(i)));
00421       AbbrevToUse = FunctionAbbrev;
00422       break;
00423     }
00424     case Type::StructTyID: {
00425       StructType *ST = cast<StructType>(T);
00426       // STRUCT: [ispacked, eltty x N]
00427       TypeVals.push_back(ST->isPacked());
00428       // Output all of the element types.
00429       for (StructType::element_iterator I = ST->element_begin(),
00430            E = ST->element_end(); I != E; ++I)
00431         TypeVals.push_back(VE.getTypeID(*I));
00432 
00433       if (ST->isLiteral()) {
00434         Code = bitc::TYPE_CODE_STRUCT_ANON;
00435         AbbrevToUse = StructAnonAbbrev;
00436       } else {
00437         if (ST->isOpaque()) {
00438           Code = bitc::TYPE_CODE_OPAQUE;
00439         } else {
00440           Code = bitc::TYPE_CODE_STRUCT_NAMED;
00441           AbbrevToUse = StructNamedAbbrev;
00442         }
00443 
00444         // Emit the name if it is present.
00445         if (!ST->getName().empty())
00446           WriteStringRecord(bitc::TYPE_CODE_STRUCT_NAME, ST->getName(),
00447                             StructNameAbbrev, Stream);
00448       }
00449       break;
00450     }
00451     case Type::ArrayTyID: {
00452       ArrayType *AT = cast<ArrayType>(T);
00453       // ARRAY: [numelts, eltty]
00454       Code = bitc::TYPE_CODE_ARRAY;
00455       TypeVals.push_back(AT->getNumElements());
00456       TypeVals.push_back(VE.getTypeID(AT->getElementType()));
00457       AbbrevToUse = ArrayAbbrev;
00458       break;
00459     }
00460     case Type::VectorTyID: {
00461       VectorType *VT = cast<VectorType>(T);
00462       // VECTOR [numelts, eltty]
00463       Code = bitc::TYPE_CODE_VECTOR;
00464       TypeVals.push_back(VT->getNumElements());
00465       TypeVals.push_back(VE.getTypeID(VT->getElementType()));
00466       break;
00467     }
00468     }
00469 
00470     // Emit the finished record.
00471     Stream.EmitRecord(Code, TypeVals, AbbrevToUse);
00472     TypeVals.clear();
00473   }
00474 
00475   Stream.ExitBlock();
00476 }
00477 
00478 static unsigned getEncodedLinkage(const GlobalValue &GV) {
00479   switch (GV.getLinkage()) {
00480   case GlobalValue::ExternalLinkage:
00481     return 0;
00482   case GlobalValue::WeakAnyLinkage:
00483     return 16;
00484   case GlobalValue::AppendingLinkage:
00485     return 2;
00486   case GlobalValue::InternalLinkage:
00487     return 3;
00488   case GlobalValue::LinkOnceAnyLinkage:
00489     return 18;
00490   case GlobalValue::ExternalWeakLinkage:
00491     return 7;
00492   case GlobalValue::CommonLinkage:
00493     return 8;
00494   case GlobalValue::PrivateLinkage:
00495     return 9;
00496   case GlobalValue::WeakODRLinkage:
00497     return 17;
00498   case GlobalValue::LinkOnceODRLinkage:
00499     return 19;
00500   case GlobalValue::AvailableExternallyLinkage:
00501     return 12;
00502   }
00503   llvm_unreachable("Invalid linkage");
00504 }
00505 
00506 static unsigned getEncodedVisibility(const GlobalValue &GV) {
00507   switch (GV.getVisibility()) {
00508   case GlobalValue::DefaultVisibility:   return 0;
00509   case GlobalValue::HiddenVisibility:    return 1;
00510   case GlobalValue::ProtectedVisibility: return 2;
00511   }
00512   llvm_unreachable("Invalid visibility");
00513 }
00514 
00515 static unsigned getEncodedDLLStorageClass(const GlobalValue &GV) {
00516   switch (GV.getDLLStorageClass()) {
00517   case GlobalValue::DefaultStorageClass:   return 0;
00518   case GlobalValue::DLLImportStorageClass: return 1;
00519   case GlobalValue::DLLExportStorageClass: return 2;
00520   }
00521   llvm_unreachable("Invalid DLL storage class");
00522 }
00523 
00524 static unsigned getEncodedThreadLocalMode(const GlobalValue &GV) {
00525   switch (GV.getThreadLocalMode()) {
00526     case GlobalVariable::NotThreadLocal:         return 0;
00527     case GlobalVariable::GeneralDynamicTLSModel: return 1;
00528     case GlobalVariable::LocalDynamicTLSModel:   return 2;
00529     case GlobalVariable::InitialExecTLSModel:    return 3;
00530     case GlobalVariable::LocalExecTLSModel:      return 4;
00531   }
00532   llvm_unreachable("Invalid TLS model");
00533 }
00534 
00535 static unsigned getEncodedComdatSelectionKind(const Comdat &C) {
00536   switch (C.getSelectionKind()) {
00537   case Comdat::Any:
00538     return bitc::COMDAT_SELECTION_KIND_ANY;
00539   case Comdat::ExactMatch:
00540     return bitc::COMDAT_SELECTION_KIND_EXACT_MATCH;
00541   case Comdat::Largest:
00542     return bitc::COMDAT_SELECTION_KIND_LARGEST;
00543   case Comdat::NoDuplicates:
00544     return bitc::COMDAT_SELECTION_KIND_NO_DUPLICATES;
00545   case Comdat::SameSize:
00546     return bitc::COMDAT_SELECTION_KIND_SAME_SIZE;
00547   }
00548   llvm_unreachable("Invalid selection kind");
00549 }
00550 
00551 static void writeComdats(const ValueEnumerator &VE, BitstreamWriter &Stream) {
00552   SmallVector<uint16_t, 64> Vals;
00553   for (const Comdat *C : VE.getComdats()) {
00554     // COMDAT: [selection_kind, name]
00555     Vals.push_back(getEncodedComdatSelectionKind(*C));
00556     size_t Size = C->getName().size();
00557     assert(isUInt<16>(Size));
00558     Vals.push_back(Size);
00559     for (char Chr : C->getName())
00560       Vals.push_back((unsigned char)Chr);
00561     Stream.EmitRecord(bitc::MODULE_CODE_COMDAT, Vals, /*AbbrevToUse=*/0);
00562     Vals.clear();
00563   }
00564 }
00565 
00566 // Emit top-level description of module, including target triple, inline asm,
00567 // descriptors for global variables, and function prototype info.
00568 static void WriteModuleInfo(const Module *M, const ValueEnumerator &VE,
00569                             BitstreamWriter &Stream) {
00570   // Emit various pieces of data attached to a module.
00571   if (!M->getTargetTriple().empty())
00572     WriteStringRecord(bitc::MODULE_CODE_TRIPLE, M->getTargetTriple(),
00573                       0/*TODO*/, Stream);
00574   const std::string &DL = M->getDataLayoutStr();
00575   if (!DL.empty())
00576     WriteStringRecord(bitc::MODULE_CODE_DATALAYOUT, DL, 0 /*TODO*/, Stream);
00577   if (!M->getModuleInlineAsm().empty())
00578     WriteStringRecord(bitc::MODULE_CODE_ASM, M->getModuleInlineAsm(),
00579                       0/*TODO*/, Stream);
00580 
00581   // Emit information about sections and GC, computing how many there are. Also
00582   // compute the maximum alignment value.
00583   std::map<std::string, unsigned> SectionMap;
00584   std::map<std::string, unsigned> GCMap;
00585   unsigned MaxAlignment = 0;
00586   unsigned MaxGlobalType = 0;
00587   for (const GlobalValue &GV : M->globals()) {
00588     MaxAlignment = std::max(MaxAlignment, GV.getAlignment());
00589     MaxGlobalType = std::max(MaxGlobalType, VE.getTypeID(GV.getType()));
00590     if (GV.hasSection()) {
00591       // Give section names unique ID's.
00592       unsigned &Entry = SectionMap[GV.getSection()];
00593       if (!Entry) {
00594         WriteStringRecord(bitc::MODULE_CODE_SECTIONNAME, GV.getSection(),
00595                           0/*TODO*/, Stream);
00596         Entry = SectionMap.size();
00597       }
00598     }
00599   }
00600   for (const Function &F : *M) {
00601     MaxAlignment = std::max(MaxAlignment, F.getAlignment());
00602     if (F.hasSection()) {
00603       // Give section names unique ID's.
00604       unsigned &Entry = SectionMap[F.getSection()];
00605       if (!Entry) {
00606         WriteStringRecord(bitc::MODULE_CODE_SECTIONNAME, F.getSection(),
00607                           0/*TODO*/, Stream);
00608         Entry = SectionMap.size();
00609       }
00610     }
00611     if (F.hasGC()) {
00612       // Same for GC names.
00613       unsigned &Entry = GCMap[F.getGC()];
00614       if (!Entry) {
00615         WriteStringRecord(bitc::MODULE_CODE_GCNAME, F.getGC(),
00616                           0/*TODO*/, Stream);
00617         Entry = GCMap.size();
00618       }
00619     }
00620   }
00621 
00622   // Emit abbrev for globals, now that we know # sections and max alignment.
00623   unsigned SimpleGVarAbbrev = 0;
00624   if (!M->global_empty()) {
00625     // Add an abbrev for common globals with no visibility or thread localness.
00626     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
00627     Abbv->Add(BitCodeAbbrevOp(bitc::MODULE_CODE_GLOBALVAR));
00628     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
00629                               Log2_32_Ceil(MaxGlobalType+1)));
00630     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));      // Constant.
00631     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));        // Initializer.
00632     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 5));      // Linkage.
00633     if (MaxAlignment == 0)                                      // Alignment.
00634       Abbv->Add(BitCodeAbbrevOp(0));
00635     else {
00636       unsigned MaxEncAlignment = Log2_32(MaxAlignment)+1;
00637       Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
00638                                Log2_32_Ceil(MaxEncAlignment+1)));
00639     }
00640     if (SectionMap.empty())                                    // Section.
00641       Abbv->Add(BitCodeAbbrevOp(0));
00642     else
00643       Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
00644                                Log2_32_Ceil(SectionMap.size()+1)));
00645     // Don't bother emitting vis + thread local.
00646     SimpleGVarAbbrev = Stream.EmitAbbrev(Abbv);
00647   }
00648 
00649   // Emit the global variable information.
00650   SmallVector<unsigned, 64> Vals;
00651   for (const GlobalVariable &GV : M->globals()) {
00652     unsigned AbbrevToUse = 0;
00653 
00654     // GLOBALVAR: [type, isconst, initid,
00655     //             linkage, alignment, section, visibility, threadlocal,
00656     //             unnamed_addr, externally_initialized, dllstorageclass]
00657     Vals.push_back(VE.getTypeID(GV.getType()));
00658     Vals.push_back(GV.isConstant());
00659     Vals.push_back(GV.isDeclaration() ? 0 :
00660                    (VE.getValueID(GV.getInitializer()) + 1));
00661     Vals.push_back(getEncodedLinkage(GV));
00662     Vals.push_back(Log2_32(GV.getAlignment())+1);
00663     Vals.push_back(GV.hasSection() ? SectionMap[GV.getSection()] : 0);
00664     if (GV.isThreadLocal() ||
00665         GV.getVisibility() != GlobalValue::DefaultVisibility ||
00666         GV.hasUnnamedAddr() || GV.isExternallyInitialized() ||
00667         GV.getDLLStorageClass() != GlobalValue::DefaultStorageClass ||
00668         GV.hasComdat()) {
00669       Vals.push_back(getEncodedVisibility(GV));
00670       Vals.push_back(getEncodedThreadLocalMode(GV));
00671       Vals.push_back(GV.hasUnnamedAddr());
00672       Vals.push_back(GV.isExternallyInitialized());
00673       Vals.push_back(getEncodedDLLStorageClass(GV));
00674       Vals.push_back(GV.hasComdat() ? VE.getComdatID(GV.getComdat()) : 0);
00675     } else {
00676       AbbrevToUse = SimpleGVarAbbrev;
00677     }
00678 
00679     Stream.EmitRecord(bitc::MODULE_CODE_GLOBALVAR, Vals, AbbrevToUse);
00680     Vals.clear();
00681   }
00682 
00683   // Emit the function proto information.
00684   for (const Function &F : *M) {
00685     // FUNCTION:  [type, callingconv, isproto, linkage, paramattrs, alignment,
00686     //             section, visibility, gc, unnamed_addr, prologuedata,
00687     //             dllstorageclass, comdat, prefixdata]
00688     Vals.push_back(VE.getTypeID(F.getType()));
00689     Vals.push_back(F.getCallingConv());
00690     Vals.push_back(F.isDeclaration());
00691     Vals.push_back(getEncodedLinkage(F));
00692     Vals.push_back(VE.getAttributeID(F.getAttributes()));
00693     Vals.push_back(Log2_32(F.getAlignment())+1);
00694     Vals.push_back(F.hasSection() ? SectionMap[F.getSection()] : 0);
00695     Vals.push_back(getEncodedVisibility(F));
00696     Vals.push_back(F.hasGC() ? GCMap[F.getGC()] : 0);
00697     Vals.push_back(F.hasUnnamedAddr());
00698     Vals.push_back(F.hasPrologueData() ? (VE.getValueID(F.getPrologueData()) + 1)
00699                                        : 0);
00700     Vals.push_back(getEncodedDLLStorageClass(F));
00701     Vals.push_back(F.hasComdat() ? VE.getComdatID(F.getComdat()) : 0);
00702     Vals.push_back(F.hasPrefixData() ? (VE.getValueID(F.getPrefixData()) + 1)
00703                                      : 0);
00704 
00705     unsigned AbbrevToUse = 0;
00706     Stream.EmitRecord(bitc::MODULE_CODE_FUNCTION, Vals, AbbrevToUse);
00707     Vals.clear();
00708   }
00709 
00710   // Emit the alias information.
00711   for (const GlobalAlias &A : M->aliases()) {
00712     // ALIAS: [alias type, aliasee val#, linkage, visibility]
00713     Vals.push_back(VE.getTypeID(A.getType()));
00714     Vals.push_back(VE.getValueID(A.getAliasee()));
00715     Vals.push_back(getEncodedLinkage(A));
00716     Vals.push_back(getEncodedVisibility(A));
00717     Vals.push_back(getEncodedDLLStorageClass(A));
00718     Vals.push_back(getEncodedThreadLocalMode(A));
00719     Vals.push_back(A.hasUnnamedAddr());
00720     unsigned AbbrevToUse = 0;
00721     Stream.EmitRecord(bitc::MODULE_CODE_ALIAS, Vals, AbbrevToUse);
00722     Vals.clear();
00723   }
00724 }
00725 
00726 static uint64_t GetOptimizationFlags(const Value *V) {
00727   uint64_t Flags = 0;
00728 
00729   if (const auto *OBO = dyn_cast<OverflowingBinaryOperator>(V)) {
00730     if (OBO->hasNoSignedWrap())
00731       Flags |= 1 << bitc::OBO_NO_SIGNED_WRAP;
00732     if (OBO->hasNoUnsignedWrap())
00733       Flags |= 1 << bitc::OBO_NO_UNSIGNED_WRAP;
00734   } else if (const auto *PEO = dyn_cast<PossiblyExactOperator>(V)) {
00735     if (PEO->isExact())
00736       Flags |= 1 << bitc::PEO_EXACT;
00737   } else if (const auto *FPMO = dyn_cast<FPMathOperator>(V)) {
00738     if (FPMO->hasUnsafeAlgebra())
00739       Flags |= FastMathFlags::UnsafeAlgebra;
00740     if (FPMO->hasNoNaNs())
00741       Flags |= FastMathFlags::NoNaNs;
00742     if (FPMO->hasNoInfs())
00743       Flags |= FastMathFlags::NoInfs;
00744     if (FPMO->hasNoSignedZeros())
00745       Flags |= FastMathFlags::NoSignedZeros;
00746     if (FPMO->hasAllowReciprocal())
00747       Flags |= FastMathFlags::AllowReciprocal;
00748   }
00749 
00750   return Flags;
00751 }
00752 
00753 static void WriteValueAsMetadata(const ValueAsMetadata *MD,
00754                                  const ValueEnumerator &VE,
00755                                  BitstreamWriter &Stream,
00756                                  SmallVectorImpl<uint64_t> &Record) {
00757   // Mimic an MDNode with a value as one operand.
00758   Value *V = MD->getValue();
00759   Record.push_back(VE.getTypeID(V->getType()));
00760   Record.push_back(VE.getValueID(V));
00761   Stream.EmitRecord(bitc::METADATA_VALUE, Record, 0);
00762   Record.clear();
00763 }
00764 
00765 static void WriteMDTuple(const MDTuple *N, const ValueEnumerator &VE,
00766                          BitstreamWriter &Stream,
00767                          SmallVectorImpl<uint64_t> &Record, unsigned Abbrev) {
00768   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
00769     Metadata *MD = N->getOperand(i);
00770     assert(!(MD && isa<LocalAsMetadata>(MD)) &&
00771            "Unexpected function-local metadata");
00772     Record.push_back(VE.getMetadataOrNullID(MD));
00773   }
00774   Stream.EmitRecord(N->isDistinct() ? bitc::METADATA_DISTINCT_NODE
00775                                     : bitc::METADATA_NODE,
00776                     Record, Abbrev);
00777   Record.clear();
00778 }
00779 
00780 static void WriteMDLocation(const MDLocation *N, const ValueEnumerator &VE,
00781                             BitstreamWriter &Stream,
00782                             SmallVectorImpl<uint64_t> &Record,
00783                             unsigned Abbrev) {
00784   Record.push_back(N->isDistinct());
00785   Record.push_back(N->getLine());
00786   Record.push_back(N->getColumn());
00787   Record.push_back(VE.getMetadataID(N->getScope()));
00788   Record.push_back(VE.getMetadataOrNullID(N->getInlinedAt()));
00789 
00790   Stream.EmitRecord(bitc::METADATA_LOCATION, Record, Abbrev);
00791   Record.clear();
00792 }
00793 
00794 static void WriteGenericDebugNode(const GenericDebugNode *,
00795                                   const ValueEnumerator &, BitstreamWriter &,
00796                                   SmallVectorImpl<uint64_t> &, unsigned) {
00797   llvm_unreachable("unimplemented");
00798 }
00799 
00800 static void WriteModuleMetadata(const Module *M,
00801                                 const ValueEnumerator &VE,
00802                                 BitstreamWriter &Stream) {
00803   const auto &MDs = VE.getMDs();
00804   if (MDs.empty() && M->named_metadata_empty())
00805     return;
00806 
00807   Stream.EnterSubblock(bitc::METADATA_BLOCK_ID, 3);
00808 
00809   unsigned MDSAbbrev = 0;
00810   if (VE.hasMDString()) {
00811     // Abbrev for METADATA_STRING.
00812     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
00813     Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_STRING));
00814     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
00815     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
00816     MDSAbbrev = Stream.EmitAbbrev(Abbv);
00817   }
00818 
00819   unsigned MDLocationAbbrev = 0;
00820   if (VE.hasMDLocation()) {
00821     // Abbrev for METADATA_LOCATION.
00822     //
00823     // Assume the column is usually under 128, and always output the inlined-at
00824     // location (it's never more expensive than building an array size 1).
00825     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
00826     Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_LOCATION));
00827     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));
00828     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
00829     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
00830     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
00831     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
00832     MDLocationAbbrev = Stream.EmitAbbrev(Abbv);
00833   }
00834 
00835   unsigned NameAbbrev = 0;
00836   if (!M->named_metadata_empty()) {
00837     // Abbrev for METADATA_NAME.
00838     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
00839     Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_NAME));
00840     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
00841     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
00842     NameAbbrev = Stream.EmitAbbrev(Abbv);
00843   }
00844 
00845   unsigned MDTupleAbbrev = 0;
00846   unsigned GenericDebugNodeAbbrev = 0;
00847   SmallVector<uint64_t, 64> Record;
00848   for (const Metadata *MD : MDs) {
00849     if (const MDNode *N = dyn_cast<MDNode>(MD)) {
00850       switch (N->getMetadataID()) {
00851       default:
00852         llvm_unreachable("Invalid MDNode subclass");
00853 #define HANDLE_MDNODE_LEAF(CLASS)                                              \
00854   case Metadata::CLASS##Kind:                                                  \
00855     Write##CLASS(cast<CLASS>(N), VE, Stream, Record, CLASS##Abbrev);           \
00856     continue;
00857 #include "llvm/IR/Metadata.def"
00858       }
00859     }
00860     if (const auto *MDC = dyn_cast<ConstantAsMetadata>(MD)) {
00861       WriteValueAsMetadata(MDC, VE, Stream, Record);
00862       continue;
00863     }
00864     const MDString *MDS = cast<MDString>(MD);
00865     // Code: [strchar x N]
00866     Record.append(MDS->bytes_begin(), MDS->bytes_end());
00867 
00868     // Emit the finished record.
00869     Stream.EmitRecord(bitc::METADATA_STRING, Record, MDSAbbrev);
00870     Record.clear();
00871   }
00872 
00873   // Write named metadata.
00874   for (const NamedMDNode &NMD : M->named_metadata()) {
00875     // Write name.
00876     StringRef Str = NMD.getName();
00877     Record.append(Str.bytes_begin(), Str.bytes_end());
00878     Stream.EmitRecord(bitc::METADATA_NAME, Record, NameAbbrev);
00879     Record.clear();
00880 
00881     // Write named metadata operands.
00882     for (const MDNode *N : NMD.operands())
00883       Record.push_back(VE.getMetadataID(N));
00884     Stream.EmitRecord(bitc::METADATA_NAMED_NODE, Record, 0);
00885     Record.clear();
00886   }
00887 
00888   Stream.ExitBlock();
00889 }
00890 
00891 static void WriteFunctionLocalMetadata(const Function &F,
00892                                        const ValueEnumerator &VE,
00893                                        BitstreamWriter &Stream) {
00894   bool StartedMetadataBlock = false;
00895   SmallVector<uint64_t, 64> Record;
00896   const SmallVectorImpl<const LocalAsMetadata *> &MDs =
00897       VE.getFunctionLocalMDs();
00898   for (unsigned i = 0, e = MDs.size(); i != e; ++i) {
00899     assert(MDs[i] && "Expected valid function-local metadata");
00900     if (!StartedMetadataBlock) {
00901       Stream.EnterSubblock(bitc::METADATA_BLOCK_ID, 3);
00902       StartedMetadataBlock = true;
00903     }
00904     WriteValueAsMetadata(MDs[i], VE, Stream, Record);
00905   }
00906 
00907   if (StartedMetadataBlock)
00908     Stream.ExitBlock();
00909 }
00910 
00911 static void WriteMetadataAttachment(const Function &F,
00912                                     const ValueEnumerator &VE,
00913                                     BitstreamWriter &Stream) {
00914   Stream.EnterSubblock(bitc::METADATA_ATTACHMENT_ID, 3);
00915 
00916   SmallVector<uint64_t, 64> Record;
00917 
00918   // Write metadata attachments
00919   // METADATA_ATTACHMENT - [m x [value, [n x [id, mdnode]]]
00920   SmallVector<std::pair<unsigned, MDNode *>, 4> MDs;
00921 
00922   for (Function::const_iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
00923     for (BasicBlock::const_iterator I = BB->begin(), E = BB->end();
00924          I != E; ++I) {
00925       MDs.clear();
00926       I->getAllMetadataOtherThanDebugLoc(MDs);
00927 
00928       // If no metadata, ignore instruction.
00929       if (MDs.empty()) continue;
00930 
00931       Record.push_back(VE.getInstructionID(I));
00932 
00933       for (unsigned i = 0, e = MDs.size(); i != e; ++i) {
00934         Record.push_back(MDs[i].first);
00935         Record.push_back(VE.getMetadataID(MDs[i].second));
00936       }
00937       Stream.EmitRecord(bitc::METADATA_ATTACHMENT, Record, 0);
00938       Record.clear();
00939     }
00940 
00941   Stream.ExitBlock();
00942 }
00943 
00944 static void WriteModuleMetadataStore(const Module *M, BitstreamWriter &Stream) {
00945   SmallVector<uint64_t, 64> Record;
00946 
00947   // Write metadata kinds
00948   // METADATA_KIND - [n x [id, name]]
00949   SmallVector<StringRef, 8> Names;
00950   M->getMDKindNames(Names);
00951 
00952   if (Names.empty()) return;
00953 
00954   Stream.EnterSubblock(bitc::METADATA_BLOCK_ID, 3);
00955 
00956   for (unsigned MDKindID = 0, e = Names.size(); MDKindID != e; ++MDKindID) {
00957     Record.push_back(MDKindID);
00958     StringRef KName = Names[MDKindID];
00959     Record.append(KName.begin(), KName.end());
00960 
00961     Stream.EmitRecord(bitc::METADATA_KIND, Record, 0);
00962     Record.clear();
00963   }
00964 
00965   Stream.ExitBlock();
00966 }
00967 
00968 static void emitSignedInt64(SmallVectorImpl<uint64_t> &Vals, uint64_t V) {
00969   if ((int64_t)V >= 0)
00970     Vals.push_back(V << 1);
00971   else
00972     Vals.push_back((-V << 1) | 1);
00973 }
00974 
00975 static void WriteConstants(unsigned FirstVal, unsigned LastVal,
00976                            const ValueEnumerator &VE,
00977                            BitstreamWriter &Stream, bool isGlobal) {
00978   if (FirstVal == LastVal) return;
00979 
00980   Stream.EnterSubblock(bitc::CONSTANTS_BLOCK_ID, 4);
00981 
00982   unsigned AggregateAbbrev = 0;
00983   unsigned String8Abbrev = 0;
00984   unsigned CString7Abbrev = 0;
00985   unsigned CString6Abbrev = 0;
00986   // If this is a constant pool for the module, emit module-specific abbrevs.
00987   if (isGlobal) {
00988     // Abbrev for CST_CODE_AGGREGATE.
00989     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
00990     Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_AGGREGATE));
00991     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
00992     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, Log2_32_Ceil(LastVal+1)));
00993     AggregateAbbrev = Stream.EmitAbbrev(Abbv);
00994 
00995     // Abbrev for CST_CODE_STRING.
00996     Abbv = new BitCodeAbbrev();
00997     Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_STRING));
00998     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
00999     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
01000     String8Abbrev = Stream.EmitAbbrev(Abbv);
01001     // Abbrev for CST_CODE_CSTRING.
01002     Abbv = new BitCodeAbbrev();
01003     Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_CSTRING));
01004     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
01005     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7));
01006     CString7Abbrev = Stream.EmitAbbrev(Abbv);
01007     // Abbrev for CST_CODE_CSTRING.
01008     Abbv = new BitCodeAbbrev();
01009     Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_CSTRING));
01010     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
01011     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
01012     CString6Abbrev = Stream.EmitAbbrev(Abbv);
01013   }
01014 
01015   SmallVector<uint64_t, 64> Record;
01016 
01017   const ValueEnumerator::ValueList &Vals = VE.getValues();
01018   Type *LastTy = nullptr;
01019   for (unsigned i = FirstVal; i != LastVal; ++i) {
01020     const Value *V = Vals[i].first;
01021     // If we need to switch types, do so now.
01022     if (V->getType() != LastTy) {
01023       LastTy = V->getType();
01024       Record.push_back(VE.getTypeID(LastTy));
01025       Stream.EmitRecord(bitc::CST_CODE_SETTYPE, Record,
01026                         CONSTANTS_SETTYPE_ABBREV);
01027       Record.clear();
01028     }
01029 
01030     if (const InlineAsm *IA = dyn_cast<InlineAsm>(V)) {
01031       Record.push_back(unsigned(IA->hasSideEffects()) |
01032                        unsigned(IA->isAlignStack()) << 1 |
01033                        unsigned(IA->getDialect()&1) << 2);
01034 
01035       // Add the asm string.
01036       const std::string &AsmStr = IA->getAsmString();
01037       Record.push_back(AsmStr.size());
01038       for (unsigned i = 0, e = AsmStr.size(); i != e; ++i)
01039         Record.push_back(AsmStr[i]);
01040 
01041       // Add the constraint string.
01042       const std::string &ConstraintStr = IA->getConstraintString();
01043       Record.push_back(ConstraintStr.size());
01044       for (unsigned i = 0, e = ConstraintStr.size(); i != e; ++i)
01045         Record.push_back(ConstraintStr[i]);
01046       Stream.EmitRecord(bitc::CST_CODE_INLINEASM, Record);
01047       Record.clear();
01048       continue;
01049     }
01050     const Constant *C = cast<Constant>(V);
01051     unsigned Code = -1U;
01052     unsigned AbbrevToUse = 0;
01053     if (C->isNullValue()) {
01054       Code = bitc::CST_CODE_NULL;
01055     } else if (isa<UndefValue>(C)) {
01056       Code = bitc::CST_CODE_UNDEF;
01057     } else if (const ConstantInt *IV = dyn_cast<ConstantInt>(C)) {
01058       if (IV->getBitWidth() <= 64) {
01059         uint64_t V = IV->getSExtValue();
01060         emitSignedInt64(Record, V);
01061         Code = bitc::CST_CODE_INTEGER;
01062         AbbrevToUse = CONSTANTS_INTEGER_ABBREV;
01063       } else {                             // Wide integers, > 64 bits in size.
01064         // We have an arbitrary precision integer value to write whose
01065         // bit width is > 64. However, in canonical unsigned integer
01066         // format it is likely that the high bits are going to be zero.
01067         // So, we only write the number of active words.
01068         unsigned NWords = IV->getValue().getActiveWords();
01069         const uint64_t *RawWords = IV->getValue().getRawData();
01070         for (unsigned i = 0; i != NWords; ++i) {
01071           emitSignedInt64(Record, RawWords[i]);
01072         }
01073         Code = bitc::CST_CODE_WIDE_INTEGER;
01074       }
01075     } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
01076       Code = bitc::CST_CODE_FLOAT;
01077       Type *Ty = CFP->getType();
01078       if (Ty->isHalfTy() || Ty->isFloatTy() || Ty->isDoubleTy()) {
01079         Record.push_back(CFP->getValueAPF().bitcastToAPInt().getZExtValue());
01080       } else if (Ty->isX86_FP80Ty()) {
01081         // api needed to prevent premature destruction
01082         // bits are not in the same order as a normal i80 APInt, compensate.
01083         APInt api = CFP->getValueAPF().bitcastToAPInt();
01084         const uint64_t *p = api.getRawData();
01085         Record.push_back((p[1] << 48) | (p[0] >> 16));
01086         Record.push_back(p[0] & 0xffffLL);
01087       } else if (Ty->isFP128Ty() || Ty->isPPC_FP128Ty()) {
01088         APInt api = CFP->getValueAPF().bitcastToAPInt();
01089         const uint64_t *p = api.getRawData();
01090         Record.push_back(p[0]);
01091         Record.push_back(p[1]);
01092       } else {
01093         assert (0 && "Unknown FP type!");
01094       }
01095     } else if (isa<ConstantDataSequential>(C) &&
01096                cast<ConstantDataSequential>(C)->isString()) {
01097       const ConstantDataSequential *Str = cast<ConstantDataSequential>(C);
01098       // Emit constant strings specially.
01099       unsigned NumElts = Str->getNumElements();
01100       // If this is a null-terminated string, use the denser CSTRING encoding.
01101       if (Str->isCString()) {
01102         Code = bitc::CST_CODE_CSTRING;
01103         --NumElts;  // Don't encode the null, which isn't allowed by char6.
01104       } else {
01105         Code = bitc::CST_CODE_STRING;
01106         AbbrevToUse = String8Abbrev;
01107       }
01108       bool isCStr7 = Code == bitc::CST_CODE_CSTRING;
01109       bool isCStrChar6 = Code == bitc::CST_CODE_CSTRING;
01110       for (unsigned i = 0; i != NumElts; ++i) {
01111         unsigned char V = Str->getElementAsInteger(i);
01112         Record.push_back(V);
01113         isCStr7 &= (V & 128) == 0;
01114         if (isCStrChar6)
01115           isCStrChar6 = BitCodeAbbrevOp::isChar6(V);
01116       }
01117 
01118       if (isCStrChar6)
01119         AbbrevToUse = CString6Abbrev;
01120       else if (isCStr7)
01121         AbbrevToUse = CString7Abbrev;
01122     } else if (const ConstantDataSequential *CDS =
01123                   dyn_cast<ConstantDataSequential>(C)) {
01124       Code = bitc::CST_CODE_DATA;
01125       Type *EltTy = CDS->getType()->getElementType();
01126       if (isa<IntegerType>(EltTy)) {
01127         for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i)
01128           Record.push_back(CDS->getElementAsInteger(i));
01129       } else if (EltTy->isFloatTy()) {
01130         for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
01131           union { float F; uint32_t I; };
01132           F = CDS->getElementAsFloat(i);
01133           Record.push_back(I);
01134         }
01135       } else {
01136         assert(EltTy->isDoubleTy() && "Unknown ConstantData element type");
01137         for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
01138           union { double F; uint64_t I; };
01139           F = CDS->getElementAsDouble(i);
01140           Record.push_back(I);
01141         }
01142       }
01143     } else if (isa<ConstantArray>(C) || isa<ConstantStruct>(C) ||
01144                isa<ConstantVector>(C)) {
01145       Code = bitc::CST_CODE_AGGREGATE;
01146       for (unsigned i = 0, e = C->getNumOperands(); i != e; ++i)
01147         Record.push_back(VE.getValueID(C->getOperand(i)));
01148       AbbrevToUse = AggregateAbbrev;
01149     } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
01150       switch (CE->getOpcode()) {
01151       default:
01152         if (Instruction::isCast(CE->getOpcode())) {
01153           Code = bitc::CST_CODE_CE_CAST;
01154           Record.push_back(GetEncodedCastOpcode(CE->getOpcode()));
01155           Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
01156           Record.push_back(VE.getValueID(C->getOperand(0)));
01157           AbbrevToUse = CONSTANTS_CE_CAST_Abbrev;
01158         } else {
01159           assert(CE->getNumOperands() == 2 && "Unknown constant expr!");
01160           Code = bitc::CST_CODE_CE_BINOP;
01161           Record.push_back(GetEncodedBinaryOpcode(CE->getOpcode()));
01162           Record.push_back(VE.getValueID(C->getOperand(0)));
01163           Record.push_back(VE.getValueID(C->getOperand(1)));
01164           uint64_t Flags = GetOptimizationFlags(CE);
01165           if (Flags != 0)
01166             Record.push_back(Flags);
01167         }
01168         break;
01169       case Instruction::GetElementPtr:
01170         Code = bitc::CST_CODE_CE_GEP;
01171         if (cast<GEPOperator>(C)->isInBounds())
01172           Code = bitc::CST_CODE_CE_INBOUNDS_GEP;
01173         for (unsigned i = 0, e = CE->getNumOperands(); i != e; ++i) {
01174           Record.push_back(VE.getTypeID(C->getOperand(i)->getType()));
01175           Record.push_back(VE.getValueID(C->getOperand(i)));
01176         }
01177         break;
01178       case Instruction::Select:
01179         Code = bitc::CST_CODE_CE_SELECT;
01180         Record.push_back(VE.getValueID(C->getOperand(0)));
01181         Record.push_back(VE.getValueID(C->getOperand(1)));
01182         Record.push_back(VE.getValueID(C->getOperand(2)));
01183         break;
01184       case Instruction::ExtractElement:
01185         Code = bitc::CST_CODE_CE_EXTRACTELT;
01186         Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
01187         Record.push_back(VE.getValueID(C->getOperand(0)));
01188         Record.push_back(VE.getTypeID(C->getOperand(1)->getType()));
01189         Record.push_back(VE.getValueID(C->getOperand(1)));
01190         break;
01191       case Instruction::InsertElement:
01192         Code = bitc::CST_CODE_CE_INSERTELT;
01193         Record.push_back(VE.getValueID(C->getOperand(0)));
01194         Record.push_back(VE.getValueID(C->getOperand(1)));
01195         Record.push_back(VE.getTypeID(C->getOperand(2)->getType()));
01196         Record.push_back(VE.getValueID(C->getOperand(2)));
01197         break;
01198       case Instruction::ShuffleVector:
01199         // If the return type and argument types are the same, this is a
01200         // standard shufflevector instruction.  If the types are different,
01201         // then the shuffle is widening or truncating the input vectors, and
01202         // the argument type must also be encoded.
01203         if (C->getType() == C->getOperand(0)->getType()) {
01204           Code = bitc::CST_CODE_CE_SHUFFLEVEC;
01205         } else {
01206           Code = bitc::CST_CODE_CE_SHUFVEC_EX;
01207           Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
01208         }
01209         Record.push_back(VE.getValueID(C->getOperand(0)));
01210         Record.push_back(VE.getValueID(C->getOperand(1)));
01211         Record.push_back(VE.getValueID(C->getOperand(2)));
01212         break;
01213       case Instruction::ICmp:
01214       case Instruction::FCmp:
01215         Code = bitc::CST_CODE_CE_CMP;
01216         Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
01217         Record.push_back(VE.getValueID(C->getOperand(0)));
01218         Record.push_back(VE.getValueID(C->getOperand(1)));
01219         Record.push_back(CE->getPredicate());
01220         break;
01221       }
01222     } else if (const BlockAddress *BA = dyn_cast<BlockAddress>(C)) {
01223       Code = bitc::CST_CODE_BLOCKADDRESS;
01224       Record.push_back(VE.getTypeID(BA->getFunction()->getType()));
01225       Record.push_back(VE.getValueID(BA->getFunction()));
01226       Record.push_back(VE.getGlobalBasicBlockID(BA->getBasicBlock()));
01227     } else {
01228 #ifndef NDEBUG
01229       C->dump();
01230 #endif
01231       llvm_unreachable("Unknown constant!");
01232     }
01233     Stream.EmitRecord(Code, Record, AbbrevToUse);
01234     Record.clear();
01235   }
01236 
01237   Stream.ExitBlock();
01238 }
01239 
01240 static void WriteModuleConstants(const ValueEnumerator &VE,
01241                                  BitstreamWriter &Stream) {
01242   const ValueEnumerator::ValueList &Vals = VE.getValues();
01243 
01244   // Find the first constant to emit, which is the first non-globalvalue value.
01245   // We know globalvalues have been emitted by WriteModuleInfo.
01246   for (unsigned i = 0, e = Vals.size(); i != e; ++i) {
01247     if (!isa<GlobalValue>(Vals[i].first)) {
01248       WriteConstants(i, Vals.size(), VE, Stream, true);
01249       return;
01250     }
01251   }
01252 }
01253 
01254 /// PushValueAndType - The file has to encode both the value and type id for
01255 /// many values, because we need to know what type to create for forward
01256 /// references.  However, most operands are not forward references, so this type
01257 /// field is not needed.
01258 ///
01259 /// This function adds V's value ID to Vals.  If the value ID is higher than the
01260 /// instruction ID, then it is a forward reference, and it also includes the
01261 /// type ID.  The value ID that is written is encoded relative to the InstID.
01262 static bool PushValueAndType(const Value *V, unsigned InstID,
01263                              SmallVectorImpl<unsigned> &Vals,
01264                              ValueEnumerator &VE) {
01265   unsigned ValID = VE.getValueID(V);
01266   // Make encoding relative to the InstID.
01267   Vals.push_back(InstID - ValID);
01268   if (ValID >= InstID) {
01269     Vals.push_back(VE.getTypeID(V->getType()));
01270     return true;
01271   }
01272   return false;
01273 }
01274 
01275 /// pushValue - Like PushValueAndType, but where the type of the value is
01276 /// omitted (perhaps it was already encoded in an earlier operand).
01277 static void pushValue(const Value *V, unsigned InstID,
01278                       SmallVectorImpl<unsigned> &Vals,
01279                       ValueEnumerator &VE) {
01280   unsigned ValID = VE.getValueID(V);
01281   Vals.push_back(InstID - ValID);
01282 }
01283 
01284 static void pushValueSigned(const Value *V, unsigned InstID,
01285                             SmallVectorImpl<uint64_t> &Vals,
01286                             ValueEnumerator &VE) {
01287   unsigned ValID = VE.getValueID(V);
01288   int64_t diff = ((int32_t)InstID - (int32_t)ValID);
01289   emitSignedInt64(Vals, diff);
01290 }
01291 
01292 /// WriteInstruction - Emit an instruction to the specified stream.
01293 static void WriteInstruction(const Instruction &I, unsigned InstID,
01294                              ValueEnumerator &VE, BitstreamWriter &Stream,
01295                              SmallVectorImpl<unsigned> &Vals) {
01296   unsigned Code = 0;
01297   unsigned AbbrevToUse = 0;
01298   VE.setInstructionID(&I);
01299   switch (I.getOpcode()) {
01300   default:
01301     if (Instruction::isCast(I.getOpcode())) {
01302       Code = bitc::FUNC_CODE_INST_CAST;
01303       if (!PushValueAndType(I.getOperand(0), InstID, Vals, VE))
01304         AbbrevToUse = FUNCTION_INST_CAST_ABBREV;
01305       Vals.push_back(VE.getTypeID(I.getType()));
01306       Vals.push_back(GetEncodedCastOpcode(I.getOpcode()));
01307     } else {
01308       assert(isa<BinaryOperator>(I) && "Unknown instruction!");
01309       Code = bitc::FUNC_CODE_INST_BINOP;
01310       if (!PushValueAndType(I.getOperand(0), InstID, Vals, VE))
01311         AbbrevToUse = FUNCTION_INST_BINOP_ABBREV;
01312       pushValue(I.getOperand(1), InstID, Vals, VE);
01313       Vals.push_back(GetEncodedBinaryOpcode(I.getOpcode()));
01314       uint64_t Flags = GetOptimizationFlags(&I);
01315       if (Flags != 0) {
01316         if (AbbrevToUse == FUNCTION_INST_BINOP_ABBREV)
01317           AbbrevToUse = FUNCTION_INST_BINOP_FLAGS_ABBREV;
01318         Vals.push_back(Flags);
01319       }
01320     }
01321     break;
01322 
01323   case Instruction::GetElementPtr:
01324     Code = bitc::FUNC_CODE_INST_GEP;
01325     if (cast<GEPOperator>(&I)->isInBounds())
01326       Code = bitc::FUNC_CODE_INST_INBOUNDS_GEP;
01327     for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
01328       PushValueAndType(I.getOperand(i), InstID, Vals, VE);
01329     break;
01330   case Instruction::ExtractValue: {
01331     Code = bitc::FUNC_CODE_INST_EXTRACTVAL;
01332     PushValueAndType(I.getOperand(0), InstID, Vals, VE);
01333     const ExtractValueInst *EVI = cast<ExtractValueInst>(&I);
01334     for (const unsigned *i = EVI->idx_begin(), *e = EVI->idx_end(); i != e; ++i)
01335       Vals.push_back(*i);
01336     break;
01337   }
01338   case Instruction::InsertValue: {
01339     Code = bitc::FUNC_CODE_INST_INSERTVAL;
01340     PushValueAndType(I.getOperand(0), InstID, Vals, VE);
01341     PushValueAndType(I.getOperand(1), InstID, Vals, VE);
01342     const InsertValueInst *IVI = cast<InsertValueInst>(&I);
01343     for (const unsigned *i = IVI->idx_begin(), *e = IVI->idx_end(); i != e; ++i)
01344       Vals.push_back(*i);
01345     break;
01346   }
01347   case Instruction::Select:
01348     Code = bitc::FUNC_CODE_INST_VSELECT;
01349     PushValueAndType(I.getOperand(1), InstID, Vals, VE);
01350     pushValue(I.getOperand(2), InstID, Vals, VE);
01351     PushValueAndType(I.getOperand(0), InstID, Vals, VE);
01352     break;
01353   case Instruction::ExtractElement:
01354     Code = bitc::FUNC_CODE_INST_EXTRACTELT;
01355     PushValueAndType(I.getOperand(0), InstID, Vals, VE);
01356     PushValueAndType(I.getOperand(1), InstID, Vals, VE);
01357     break;
01358   case Instruction::InsertElement:
01359     Code = bitc::FUNC_CODE_INST_INSERTELT;
01360     PushValueAndType(I.getOperand(0), InstID, Vals, VE);
01361     pushValue(I.getOperand(1), InstID, Vals, VE);
01362     PushValueAndType(I.getOperand(2), InstID, Vals, VE);
01363     break;
01364   case Instruction::ShuffleVector:
01365     Code = bitc::FUNC_CODE_INST_SHUFFLEVEC;
01366     PushValueAndType(I.getOperand(0), InstID, Vals, VE);
01367     pushValue(I.getOperand(1), InstID, Vals, VE);
01368     pushValue(I.getOperand(2), InstID, Vals, VE);
01369     break;
01370   case Instruction::ICmp:
01371   case Instruction::FCmp:
01372     // compare returning Int1Ty or vector of Int1Ty
01373     Code = bitc::FUNC_CODE_INST_CMP2;
01374     PushValueAndType(I.getOperand(0), InstID, Vals, VE);
01375     pushValue(I.getOperand(1), InstID, Vals, VE);
01376     Vals.push_back(cast<CmpInst>(I).getPredicate());
01377     break;
01378 
01379   case Instruction::Ret:
01380     {
01381       Code = bitc::FUNC_CODE_INST_RET;
01382       unsigned NumOperands = I.getNumOperands();
01383       if (NumOperands == 0)
01384         AbbrevToUse = FUNCTION_INST_RET_VOID_ABBREV;
01385       else if (NumOperands == 1) {
01386         if (!PushValueAndType(I.getOperand(0), InstID, Vals, VE))
01387           AbbrevToUse = FUNCTION_INST_RET_VAL_ABBREV;
01388       } else {
01389         for (unsigned i = 0, e = NumOperands; i != e; ++i)
01390           PushValueAndType(I.getOperand(i), InstID, Vals, VE);
01391       }
01392     }
01393     break;
01394   case Instruction::Br:
01395     {
01396       Code = bitc::FUNC_CODE_INST_BR;
01397       const BranchInst &II = cast<BranchInst>(I);
01398       Vals.push_back(VE.getValueID(II.getSuccessor(0)));
01399       if (II.isConditional()) {
01400         Vals.push_back(VE.getValueID(II.getSuccessor(1)));
01401         pushValue(II.getCondition(), InstID, Vals, VE);
01402       }
01403     }
01404     break;
01405   case Instruction::Switch:
01406     {
01407       Code = bitc::FUNC_CODE_INST_SWITCH;
01408       const SwitchInst &SI = cast<SwitchInst>(I);
01409       Vals.push_back(VE.getTypeID(SI.getCondition()->getType()));
01410       pushValue(SI.getCondition(), InstID, Vals, VE);
01411       Vals.push_back(VE.getValueID(SI.getDefaultDest()));
01412       for (SwitchInst::ConstCaseIt i = SI.case_begin(), e = SI.case_end();
01413            i != e; ++i) {
01414         Vals.push_back(VE.getValueID(i.getCaseValue()));
01415         Vals.push_back(VE.getValueID(i.getCaseSuccessor()));
01416       }
01417     }
01418     break;
01419   case Instruction::IndirectBr:
01420     Code = bitc::FUNC_CODE_INST_INDIRECTBR;
01421     Vals.push_back(VE.getTypeID(I.getOperand(0)->getType()));
01422     // Encode the address operand as relative, but not the basic blocks.
01423     pushValue(I.getOperand(0), InstID, Vals, VE);
01424     for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i)
01425       Vals.push_back(VE.getValueID(I.getOperand(i)));
01426     break;
01427 
01428   case Instruction::Invoke: {
01429     const InvokeInst *II = cast<InvokeInst>(&I);
01430     const Value *Callee(II->getCalledValue());
01431     PointerType *PTy = cast<PointerType>(Callee->getType());
01432     FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
01433     Code = bitc::FUNC_CODE_INST_INVOKE;
01434 
01435     Vals.push_back(VE.getAttributeID(II->getAttributes()));
01436     Vals.push_back(II->getCallingConv());
01437     Vals.push_back(VE.getValueID(II->getNormalDest()));
01438     Vals.push_back(VE.getValueID(II->getUnwindDest()));
01439     PushValueAndType(Callee, InstID, Vals, VE);
01440 
01441     // Emit value #'s for the fixed parameters.
01442     for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
01443       pushValue(I.getOperand(i), InstID, Vals, VE);  // fixed param.
01444 
01445     // Emit type/value pairs for varargs params.
01446     if (FTy->isVarArg()) {
01447       for (unsigned i = FTy->getNumParams(), e = I.getNumOperands()-3;
01448            i != e; ++i)
01449         PushValueAndType(I.getOperand(i), InstID, Vals, VE); // vararg
01450     }
01451     break;
01452   }
01453   case Instruction::Resume:
01454     Code = bitc::FUNC_CODE_INST_RESUME;
01455     PushValueAndType(I.getOperand(0), InstID, Vals, VE);
01456     break;
01457   case Instruction::Unreachable:
01458     Code = bitc::FUNC_CODE_INST_UNREACHABLE;
01459     AbbrevToUse = FUNCTION_INST_UNREACHABLE_ABBREV;
01460     break;
01461 
01462   case Instruction::PHI: {
01463     const PHINode &PN = cast<PHINode>(I);
01464     Code = bitc::FUNC_CODE_INST_PHI;
01465     // With the newer instruction encoding, forward references could give
01466     // negative valued IDs.  This is most common for PHIs, so we use
01467     // signed VBRs.
01468     SmallVector<uint64_t, 128> Vals64;
01469     Vals64.push_back(VE.getTypeID(PN.getType()));
01470     for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
01471       pushValueSigned(PN.getIncomingValue(i), InstID, Vals64, VE);
01472       Vals64.push_back(VE.getValueID(PN.getIncomingBlock(i)));
01473     }
01474     // Emit a Vals64 vector and exit.
01475     Stream.EmitRecord(Code, Vals64, AbbrevToUse);
01476     Vals64.clear();
01477     return;
01478   }
01479 
01480   case Instruction::LandingPad: {
01481     const LandingPadInst &LP = cast<LandingPadInst>(I);
01482     Code = bitc::FUNC_CODE_INST_LANDINGPAD;
01483     Vals.push_back(VE.getTypeID(LP.getType()));
01484     PushValueAndType(LP.getPersonalityFn(), InstID, Vals, VE);
01485     Vals.push_back(LP.isCleanup());
01486     Vals.push_back(LP.getNumClauses());
01487     for (unsigned I = 0, E = LP.getNumClauses(); I != E; ++I) {
01488       if (LP.isCatch(I))
01489         Vals.push_back(LandingPadInst::Catch);
01490       else
01491         Vals.push_back(LandingPadInst::Filter);
01492       PushValueAndType(LP.getClause(I), InstID, Vals, VE);
01493     }
01494     break;
01495   }
01496 
01497   case Instruction::Alloca: {
01498     Code = bitc::FUNC_CODE_INST_ALLOCA;
01499     Vals.push_back(VE.getTypeID(I.getType()));
01500     Vals.push_back(VE.getTypeID(I.getOperand(0)->getType()));
01501     Vals.push_back(VE.getValueID(I.getOperand(0))); // size.
01502     const AllocaInst &AI = cast<AllocaInst>(I);
01503     unsigned AlignRecord = Log2_32(AI.getAlignment()) + 1;
01504     assert(Log2_32(Value::MaximumAlignment) + 1 < 1 << 5 &&
01505            "not enough bits for maximum alignment");
01506     assert(AlignRecord < 1 << 5 && "alignment greater than 1 << 64");
01507     AlignRecord |= AI.isUsedWithInAlloca() << 5;
01508     Vals.push_back(AlignRecord);
01509     break;
01510   }
01511 
01512   case Instruction::Load:
01513     if (cast<LoadInst>(I).isAtomic()) {
01514       Code = bitc::FUNC_CODE_INST_LOADATOMIC;
01515       PushValueAndType(I.getOperand(0), InstID, Vals, VE);
01516     } else {
01517       Code = bitc::FUNC_CODE_INST_LOAD;
01518       if (!PushValueAndType(I.getOperand(0), InstID, Vals, VE))  // ptr
01519         AbbrevToUse = FUNCTION_INST_LOAD_ABBREV;
01520     }
01521     Vals.push_back(Log2_32(cast<LoadInst>(I).getAlignment())+1);
01522     Vals.push_back(cast<LoadInst>(I).isVolatile());
01523     if (cast<LoadInst>(I).isAtomic()) {
01524       Vals.push_back(GetEncodedOrdering(cast<LoadInst>(I).getOrdering()));
01525       Vals.push_back(GetEncodedSynchScope(cast<LoadInst>(I).getSynchScope()));
01526     }
01527     break;
01528   case Instruction::Store:
01529     if (cast<StoreInst>(I).isAtomic())
01530       Code = bitc::FUNC_CODE_INST_STOREATOMIC;
01531     else
01532       Code = bitc::FUNC_CODE_INST_STORE;
01533     PushValueAndType(I.getOperand(1), InstID, Vals, VE);  // ptrty + ptr
01534     pushValue(I.getOperand(0), InstID, Vals, VE);         // val.
01535     Vals.push_back(Log2_32(cast<StoreInst>(I).getAlignment())+1);
01536     Vals.push_back(cast<StoreInst>(I).isVolatile());
01537     if (cast<StoreInst>(I).isAtomic()) {
01538       Vals.push_back(GetEncodedOrdering(cast<StoreInst>(I).getOrdering()));
01539       Vals.push_back(GetEncodedSynchScope(cast<StoreInst>(I).getSynchScope()));
01540     }
01541     break;
01542   case Instruction::AtomicCmpXchg:
01543     Code = bitc::FUNC_CODE_INST_CMPXCHG;
01544     PushValueAndType(I.getOperand(0), InstID, Vals, VE);  // ptrty + ptr
01545     pushValue(I.getOperand(1), InstID, Vals, VE);         // cmp.
01546     pushValue(I.getOperand(2), InstID, Vals, VE);         // newval.
01547     Vals.push_back(cast<AtomicCmpXchgInst>(I).isVolatile());
01548     Vals.push_back(GetEncodedOrdering(
01549                      cast<AtomicCmpXchgInst>(I).getSuccessOrdering()));
01550     Vals.push_back(GetEncodedSynchScope(
01551                      cast<AtomicCmpXchgInst>(I).getSynchScope()));
01552     Vals.push_back(GetEncodedOrdering(
01553                      cast<AtomicCmpXchgInst>(I).getFailureOrdering()));
01554     Vals.push_back(cast<AtomicCmpXchgInst>(I).isWeak());
01555     break;
01556   case Instruction::AtomicRMW:
01557     Code = bitc::FUNC_CODE_INST_ATOMICRMW;
01558     PushValueAndType(I.getOperand(0), InstID, Vals, VE);  // ptrty + ptr
01559     pushValue(I.getOperand(1), InstID, Vals, VE);         // val.
01560     Vals.push_back(GetEncodedRMWOperation(
01561                      cast<AtomicRMWInst>(I).getOperation()));
01562     Vals.push_back(cast<AtomicRMWInst>(I).isVolatile());
01563     Vals.push_back(GetEncodedOrdering(cast<AtomicRMWInst>(I).getOrdering()));
01564     Vals.push_back(GetEncodedSynchScope(
01565                      cast<AtomicRMWInst>(I).getSynchScope()));
01566     break;
01567   case Instruction::Fence:
01568     Code = bitc::FUNC_CODE_INST_FENCE;
01569     Vals.push_back(GetEncodedOrdering(cast<FenceInst>(I).getOrdering()));
01570     Vals.push_back(GetEncodedSynchScope(cast<FenceInst>(I).getSynchScope()));
01571     break;
01572   case Instruction::Call: {
01573     const CallInst &CI = cast<CallInst>(I);
01574     PointerType *PTy = cast<PointerType>(CI.getCalledValue()->getType());
01575     FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
01576 
01577     Code = bitc::FUNC_CODE_INST_CALL;
01578 
01579     Vals.push_back(VE.getAttributeID(CI.getAttributes()));
01580     Vals.push_back((CI.getCallingConv() << 1) | unsigned(CI.isTailCall()) |
01581                    unsigned(CI.isMustTailCall()) << 14);
01582     PushValueAndType(CI.getCalledValue(), InstID, Vals, VE);  // Callee
01583 
01584     // Emit value #'s for the fixed parameters.
01585     for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i) {
01586       // Check for labels (can happen with asm labels).
01587       if (FTy->getParamType(i)->isLabelTy())
01588         Vals.push_back(VE.getValueID(CI.getArgOperand(i)));
01589       else
01590         pushValue(CI.getArgOperand(i), InstID, Vals, VE);  // fixed param.
01591     }
01592 
01593     // Emit type/value pairs for varargs params.
01594     if (FTy->isVarArg()) {
01595       for (unsigned i = FTy->getNumParams(), e = CI.getNumArgOperands();
01596            i != e; ++i)
01597         PushValueAndType(CI.getArgOperand(i), InstID, Vals, VE);  // varargs
01598     }
01599     break;
01600   }
01601   case Instruction::VAArg:
01602     Code = bitc::FUNC_CODE_INST_VAARG;
01603     Vals.push_back(VE.getTypeID(I.getOperand(0)->getType()));   // valistty
01604     pushValue(I.getOperand(0), InstID, Vals, VE); // valist.
01605     Vals.push_back(VE.getTypeID(I.getType())); // restype.
01606     break;
01607   }
01608 
01609   Stream.EmitRecord(Code, Vals, AbbrevToUse);
01610   Vals.clear();
01611 }
01612 
01613 // Emit names for globals/functions etc.
01614 static void WriteValueSymbolTable(const ValueSymbolTable &VST,
01615                                   const ValueEnumerator &VE,
01616                                   BitstreamWriter &Stream) {
01617   if (VST.empty()) return;
01618   Stream.EnterSubblock(bitc::VALUE_SYMTAB_BLOCK_ID, 4);
01619 
01620   // FIXME: Set up the abbrev, we know how many values there are!
01621   // FIXME: We know if the type names can use 7-bit ascii.
01622   SmallVector<unsigned, 64> NameVals;
01623 
01624   for (ValueSymbolTable::const_iterator SI = VST.begin(), SE = VST.end();
01625        SI != SE; ++SI) {
01626 
01627     const ValueName &Name = *SI;
01628 
01629     // Figure out the encoding to use for the name.
01630     bool is7Bit = true;
01631     bool isChar6 = true;
01632     for (const char *C = Name.getKeyData(), *E = C+Name.getKeyLength();
01633          C != E; ++C) {
01634       if (isChar6)
01635         isChar6 = BitCodeAbbrevOp::isChar6(*C);
01636       if ((unsigned char)*C & 128) {
01637         is7Bit = false;
01638         break;  // don't bother scanning the rest.
01639       }
01640     }
01641 
01642     unsigned AbbrevToUse = VST_ENTRY_8_ABBREV;
01643 
01644     // VST_ENTRY:   [valueid, namechar x N]
01645     // VST_BBENTRY: [bbid, namechar x N]
01646     unsigned Code;
01647     if (isa<BasicBlock>(SI->getValue())) {
01648       Code = bitc::VST_CODE_BBENTRY;
01649       if (isChar6)
01650         AbbrevToUse = VST_BBENTRY_6_ABBREV;
01651     } else {
01652       Code = bitc::VST_CODE_ENTRY;
01653       if (isChar6)
01654         AbbrevToUse = VST_ENTRY_6_ABBREV;
01655       else if (is7Bit)
01656         AbbrevToUse = VST_ENTRY_7_ABBREV;
01657     }
01658 
01659     NameVals.push_back(VE.getValueID(SI->getValue()));
01660     for (const char *P = Name.getKeyData(),
01661          *E = Name.getKeyData()+Name.getKeyLength(); P != E; ++P)
01662       NameVals.push_back((unsigned char)*P);
01663 
01664     // Emit the finished record.
01665     Stream.EmitRecord(Code, NameVals, AbbrevToUse);
01666     NameVals.clear();
01667   }
01668   Stream.ExitBlock();
01669 }
01670 
01671 static void WriteUseList(ValueEnumerator &VE, UseListOrder &&Order,
01672                          BitstreamWriter &Stream) {
01673   assert(Order.Shuffle.size() >= 2 && "Shuffle too small");
01674   unsigned Code;
01675   if (isa<BasicBlock>(Order.V))
01676     Code = bitc::USELIST_CODE_BB;
01677   else
01678     Code = bitc::USELIST_CODE_DEFAULT;
01679 
01680   SmallVector<uint64_t, 64> Record;
01681   for (unsigned I : Order.Shuffle)
01682     Record.push_back(I);
01683   Record.push_back(VE.getValueID(Order.V));
01684   Stream.EmitRecord(Code, Record);
01685 }
01686 
01687 static void WriteUseListBlock(const Function *F, ValueEnumerator &VE,
01688                               BitstreamWriter &Stream) {
01689   auto hasMore = [&]() {
01690     return !VE.UseListOrders.empty() && VE.UseListOrders.back().F == F;
01691   };
01692   if (!hasMore())
01693     // Nothing to do.
01694     return;
01695 
01696   Stream.EnterSubblock(bitc::USELIST_BLOCK_ID, 3);
01697   while (hasMore()) {
01698     WriteUseList(VE, std::move(VE.UseListOrders.back()), Stream);
01699     VE.UseListOrders.pop_back();
01700   }
01701   Stream.ExitBlock();
01702 }
01703 
01704 /// WriteFunction - Emit a function body to the module stream.
01705 static void WriteFunction(const Function &F, ValueEnumerator &VE,
01706                           BitstreamWriter &Stream) {
01707   Stream.EnterSubblock(bitc::FUNCTION_BLOCK_ID, 4);
01708   VE.incorporateFunction(F);
01709 
01710   SmallVector<unsigned, 64> Vals;
01711 
01712   // Emit the number of basic blocks, so the reader can create them ahead of
01713   // time.
01714   Vals.push_back(VE.getBasicBlocks().size());
01715   Stream.EmitRecord(bitc::FUNC_CODE_DECLAREBLOCKS, Vals);
01716   Vals.clear();
01717 
01718   // If there are function-local constants, emit them now.
01719   unsigned CstStart, CstEnd;
01720   VE.getFunctionConstantRange(CstStart, CstEnd);
01721   WriteConstants(CstStart, CstEnd, VE, Stream, false);
01722 
01723   // If there is function-local metadata, emit it now.
01724   WriteFunctionLocalMetadata(F, VE, Stream);
01725 
01726   // Keep a running idea of what the instruction ID is.
01727   unsigned InstID = CstEnd;
01728 
01729   bool NeedsMetadataAttachment = false;
01730 
01731   DebugLoc LastDL;
01732 
01733   // Finally, emit all the instructions, in order.
01734   for (Function::const_iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
01735     for (BasicBlock::const_iterator I = BB->begin(), E = BB->end();
01736          I != E; ++I) {
01737       WriteInstruction(*I, InstID, VE, Stream, Vals);
01738 
01739       if (!I->getType()->isVoidTy())
01740         ++InstID;
01741 
01742       // If the instruction has metadata, write a metadata attachment later.
01743       NeedsMetadataAttachment |= I->hasMetadataOtherThanDebugLoc();
01744 
01745       // If the instruction has a debug location, emit it.
01746       DebugLoc DL = I->getDebugLoc();
01747       if (DL.isUnknown()) {
01748         // nothing todo.
01749       } else if (DL == LastDL) {
01750         // Just repeat the same debug loc as last time.
01751         Stream.EmitRecord(bitc::FUNC_CODE_DEBUG_LOC_AGAIN, Vals);
01752       } else {
01753         MDNode *Scope, *IA;
01754         DL.getScopeAndInlinedAt(Scope, IA, I->getContext());
01755         assert(Scope && "Expected valid scope");
01756 
01757         Vals.push_back(DL.getLine());
01758         Vals.push_back(DL.getCol());
01759         Vals.push_back(VE.getMetadataOrNullID(Scope));
01760         Vals.push_back(VE.getMetadataOrNullID(IA));
01761         Stream.EmitRecord(bitc::FUNC_CODE_DEBUG_LOC, Vals);
01762         Vals.clear();
01763 
01764         LastDL = DL;
01765       }
01766     }
01767 
01768   // Emit names for all the instructions etc.
01769   WriteValueSymbolTable(F.getValueSymbolTable(), VE, Stream);
01770 
01771   if (NeedsMetadataAttachment)
01772     WriteMetadataAttachment(F, VE, Stream);
01773   if (shouldPreserveBitcodeUseListOrder())
01774     WriteUseListBlock(&F, VE, Stream);
01775   VE.purgeFunction();
01776   Stream.ExitBlock();
01777 }
01778 
01779 // Emit blockinfo, which defines the standard abbreviations etc.
01780 static void WriteBlockInfo(const ValueEnumerator &VE, BitstreamWriter &Stream) {
01781   // We only want to emit block info records for blocks that have multiple
01782   // instances: CONSTANTS_BLOCK, FUNCTION_BLOCK and VALUE_SYMTAB_BLOCK.
01783   // Other blocks can define their abbrevs inline.
01784   Stream.EnterBlockInfoBlock(2);
01785 
01786   { // 8-bit fixed-width VST_ENTRY/VST_BBENTRY strings.
01787     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
01788     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 3));
01789     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
01790     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
01791     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
01792     if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID,
01793                                    Abbv) != VST_ENTRY_8_ABBREV)
01794       llvm_unreachable("Unexpected abbrev ordering!");
01795   }
01796 
01797   { // 7-bit fixed width VST_ENTRY strings.
01798     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
01799     Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_ENTRY));
01800     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
01801     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
01802     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7));
01803     if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID,
01804                                    Abbv) != VST_ENTRY_7_ABBREV)
01805       llvm_unreachable("Unexpected abbrev ordering!");
01806   }
01807   { // 6-bit char6 VST_ENTRY strings.
01808     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
01809     Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_ENTRY));
01810     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
01811     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
01812     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
01813     if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID,
01814                                    Abbv) != VST_ENTRY_6_ABBREV)
01815       llvm_unreachable("Unexpected abbrev ordering!");
01816   }
01817   { // 6-bit char6 VST_BBENTRY strings.
01818     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
01819     Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_BBENTRY));
01820     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
01821     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
01822     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
01823     if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID,
01824                                    Abbv) != VST_BBENTRY_6_ABBREV)
01825       llvm_unreachable("Unexpected abbrev ordering!");
01826   }
01827 
01828 
01829 
01830   { // SETTYPE abbrev for CONSTANTS_BLOCK.
01831     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
01832     Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_SETTYPE));
01833     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
01834                               Log2_32_Ceil(VE.getTypes().size()+1)));
01835     if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID,
01836                                    Abbv) != CONSTANTS_SETTYPE_ABBREV)
01837       llvm_unreachable("Unexpected abbrev ordering!");
01838   }
01839 
01840   { // INTEGER abbrev for CONSTANTS_BLOCK.
01841     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
01842     Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_INTEGER));
01843     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
01844     if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID,
01845                                    Abbv) != CONSTANTS_INTEGER_ABBREV)
01846       llvm_unreachable("Unexpected abbrev ordering!");
01847   }
01848 
01849   { // CE_CAST abbrev for CONSTANTS_BLOCK.
01850     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
01851     Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_CE_CAST));
01852     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4));  // cast opc
01853     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,       // typeid
01854                               Log2_32_Ceil(VE.getTypes().size()+1)));
01855     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));    // value id
01856 
01857     if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID,
01858                                    Abbv) != CONSTANTS_CE_CAST_Abbrev)
01859       llvm_unreachable("Unexpected abbrev ordering!");
01860   }
01861   { // NULL abbrev for CONSTANTS_BLOCK.
01862     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
01863     Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_NULL));
01864     if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID,
01865                                    Abbv) != CONSTANTS_NULL_Abbrev)
01866       llvm_unreachable("Unexpected abbrev ordering!");
01867   }
01868 
01869   // FIXME: This should only use space for first class types!
01870 
01871   { // INST_LOAD abbrev for FUNCTION_BLOCK.
01872     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
01873     Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_LOAD));
01874     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Ptr
01875     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // Align
01876     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // volatile
01877     if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
01878                                    Abbv) != FUNCTION_INST_LOAD_ABBREV)
01879       llvm_unreachable("Unexpected abbrev ordering!");
01880   }
01881   { // INST_BINOP abbrev for FUNCTION_BLOCK.
01882     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
01883     Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_BINOP));
01884     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // LHS
01885     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // RHS
01886     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
01887     if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
01888                                    Abbv) != FUNCTION_INST_BINOP_ABBREV)
01889       llvm_unreachable("Unexpected abbrev ordering!");
01890   }
01891   { // INST_BINOP_FLAGS abbrev for FUNCTION_BLOCK.
01892     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
01893     Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_BINOP));
01894     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // LHS
01895     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // RHS
01896     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
01897     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7)); // flags
01898     if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
01899                                    Abbv) != FUNCTION_INST_BINOP_FLAGS_ABBREV)
01900       llvm_unreachable("Unexpected abbrev ordering!");
01901   }
01902   { // INST_CAST abbrev for FUNCTION_BLOCK.
01903     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
01904     Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_CAST));
01905     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));    // OpVal
01906     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,       // dest ty
01907                               Log2_32_Ceil(VE.getTypes().size()+1)));
01908     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4));  // opc
01909     if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
01910                                    Abbv) != FUNCTION_INST_CAST_ABBREV)
01911       llvm_unreachable("Unexpected abbrev ordering!");
01912   }
01913 
01914   { // INST_RET abbrev for FUNCTION_BLOCK.
01915     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
01916     Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_RET));
01917     if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
01918                                    Abbv) != FUNCTION_INST_RET_VOID_ABBREV)
01919       llvm_unreachable("Unexpected abbrev ordering!");
01920   }
01921   { // INST_RET abbrev for FUNCTION_BLOCK.
01922     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
01923     Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_RET));
01924     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // ValID
01925     if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
01926                                    Abbv) != FUNCTION_INST_RET_VAL_ABBREV)
01927       llvm_unreachable("Unexpected abbrev ordering!");
01928   }
01929   { // INST_UNREACHABLE abbrev for FUNCTION_BLOCK.
01930     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
01931     Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_UNREACHABLE));
01932     if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
01933                                    Abbv) != FUNCTION_INST_UNREACHABLE_ABBREV)
01934       llvm_unreachable("Unexpected abbrev ordering!");
01935   }
01936 
01937   Stream.ExitBlock();
01938 }
01939 
01940 /// WriteModule - Emit the specified module to the bitstream.
01941 static void WriteModule(const Module *M, BitstreamWriter &Stream) {
01942   Stream.EnterSubblock(bitc::MODULE_BLOCK_ID, 3);
01943 
01944   SmallVector<unsigned, 1> Vals;
01945   unsigned CurVersion = 1;
01946   Vals.push_back(CurVersion);
01947   Stream.EmitRecord(bitc::MODULE_CODE_VERSION, Vals);
01948 
01949   // Analyze the module, enumerating globals, functions, etc.
01950   ValueEnumerator VE(*M);
01951 
01952   // Emit blockinfo, which defines the standard abbreviations etc.
01953   WriteBlockInfo(VE, Stream);
01954 
01955   // Emit information about attribute groups.
01956   WriteAttributeGroupTable(VE, Stream);
01957 
01958   // Emit information about parameter attributes.
01959   WriteAttributeTable(VE, Stream);
01960 
01961   // Emit information describing all of the types in the module.
01962   WriteTypeTable(VE, Stream);
01963 
01964   writeComdats(VE, Stream);
01965 
01966   // Emit top-level description of module, including target triple, inline asm,
01967   // descriptors for global variables, and function prototype info.
01968   WriteModuleInfo(M, VE, Stream);
01969 
01970   // Emit constants.
01971   WriteModuleConstants(VE, Stream);
01972 
01973   // Emit metadata.
01974   WriteModuleMetadata(M, VE, Stream);
01975 
01976   // Emit metadata.
01977   WriteModuleMetadataStore(M, Stream);
01978 
01979   // Emit names for globals/functions etc.
01980   WriteValueSymbolTable(M->getValueSymbolTable(), VE, Stream);
01981 
01982   // Emit module-level use-lists.
01983   if (shouldPreserveBitcodeUseListOrder())
01984     WriteUseListBlock(nullptr, VE, Stream);
01985 
01986   // Emit function bodies.
01987   for (Module::const_iterator F = M->begin(), E = M->end(); F != E; ++F)
01988     if (!F->isDeclaration())
01989       WriteFunction(*F, VE, Stream);
01990 
01991   Stream.ExitBlock();
01992 }
01993 
01994 /// EmitDarwinBCHeader - If generating a bc file on darwin, we have to emit a
01995 /// header and trailer to make it compatible with the system archiver.  To do
01996 /// this we emit the following header, and then emit a trailer that pads the
01997 /// file out to be a multiple of 16 bytes.
01998 ///
01999 /// struct bc_header {
02000 ///   uint32_t Magic;         // 0x0B17C0DE
02001 ///   uint32_t Version;       // Version, currently always 0.
02002 ///   uint32_t BitcodeOffset; // Offset to traditional bitcode file.
02003 ///   uint32_t BitcodeSize;   // Size of traditional bitcode file.
02004 ///   uint32_t CPUType;       // CPU specifier.
02005 ///   ... potentially more later ...
02006 /// };
02007 enum {
02008   DarwinBCSizeFieldOffset = 3*4, // Offset to bitcode_size.
02009   DarwinBCHeaderSize = 5*4
02010 };
02011 
02012 static void WriteInt32ToBuffer(uint32_t Value, SmallVectorImpl<char> &Buffer,
02013                                uint32_t &Position) {
02014   Buffer[Position + 0] = (unsigned char) (Value >>  0);
02015   Buffer[Position + 1] = (unsigned char) (Value >>  8);
02016   Buffer[Position + 2] = (unsigned char) (Value >> 16);
02017   Buffer[Position + 3] = (unsigned char) (Value >> 24);
02018   Position += 4;
02019 }
02020 
02021 static void EmitDarwinBCHeaderAndTrailer(SmallVectorImpl<char> &Buffer,
02022                                          const Triple &TT) {
02023   unsigned CPUType = ~0U;
02024 
02025   // Match x86_64-*, i[3-9]86-*, powerpc-*, powerpc64-*, arm-*, thumb-*,
02026   // armv[0-9]-*, thumbv[0-9]-*, armv5te-*, or armv6t2-*. The CPUType is a magic
02027   // number from /usr/include/mach/machine.h.  It is ok to reproduce the
02028   // specific constants here because they are implicitly part of the Darwin ABI.
02029   enum {
02030     DARWIN_CPU_ARCH_ABI64      = 0x01000000,
02031     DARWIN_CPU_TYPE_X86        = 7,
02032     DARWIN_CPU_TYPE_ARM        = 12,
02033     DARWIN_CPU_TYPE_POWERPC    = 18
02034   };
02035 
02036   Triple::ArchType Arch = TT.getArch();
02037   if (Arch == Triple::x86_64)
02038     CPUType = DARWIN_CPU_TYPE_X86 | DARWIN_CPU_ARCH_ABI64;
02039   else if (Arch == Triple::x86)
02040     CPUType = DARWIN_CPU_TYPE_X86;
02041   else if (Arch == Triple::ppc)
02042     CPUType = DARWIN_CPU_TYPE_POWERPC;
02043   else if (Arch == Triple::ppc64)
02044     CPUType = DARWIN_CPU_TYPE_POWERPC | DARWIN_CPU_ARCH_ABI64;
02045   else if (Arch == Triple::arm || Arch == Triple::thumb)
02046     CPUType = DARWIN_CPU_TYPE_ARM;
02047 
02048   // Traditional Bitcode starts after header.
02049   assert(Buffer.size() >= DarwinBCHeaderSize &&
02050          "Expected header size to be reserved");
02051   unsigned BCOffset = DarwinBCHeaderSize;
02052   unsigned BCSize = Buffer.size()-DarwinBCHeaderSize;
02053 
02054   // Write the magic and version.
02055   unsigned Position = 0;
02056   WriteInt32ToBuffer(0x0B17C0DE , Buffer, Position);
02057   WriteInt32ToBuffer(0          , Buffer, Position); // Version.
02058   WriteInt32ToBuffer(BCOffset   , Buffer, Position);
02059   WriteInt32ToBuffer(BCSize     , Buffer, Position);
02060   WriteInt32ToBuffer(CPUType    , Buffer, Position);
02061 
02062   // If the file is not a multiple of 16 bytes, insert dummy padding.
02063   while (Buffer.size() & 15)
02064     Buffer.push_back(0);
02065 }
02066 
02067 /// WriteBitcodeToFile - Write the specified module to the specified output
02068 /// stream.
02069 void llvm::WriteBitcodeToFile(const Module *M, raw_ostream &Out) {
02070   SmallVector<char, 0> Buffer;
02071   Buffer.reserve(256*1024);
02072 
02073   // If this is darwin or another generic macho target, reserve space for the
02074   // header.
02075   Triple TT(M->getTargetTriple());
02076   if (TT.isOSDarwin())
02077     Buffer.insert(Buffer.begin(), DarwinBCHeaderSize, 0);
02078 
02079   // Emit the module into the buffer.
02080   {
02081     BitstreamWriter Stream(Buffer);
02082 
02083     // Emit the file header.
02084     Stream.Emit((unsigned)'B', 8);
02085     Stream.Emit((unsigned)'C', 8);
02086     Stream.Emit(0x0, 4);
02087     Stream.Emit(0xC, 4);
02088     Stream.Emit(0xE, 4);
02089     Stream.Emit(0xD, 4);
02090 
02091     // Emit the module.
02092     WriteModule(M, Stream);
02093   }
02094 
02095   if (TT.isOSDarwin())
02096     EmitDarwinBCHeaderAndTrailer(Buffer, TT);
02097 
02098   // Write the generated bitstream to "Out".
02099   Out.write((char*)&Buffer.front(), Buffer.size());
02100 }