LLVM API Documentation

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