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