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