Home | History | Annotate | Download | only in BitWriter_2_9_func
      1 //===--- Bitcode/Writer/BitcodeWriter.cpp - Bitcode Writer ----------------===//
      2 //
      3 //                     The LLVM Compiler Infrastructure
      4 //
      5 // This file is distributed under the University of Illinois Open Source
      6 // License. See LICENSE.TXT for details.
      7 //
      8 //===----------------------------------------------------------------------===//
      9 //
     10 // Bitcode writer implementation.
     11 //
     12 //===----------------------------------------------------------------------===//
     13 
     14 #include "ReaderWriter_2_9_func.h"
     15 #include "legacy_bitcode.h"
     16 #include "ValueEnumerator.h"
     17 #include "llvm/ADT/Triple.h"
     18 #include "llvm/Bitcode/BitstreamWriter.h"
     19 #include "llvm/Bitcode/LLVMBitCodes.h"
     20 #include "llvm/IR/Constants.h"
     21 #include "llvm/IR/DerivedTypes.h"
     22 #include "llvm/IR/InlineAsm.h"
     23 #include "llvm/IR/Instructions.h"
     24 #include "llvm/IR/Module.h"
     25 #include "llvm/IR/Operator.h"
     26 #include "llvm/IR/ValueSymbolTable.h"
     27 #include "llvm/Support/ErrorHandling.h"
     28 #include "llvm/Support/MathExtras.h"
     29 #include "llvm/Support/Program.h"
     30 #include "llvm/Support/raw_ostream.h"
     31 #include <cctype>
     32 #include <map>
     33 using namespace llvm;
     34 
     35 /// These are manifest constants used by the bitcode writer. They do not need to
     36 /// be kept in sync with the reader, but need to be consistent within this file.
     37 enum {
     38   CurVersion = 0,
     39 
     40   // VALUE_SYMTAB_BLOCK abbrev id's.
     41   VST_ENTRY_8_ABBREV = bitc::FIRST_APPLICATION_ABBREV,
     42   VST_ENTRY_7_ABBREV,
     43   VST_ENTRY_6_ABBREV,
     44   VST_BBENTRY_6_ABBREV,
     45 
     46   // CONSTANTS_BLOCK abbrev id's.
     47   CONSTANTS_SETTYPE_ABBREV = bitc::FIRST_APPLICATION_ABBREV,
     48   CONSTANTS_INTEGER_ABBREV,
     49   CONSTANTS_CE_CAST_Abbrev,
     50   CONSTANTS_NULL_Abbrev,
     51 
     52   // FUNCTION_BLOCK abbrev id's.
     53   FUNCTION_INST_LOAD_ABBREV = bitc::FIRST_APPLICATION_ABBREV,
     54   FUNCTION_INST_BINOP_ABBREV,
     55   FUNCTION_INST_BINOP_FLAGS_ABBREV,
     56   FUNCTION_INST_CAST_ABBREV,
     57   FUNCTION_INST_RET_VOID_ABBREV,
     58   FUNCTION_INST_RET_VAL_ABBREV,
     59   FUNCTION_INST_UNREACHABLE_ABBREV
     60 };
     61 
     62 
     63 static unsigned GetEncodedCastOpcode(unsigned Opcode) {
     64   switch (Opcode) {
     65   default: llvm_unreachable("Unknown cast instruction!");
     66   case Instruction::Trunc   : return bitc::CAST_TRUNC;
     67   case Instruction::ZExt    : return bitc::CAST_ZEXT;
     68   case Instruction::SExt    : return bitc::CAST_SEXT;
     69   case Instruction::FPToUI  : return bitc::CAST_FPTOUI;
     70   case Instruction::FPToSI  : return bitc::CAST_FPTOSI;
     71   case Instruction::UIToFP  : return bitc::CAST_UITOFP;
     72   case Instruction::SIToFP  : return bitc::CAST_SITOFP;
     73   case Instruction::FPTrunc : return bitc::CAST_FPTRUNC;
     74   case Instruction::FPExt   : return bitc::CAST_FPEXT;
     75   case Instruction::PtrToInt: return bitc::CAST_PTRTOINT;
     76   case Instruction::IntToPtr: return bitc::CAST_INTTOPTR;
     77   case Instruction::BitCast : return bitc::CAST_BITCAST;
     78   }
     79 }
     80 
     81 static unsigned GetEncodedBinaryOpcode(unsigned Opcode) {
     82   switch (Opcode) {
     83   default: llvm_unreachable("Unknown binary instruction!");
     84   case Instruction::Add:
     85   case Instruction::FAdd: return bitc::BINOP_ADD;
     86   case Instruction::Sub:
     87   case Instruction::FSub: return bitc::BINOP_SUB;
     88   case Instruction::Mul:
     89   case Instruction::FMul: return bitc::BINOP_MUL;
     90   case Instruction::UDiv: return bitc::BINOP_UDIV;
     91   case Instruction::FDiv:
     92   case Instruction::SDiv: return bitc::BINOP_SDIV;
     93   case Instruction::URem: return bitc::BINOP_UREM;
     94   case Instruction::FRem:
     95   case Instruction::SRem: return bitc::BINOP_SREM;
     96   case Instruction::Shl:  return bitc::BINOP_SHL;
     97   case Instruction::LShr: return bitc::BINOP_LSHR;
     98   case Instruction::AShr: return bitc::BINOP_ASHR;
     99   case Instruction::And:  return bitc::BINOP_AND;
    100   case Instruction::Or:   return bitc::BINOP_OR;
    101   case Instruction::Xor:  return bitc::BINOP_XOR;
    102   }
    103 }
    104 
    105 static unsigned GetEncodedRMWOperation(AtomicRMWInst::BinOp Op) {
    106   switch (Op) {
    107   default: llvm_unreachable("Unknown RMW operation!");
    108   case AtomicRMWInst::Xchg: return bitc::RMW_XCHG;
    109   case AtomicRMWInst::Add: return bitc::RMW_ADD;
    110   case AtomicRMWInst::Sub: return bitc::RMW_SUB;
    111   case AtomicRMWInst::And: return bitc::RMW_AND;
    112   case AtomicRMWInst::Nand: return bitc::RMW_NAND;
    113   case AtomicRMWInst::Or: return bitc::RMW_OR;
    114   case AtomicRMWInst::Xor: return bitc::RMW_XOR;
    115   case AtomicRMWInst::Max: return bitc::RMW_MAX;
    116   case AtomicRMWInst::Min: return bitc::RMW_MIN;
    117   case AtomicRMWInst::UMax: return bitc::RMW_UMAX;
    118   case AtomicRMWInst::UMin: return bitc::RMW_UMIN;
    119   }
    120 }
    121 
    122 static unsigned GetEncodedOrdering(AtomicOrdering Ordering) {
    123   switch (Ordering) {
    124   default: llvm_unreachable("Unknown atomic ordering");
    125   case NotAtomic: return bitc::ORDERING_NOTATOMIC;
    126   case Unordered: return bitc::ORDERING_UNORDERED;
    127   case Monotonic: return bitc::ORDERING_MONOTONIC;
    128   case Acquire: return bitc::ORDERING_ACQUIRE;
    129   case Release: return bitc::ORDERING_RELEASE;
    130   case AcquireRelease: return bitc::ORDERING_ACQREL;
    131   case SequentiallyConsistent: return bitc::ORDERING_SEQCST;
    132   }
    133 }
    134 
    135 static unsigned GetEncodedSynchScope(SynchronizationScope SynchScope) {
    136   switch (SynchScope) {
    137   default: llvm_unreachable("Unknown synchronization scope");
    138   case SingleThread: return bitc::SYNCHSCOPE_SINGLETHREAD;
    139   case CrossThread: return bitc::SYNCHSCOPE_CROSSTHREAD;
    140   }
    141 }
    142 
    143 static void WriteStringRecord(unsigned Code, StringRef Str,
    144                               unsigned AbbrevToUse, BitstreamWriter &Stream) {
    145   SmallVector<unsigned, 64> Vals;
    146 
    147   // Code: [strchar x N]
    148   for (unsigned i = 0, e = Str.size(); i != e; ++i) {
    149     if (AbbrevToUse && !BitCodeAbbrevOp::isChar6(Str[i]))
    150       AbbrevToUse = 0;
    151     Vals.push_back(Str[i]);
    152   }
    153 
    154   // Emit the finished record.
    155   Stream.EmitRecord(Code, Vals, AbbrevToUse);
    156 }
    157 
    158 // Emit information about parameter attributes.
    159 static void WriteAttributeTable(const llvm_2_9_func::ValueEnumerator &VE,
    160                                 BitstreamWriter &Stream) {
    161   const std::vector<AttributeSet> &Attrs = VE.getAttributes();
    162   if (Attrs.empty()) return;
    163 
    164   Stream.EnterSubblock(bitc::PARAMATTR_BLOCK_ID, 3);
    165 
    166   SmallVector<uint64_t, 64> Record;
    167   for (unsigned i = 0, e = Attrs.size(); i != e; ++i) {
    168     const AttributeSet &A = Attrs[i];
    169     for (unsigned i = 0, e = A.getNumSlots(); i != e; ++i) {
    170       Record.push_back(A.getSlotIndex(i));
    171       Record.push_back(encodeLLVMAttributesForBitcode(A, A.getSlotIndex(i)));
    172     }
    173 
    174     // This needs to use the 3.2 entry type
    175     Stream.EmitRecord(bitc::PARAMATTR_CODE_ENTRY_OLD, Record);
    176     Record.clear();
    177   }
    178 
    179   Stream.ExitBlock();
    180 }
    181 
    182 /// WriteTypeTable - Write out the type table for a module.
    183 static void WriteTypeTable(const llvm_2_9_func::ValueEnumerator &VE,
    184                            BitstreamWriter &Stream) {
    185   const llvm_2_9_func::ValueEnumerator::TypeList &TypeList = VE.getTypes();
    186 
    187   Stream.EnterSubblock(bitc::TYPE_BLOCK_ID_NEW, 4 /*count from # abbrevs */);
    188   SmallVector<uint64_t, 64> TypeVals;
    189 
    190   // Abbrev for TYPE_CODE_POINTER.
    191   BitCodeAbbrev *Abbv = new BitCodeAbbrev();
    192   Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_POINTER));
    193   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
    194                             Log2_32_Ceil(VE.getTypes().size()+1)));
    195   Abbv->Add(BitCodeAbbrevOp(0));  // Addrspace = 0
    196   unsigned PtrAbbrev = Stream.EmitAbbrev(Abbv);
    197 
    198   // Abbrev for TYPE_CODE_FUNCTION.
    199   Abbv = new BitCodeAbbrev();
    200   Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_FUNCTION_OLD));
    201   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));  // isvararg
    202   Abbv->Add(BitCodeAbbrevOp(0));  // FIXME: DEAD value, remove in LLVM 3.0
    203   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
    204   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
    205                             Log2_32_Ceil(VE.getTypes().size()+1)));
    206   unsigned FunctionAbbrev = Stream.EmitAbbrev(Abbv);
    207 
    208   // Abbrev for TYPE_CODE_STRUCT_ANON.
    209   Abbv = new BitCodeAbbrev();
    210   Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_STRUCT_ANON));
    211   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));  // ispacked
    212   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
    213   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
    214                             Log2_32_Ceil(VE.getTypes().size()+1)));
    215   unsigned StructAnonAbbrev = Stream.EmitAbbrev(Abbv);
    216 
    217   // Abbrev for TYPE_CODE_STRUCT_NAME.
    218   Abbv = new BitCodeAbbrev();
    219   Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_STRUCT_NAME));
    220   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
    221   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
    222   unsigned StructNameAbbrev = Stream.EmitAbbrev(Abbv);
    223 
    224   // Abbrev for TYPE_CODE_STRUCT_NAMED.
    225   Abbv = new BitCodeAbbrev();
    226   Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_STRUCT_NAMED));
    227   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));  // ispacked
    228   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
    229   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
    230                             Log2_32_Ceil(VE.getTypes().size()+1)));
    231   unsigned StructNamedAbbrev = Stream.EmitAbbrev(Abbv);
    232 
    233   // Abbrev for TYPE_CODE_ARRAY.
    234   Abbv = new BitCodeAbbrev();
    235   Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_ARRAY));
    236   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));   // size
    237   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
    238                             Log2_32_Ceil(VE.getTypes().size()+1)));
    239   unsigned ArrayAbbrev = Stream.EmitAbbrev(Abbv);
    240 
    241   // Emit an entry count so the reader can reserve space.
    242   TypeVals.push_back(TypeList.size());
    243   Stream.EmitRecord(bitc::TYPE_CODE_NUMENTRY, TypeVals);
    244   TypeVals.clear();
    245 
    246   // Loop over all of the types, emitting each in turn.
    247   for (unsigned i = 0, e = TypeList.size(); i != e; ++i) {
    248     Type *T = TypeList[i];
    249     int AbbrevToUse = 0;
    250     unsigned Code = 0;
    251 
    252     switch (T->getTypeID()) {
    253     default: llvm_unreachable("Unknown type!");
    254     case Type::VoidTyID:      Code = bitc::TYPE_CODE_VOID;   break;
    255     case Type::FloatTyID:     Code = bitc::TYPE_CODE_FLOAT;  break;
    256     case Type::DoubleTyID:    Code = bitc::TYPE_CODE_DOUBLE; break;
    257     case Type::X86_FP80TyID:  Code = bitc::TYPE_CODE_X86_FP80; break;
    258     case Type::FP128TyID:     Code = bitc::TYPE_CODE_FP128; break;
    259     case Type::PPC_FP128TyID: Code = bitc::TYPE_CODE_PPC_FP128; break;
    260     case Type::LabelTyID:     Code = bitc::TYPE_CODE_LABEL;  break;
    261     case Type::MetadataTyID:  Code = bitc::TYPE_CODE_METADATA; break;
    262     case Type::X86_MMXTyID:   Code = bitc::TYPE_CODE_X86_MMX; break;
    263     case Type::IntegerTyID:
    264       // INTEGER: [width]
    265       Code = bitc::TYPE_CODE_INTEGER;
    266       TypeVals.push_back(cast<IntegerType>(T)->getBitWidth());
    267       break;
    268     case Type::PointerTyID: {
    269       PointerType *PTy = cast<PointerType>(T);
    270       // POINTER: [pointee type, address space]
    271       Code = bitc::TYPE_CODE_POINTER;
    272       TypeVals.push_back(VE.getTypeID(PTy->getElementType()));
    273       unsigned AddressSpace = PTy->getAddressSpace();
    274       TypeVals.push_back(AddressSpace);
    275       if (AddressSpace == 0) AbbrevToUse = PtrAbbrev;
    276       break;
    277     }
    278     case Type::FunctionTyID: {
    279       FunctionType *FT = cast<FunctionType>(T);
    280       // FUNCTION: [isvararg, attrid, retty, paramty x N]
    281       Code = bitc::TYPE_CODE_FUNCTION_OLD;
    282       TypeVals.push_back(FT->isVarArg());
    283       TypeVals.push_back(0);  // FIXME: DEAD: remove in llvm 3.0
    284       TypeVals.push_back(VE.getTypeID(FT->getReturnType()));
    285       for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i)
    286         TypeVals.push_back(VE.getTypeID(FT->getParamType(i)));
    287       AbbrevToUse = FunctionAbbrev;
    288       break;
    289     }
    290     case Type::StructTyID: {
    291       StructType *ST = cast<StructType>(T);
    292       // STRUCT: [ispacked, eltty x N]
    293       TypeVals.push_back(ST->isPacked());
    294       // Output all of the element types.
    295       for (StructType::element_iterator I = ST->element_begin(),
    296            E = ST->element_end(); I != E; ++I)
    297         TypeVals.push_back(VE.getTypeID(*I));
    298 
    299       if (ST->isLiteral()) {
    300         Code = bitc::TYPE_CODE_STRUCT_ANON;
    301         AbbrevToUse = StructAnonAbbrev;
    302       } else {
    303         if (ST->isOpaque()) {
    304           Code = bitc::TYPE_CODE_OPAQUE;
    305         } else {
    306           Code = bitc::TYPE_CODE_STRUCT_NAMED;
    307           AbbrevToUse = StructNamedAbbrev;
    308         }
    309 
    310         // Emit the name if it is present.
    311         if (!ST->getName().empty())
    312           WriteStringRecord(bitc::TYPE_CODE_STRUCT_NAME, ST->getName(),
    313                             StructNameAbbrev, Stream);
    314       }
    315       break;
    316     }
    317     case Type::ArrayTyID: {
    318       ArrayType *AT = cast<ArrayType>(T);
    319       // ARRAY: [numelts, eltty]
    320       Code = bitc::TYPE_CODE_ARRAY;
    321       TypeVals.push_back(AT->getNumElements());
    322       TypeVals.push_back(VE.getTypeID(AT->getElementType()));
    323       AbbrevToUse = ArrayAbbrev;
    324       break;
    325     }
    326     case Type::VectorTyID: {
    327       VectorType *VT = cast<VectorType>(T);
    328       // VECTOR [numelts, eltty]
    329       Code = bitc::TYPE_CODE_VECTOR;
    330       TypeVals.push_back(VT->getNumElements());
    331       TypeVals.push_back(VE.getTypeID(VT->getElementType()));
    332       break;
    333     }
    334     }
    335 
    336     // Emit the finished record.
    337     Stream.EmitRecord(Code, TypeVals, AbbrevToUse);
    338     TypeVals.clear();
    339   }
    340 
    341   Stream.ExitBlock();
    342 }
    343 
    344 static unsigned getEncodedLinkage(const GlobalValue *GV) {
    345   switch (GV->getLinkage()) {
    346   case GlobalValue::ExternalLinkage:                 return 0;
    347   case GlobalValue::WeakAnyLinkage:                  return 1;
    348   case GlobalValue::AppendingLinkage:                return 2;
    349   case GlobalValue::InternalLinkage:                 return 3;
    350   case GlobalValue::LinkOnceAnyLinkage:              return 4;
    351   case GlobalValue::DLLImportLinkage:                return 5;
    352   case GlobalValue::DLLExportLinkage:                return 6;
    353   case GlobalValue::ExternalWeakLinkage:             return 7;
    354   case GlobalValue::CommonLinkage:                   return 8;
    355   case GlobalValue::PrivateLinkage:                  return 9;
    356   case GlobalValue::WeakODRLinkage:                  return 10;
    357   case GlobalValue::LinkOnceODRLinkage:              return 11;
    358   case GlobalValue::AvailableExternallyLinkage:      return 12;
    359   case GlobalValue::LinkerPrivateLinkage:            return 13;
    360   case GlobalValue::LinkerPrivateWeakLinkage:        return 14;
    361   case GlobalValue::LinkOnceODRAutoHideLinkage:      return 15;
    362   }
    363   llvm_unreachable("Invalid linkage");
    364 }
    365 
    366 static unsigned getEncodedVisibility(const GlobalValue *GV) {
    367   switch (GV->getVisibility()) {
    368   default: llvm_unreachable("Invalid visibility!");
    369   case GlobalValue::DefaultVisibility:   return 0;
    370   case GlobalValue::HiddenVisibility:    return 1;
    371   case GlobalValue::ProtectedVisibility: return 2;
    372   }
    373 }
    374 
    375 // Emit top-level description of module, including target triple, inline asm,
    376 // descriptors for global variables, and function prototype info.
    377 static void WriteModuleInfo(const Module *M,
    378                             const llvm_2_9_func::ValueEnumerator &VE,
    379                             BitstreamWriter &Stream) {
    380   // Emit various pieces of data attached to a module.
    381   if (!M->getTargetTriple().empty())
    382     WriteStringRecord(bitc::MODULE_CODE_TRIPLE, M->getTargetTriple(),
    383                       0/*TODO*/, Stream);
    384   if (!M->getDataLayout().empty())
    385     WriteStringRecord(bitc::MODULE_CODE_DATALAYOUT, M->getDataLayout(),
    386                       0/*TODO*/, Stream);
    387   if (!M->getModuleInlineAsm().empty())
    388     WriteStringRecord(bitc::MODULE_CODE_ASM, M->getModuleInlineAsm(),
    389                       0/*TODO*/, Stream);
    390 
    391   // Emit information about sections and GC, computing how many there are. Also
    392   // compute the maximum alignment value.
    393   std::map<std::string, unsigned> SectionMap;
    394   std::map<std::string, unsigned> GCMap;
    395   unsigned MaxAlignment = 0;
    396   unsigned MaxGlobalType = 0;
    397   for (Module::const_global_iterator GV = M->global_begin(),E = M->global_end();
    398        GV != E; ++GV) {
    399     MaxAlignment = std::max(MaxAlignment, GV->getAlignment());
    400     MaxGlobalType = std::max(MaxGlobalType, VE.getTypeID(GV->getType()));
    401 
    402     if (!GV->hasSection()) continue;
    403     // Give section names unique ID's.
    404     unsigned &Entry = SectionMap[GV->getSection()];
    405     if (Entry != 0) continue;
    406     WriteStringRecord(bitc::MODULE_CODE_SECTIONNAME, GV->getSection(),
    407                       0/*TODO*/, Stream);
    408     Entry = SectionMap.size();
    409   }
    410   for (Module::const_iterator F = M->begin(), E = M->end(); F != E; ++F) {
    411     MaxAlignment = std::max(MaxAlignment, F->getAlignment());
    412     if (F->hasSection()) {
    413       // Give section names unique ID's.
    414       unsigned &Entry = SectionMap[F->getSection()];
    415       if (!Entry) {
    416         WriteStringRecord(bitc::MODULE_CODE_SECTIONNAME, F->getSection(),
    417                           0/*TODO*/, Stream);
    418         Entry = SectionMap.size();
    419       }
    420     }
    421     if (F->hasGC()) {
    422       // Same for GC names.
    423       unsigned &Entry = GCMap[F->getGC()];
    424       if (!Entry) {
    425         WriteStringRecord(bitc::MODULE_CODE_GCNAME, F->getGC(),
    426                           0/*TODO*/, Stream);
    427         Entry = GCMap.size();
    428       }
    429     }
    430   }
    431 
    432   // Emit abbrev for globals, now that we know # sections and max alignment.
    433   unsigned SimpleGVarAbbrev = 0;
    434   if (!M->global_empty()) {
    435     // Add an abbrev for common globals with no visibility or thread localness.
    436     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
    437     Abbv->Add(BitCodeAbbrevOp(bitc::MODULE_CODE_GLOBALVAR));
    438     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
    439                               Log2_32_Ceil(MaxGlobalType+1)));
    440     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));      // Constant.
    441     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));        // Initializer.
    442     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4));      // Linkage.
    443     if (MaxAlignment == 0)                                      // Alignment.
    444       Abbv->Add(BitCodeAbbrevOp(0));
    445     else {
    446       unsigned MaxEncAlignment = Log2_32(MaxAlignment)+1;
    447       Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
    448                                Log2_32_Ceil(MaxEncAlignment+1)));
    449     }
    450     if (SectionMap.empty())                                    // Section.
    451       Abbv->Add(BitCodeAbbrevOp(0));
    452     else
    453       Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
    454                                Log2_32_Ceil(SectionMap.size()+1)));
    455     // Don't bother emitting vis + thread local.
    456     SimpleGVarAbbrev = Stream.EmitAbbrev(Abbv);
    457   }
    458 
    459   // Emit the global variable information.
    460   SmallVector<unsigned, 64> Vals;
    461   for (Module::const_global_iterator GV = M->global_begin(),E = M->global_end();
    462        GV != E; ++GV) {
    463     unsigned AbbrevToUse = 0;
    464 
    465     // GLOBALVAR: [type, isconst, initid,
    466     //             linkage, alignment, section, visibility, threadlocal,
    467     //             unnamed_addr]
    468     Vals.push_back(VE.getTypeID(GV->getType()));
    469     Vals.push_back(GV->isConstant());
    470     Vals.push_back(GV->isDeclaration() ? 0 :
    471                    (VE.getValueID(GV->getInitializer()) + 1));
    472     Vals.push_back(getEncodedLinkage(GV));
    473     Vals.push_back(Log2_32(GV->getAlignment())+1);
    474     Vals.push_back(GV->hasSection() ? SectionMap[GV->getSection()] : 0);
    475     if (GV->isThreadLocal() ||
    476         GV->getVisibility() != GlobalValue::DefaultVisibility ||
    477         GV->hasUnnamedAddr()) {
    478       Vals.push_back(getEncodedVisibility(GV));
    479       Vals.push_back(GV->isThreadLocal());
    480       Vals.push_back(GV->hasUnnamedAddr());
    481     } else {
    482       AbbrevToUse = SimpleGVarAbbrev;
    483     }
    484 
    485     Stream.EmitRecord(bitc::MODULE_CODE_GLOBALVAR, Vals, AbbrevToUse);
    486     Vals.clear();
    487   }
    488 
    489   // Emit the function proto information.
    490   for (Module::const_iterator F = M->begin(), E = M->end(); F != E; ++F) {
    491     // FUNCTION:  [type, callingconv, isproto, paramattr,
    492     //             linkage, alignment, section, visibility, gc, unnamed_addr]
    493     Vals.push_back(VE.getTypeID(F->getType()));
    494     Vals.push_back(F->getCallingConv());
    495     Vals.push_back(F->isDeclaration());
    496     Vals.push_back(getEncodedLinkage(F));
    497     Vals.push_back(VE.getAttributeID(F->getAttributes()));
    498     Vals.push_back(Log2_32(F->getAlignment())+1);
    499     Vals.push_back(F->hasSection() ? SectionMap[F->getSection()] : 0);
    500     Vals.push_back(getEncodedVisibility(F));
    501     Vals.push_back(F->hasGC() ? GCMap[F->getGC()] : 0);
    502     Vals.push_back(F->hasUnnamedAddr());
    503 
    504     unsigned AbbrevToUse = 0;
    505     Stream.EmitRecord(bitc::MODULE_CODE_FUNCTION, Vals, AbbrevToUse);
    506     Vals.clear();
    507   }
    508 
    509   // Emit the alias information.
    510   for (Module::const_alias_iterator AI = M->alias_begin(), E = M->alias_end();
    511        AI != E; ++AI) {
    512     Vals.push_back(VE.getTypeID(AI->getType()));
    513     Vals.push_back(VE.getValueID(AI->getAliasee()));
    514     Vals.push_back(getEncodedLinkage(AI));
    515     Vals.push_back(getEncodedVisibility(AI));
    516     unsigned AbbrevToUse = 0;
    517     Stream.EmitRecord(bitc::MODULE_CODE_ALIAS, Vals, AbbrevToUse);
    518     Vals.clear();
    519   }
    520 }
    521 
    522 static uint64_t GetOptimizationFlags(const Value *V) {
    523   uint64_t Flags = 0;
    524 
    525   if (const OverflowingBinaryOperator *OBO =
    526         dyn_cast<OverflowingBinaryOperator>(V)) {
    527     if (OBO->hasNoSignedWrap())
    528       Flags |= 1 << bitc::OBO_NO_SIGNED_WRAP;
    529     if (OBO->hasNoUnsignedWrap())
    530       Flags |= 1 << bitc::OBO_NO_UNSIGNED_WRAP;
    531   } else if (const PossiblyExactOperator *PEO =
    532                dyn_cast<PossiblyExactOperator>(V)) {
    533     if (PEO->isExact())
    534       Flags |= 1 << bitc::PEO_EXACT;
    535   }
    536 
    537   return Flags;
    538 }
    539 
    540 static void WriteMDNode(const MDNode *N,
    541                         const llvm_2_9_func::ValueEnumerator &VE,
    542                         BitstreamWriter &Stream,
    543                         SmallVector<uint64_t, 64> &Record) {
    544   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
    545     if (N->getOperand(i)) {
    546       Record.push_back(VE.getTypeID(N->getOperand(i)->getType()));
    547       Record.push_back(VE.getValueID(N->getOperand(i)));
    548     } else {
    549       Record.push_back(VE.getTypeID(Type::getVoidTy(N->getContext())));
    550       Record.push_back(0);
    551     }
    552   }
    553   unsigned MDCode = N->isFunctionLocal() ? bitc::METADATA_FN_NODE :
    554                                            bitc::METADATA_NODE;
    555   Stream.EmitRecord(MDCode, Record, 0);
    556   Record.clear();
    557 }
    558 
    559 static void WriteModuleMetadata(const Module *M,
    560                                 const llvm_2_9_func::ValueEnumerator &VE,
    561                                 BitstreamWriter &Stream) {
    562   const llvm_2_9_func::ValueEnumerator::ValueList &Vals = VE.getMDValues();
    563   bool StartedMetadataBlock = false;
    564   unsigned MDSAbbrev = 0;
    565   SmallVector<uint64_t, 64> Record;
    566   for (unsigned i = 0, e = Vals.size(); i != e; ++i) {
    567 
    568     if (const MDNode *N = dyn_cast<MDNode>(Vals[i].first)) {
    569       if (!N->isFunctionLocal() || !N->getFunction()) {
    570         if (!StartedMetadataBlock) {
    571           Stream.EnterSubblock(bitc::METADATA_BLOCK_ID, 3);
    572           StartedMetadataBlock = true;
    573         }
    574         WriteMDNode(N, VE, Stream, Record);
    575       }
    576     } else if (const MDString *MDS = dyn_cast<MDString>(Vals[i].first)) {
    577       if (!StartedMetadataBlock)  {
    578         Stream.EnterSubblock(bitc::METADATA_BLOCK_ID, 3);
    579 
    580         // Abbrev for METADATA_STRING.
    581         BitCodeAbbrev *Abbv = new BitCodeAbbrev();
    582         Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_STRING));
    583         Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
    584         Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
    585         MDSAbbrev = Stream.EmitAbbrev(Abbv);
    586         StartedMetadataBlock = true;
    587       }
    588 
    589       // Code: [strchar x N]
    590       Record.append(MDS->begin(), MDS->end());
    591 
    592       // Emit the finished record.
    593       Stream.EmitRecord(bitc::METADATA_STRING, Record, MDSAbbrev);
    594       Record.clear();
    595     }
    596   }
    597 
    598   // Write named metadata.
    599   for (Module::const_named_metadata_iterator I = M->named_metadata_begin(),
    600        E = M->named_metadata_end(); I != E; ++I) {
    601     const NamedMDNode *NMD = I;
    602     if (!StartedMetadataBlock)  {
    603       Stream.EnterSubblock(bitc::METADATA_BLOCK_ID, 3);
    604       StartedMetadataBlock = true;
    605     }
    606 
    607     // Write name.
    608     StringRef Str = NMD->getName();
    609     for (unsigned i = 0, e = Str.size(); i != e; ++i)
    610       Record.push_back(Str[i]);
    611     Stream.EmitRecord(bitc::METADATA_NAME, Record, 0/*TODO*/);
    612     Record.clear();
    613 
    614     // Write named metadata operands.
    615     for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i)
    616       Record.push_back(VE.getValueID(NMD->getOperand(i)));
    617     Stream.EmitRecord(bitc::METADATA_NAMED_NODE, Record, 0);
    618     Record.clear();
    619   }
    620 
    621   if (StartedMetadataBlock)
    622     Stream.ExitBlock();
    623 }
    624 
    625 static void WriteFunctionLocalMetadata(const Function &F,
    626                                        const llvm_2_9_func::ValueEnumerator &VE,
    627                                        BitstreamWriter &Stream) {
    628   bool StartedMetadataBlock = false;
    629   SmallVector<uint64_t, 64> Record;
    630   const SmallVector<const MDNode *, 8> &Vals = VE.getFunctionLocalMDValues();
    631   for (unsigned i = 0, e = Vals.size(); i != e; ++i)
    632     if (const MDNode *N = Vals[i])
    633       if (N->isFunctionLocal() && N->getFunction() == &F) {
    634         if (!StartedMetadataBlock) {
    635           Stream.EnterSubblock(bitc::METADATA_BLOCK_ID, 3);
    636           StartedMetadataBlock = true;
    637         }
    638         WriteMDNode(N, VE, Stream, Record);
    639       }
    640 
    641   if (StartedMetadataBlock)
    642     Stream.ExitBlock();
    643 }
    644 
    645 static void WriteMetadataAttachment(const Function &F,
    646                                     const llvm_2_9_func::ValueEnumerator &VE,
    647                                     BitstreamWriter &Stream) {
    648   Stream.EnterSubblock(bitc::METADATA_ATTACHMENT_ID, 3);
    649 
    650   SmallVector<uint64_t, 64> Record;
    651 
    652   // Write metadata attachments
    653   // METADATA_ATTACHMENT - [m x [value, [n x [id, mdnode]]]
    654   SmallVector<std::pair<unsigned, MDNode*>, 4> MDs;
    655 
    656   for (Function::const_iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
    657     for (BasicBlock::const_iterator I = BB->begin(), E = BB->end();
    658          I != E; ++I) {
    659       MDs.clear();
    660       I->getAllMetadataOtherThanDebugLoc(MDs);
    661 
    662       // If no metadata, ignore instruction.
    663       if (MDs.empty()) continue;
    664 
    665       Record.push_back(VE.getInstructionID(I));
    666 
    667       for (unsigned i = 0, e = MDs.size(); i != e; ++i) {
    668         Record.push_back(MDs[i].first);
    669         Record.push_back(VE.getValueID(MDs[i].second));
    670       }
    671       Stream.EmitRecord(bitc::METADATA_ATTACHMENT, Record, 0);
    672       Record.clear();
    673     }
    674 
    675   Stream.ExitBlock();
    676 }
    677 
    678 static void WriteModuleMetadataStore(const Module *M, BitstreamWriter &Stream) {
    679   SmallVector<uint64_t, 64> Record;
    680 
    681   // Write metadata kinds
    682   // METADATA_KIND - [n x [id, name]]
    683   SmallVector<StringRef, 4> Names;
    684   M->getMDKindNames(Names);
    685 
    686   if (Names.empty()) return;
    687 
    688   Stream.EnterSubblock(bitc::METADATA_BLOCK_ID, 3);
    689 
    690   for (unsigned MDKindID = 0, e = Names.size(); MDKindID != e; ++MDKindID) {
    691     Record.push_back(MDKindID);
    692     StringRef KName = Names[MDKindID];
    693     Record.append(KName.begin(), KName.end());
    694 
    695     Stream.EmitRecord(bitc::METADATA_KIND, Record, 0);
    696     Record.clear();
    697   }
    698 
    699   Stream.ExitBlock();
    700 }
    701 
    702 static void WriteConstants(unsigned FirstVal, unsigned LastVal,
    703                            const llvm_2_9_func::ValueEnumerator &VE,
    704                            BitstreamWriter &Stream, bool isGlobal) {
    705   if (FirstVal == LastVal) return;
    706 
    707   Stream.EnterSubblock(bitc::CONSTANTS_BLOCK_ID, 4);
    708 
    709   unsigned AggregateAbbrev = 0;
    710   unsigned String8Abbrev = 0;
    711   unsigned CString7Abbrev = 0;
    712   unsigned CString6Abbrev = 0;
    713   // If this is a constant pool for the module, emit module-specific abbrevs.
    714   if (isGlobal) {
    715     // Abbrev for CST_CODE_AGGREGATE.
    716     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
    717     Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_AGGREGATE));
    718     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
    719     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, Log2_32_Ceil(LastVal+1)));
    720     AggregateAbbrev = Stream.EmitAbbrev(Abbv);
    721 
    722     // Abbrev for CST_CODE_STRING.
    723     Abbv = new BitCodeAbbrev();
    724     Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_STRING));
    725     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
    726     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
    727     String8Abbrev = Stream.EmitAbbrev(Abbv);
    728     // Abbrev for CST_CODE_CSTRING.
    729     Abbv = new BitCodeAbbrev();
    730     Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_CSTRING));
    731     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
    732     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7));
    733     CString7Abbrev = Stream.EmitAbbrev(Abbv);
    734     // Abbrev for CST_CODE_CSTRING.
    735     Abbv = new BitCodeAbbrev();
    736     Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_CSTRING));
    737     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
    738     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
    739     CString6Abbrev = Stream.EmitAbbrev(Abbv);
    740   }
    741 
    742   SmallVector<uint64_t, 64> Record;
    743 
    744   const llvm_2_9_func::ValueEnumerator::ValueList &Vals = VE.getValues();
    745   Type *LastTy = 0;
    746   for (unsigned i = FirstVal; i != LastVal; ++i) {
    747     const Value *V = Vals[i].first;
    748     // If we need to switch types, do so now.
    749     if (V->getType() != LastTy) {
    750       LastTy = V->getType();
    751       Record.push_back(VE.getTypeID(LastTy));
    752       Stream.EmitRecord(bitc::CST_CODE_SETTYPE, Record,
    753                         CONSTANTS_SETTYPE_ABBREV);
    754       Record.clear();
    755     }
    756 
    757     if (const InlineAsm *IA = dyn_cast<InlineAsm>(V)) {
    758       Record.push_back(unsigned(IA->hasSideEffects()) |
    759                        unsigned(IA->isAlignStack()) << 1);
    760 
    761       // Add the asm string.
    762       const std::string &AsmStr = IA->getAsmString();
    763       Record.push_back(AsmStr.size());
    764       for (unsigned i = 0, e = AsmStr.size(); i != e; ++i)
    765         Record.push_back(AsmStr[i]);
    766 
    767       // Add the constraint string.
    768       const std::string &ConstraintStr = IA->getConstraintString();
    769       Record.push_back(ConstraintStr.size());
    770       for (unsigned i = 0, e = ConstraintStr.size(); i != e; ++i)
    771         Record.push_back(ConstraintStr[i]);
    772       Stream.EmitRecord(bitc::CST_CODE_INLINEASM, Record);
    773       Record.clear();
    774       continue;
    775     }
    776     const Constant *C = cast<Constant>(V);
    777     unsigned Code = -1U;
    778     unsigned AbbrevToUse = 0;
    779     if (C->isNullValue()) {
    780       Code = bitc::CST_CODE_NULL;
    781     } else if (isa<UndefValue>(C)) {
    782       Code = bitc::CST_CODE_UNDEF;
    783     } else if (const ConstantInt *IV = dyn_cast<ConstantInt>(C)) {
    784       if (IV->getBitWidth() <= 64) {
    785         uint64_t V = IV->getSExtValue();
    786         if ((int64_t)V >= 0)
    787           Record.push_back(V << 1);
    788         else
    789           Record.push_back((-V << 1) | 1);
    790         Code = bitc::CST_CODE_INTEGER;
    791         AbbrevToUse = CONSTANTS_INTEGER_ABBREV;
    792       } else {                             // Wide integers, > 64 bits in size.
    793         // We have an arbitrary precision integer value to write whose
    794         // bit width is > 64. However, in canonical unsigned integer
    795         // format it is likely that the high bits are going to be zero.
    796         // So, we only write the number of active words.
    797         unsigned NWords = IV->getValue().getActiveWords();
    798         const uint64_t *RawWords = IV->getValue().getRawData();
    799         for (unsigned i = 0; i != NWords; ++i) {
    800           int64_t V = RawWords[i];
    801           if (V >= 0)
    802             Record.push_back(V << 1);
    803           else
    804             Record.push_back((-V << 1) | 1);
    805         }
    806         Code = bitc::CST_CODE_WIDE_INTEGER;
    807       }
    808     } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
    809       Code = bitc::CST_CODE_FLOAT;
    810       Type *Ty = CFP->getType();
    811       if (Ty->isFloatTy() || Ty->isDoubleTy()) {
    812         Record.push_back(CFP->getValueAPF().bitcastToAPInt().getZExtValue());
    813       } else if (Ty->isX86_FP80Ty()) {
    814         // api needed to prevent premature destruction
    815         // bits are not in the same order as a normal i80 APInt, compensate.
    816         APInt api = CFP->getValueAPF().bitcastToAPInt();
    817         const uint64_t *p = api.getRawData();
    818         Record.push_back((p[1] << 48) | (p[0] >> 16));
    819         Record.push_back(p[0] & 0xffffLL);
    820       } else if (Ty->isFP128Ty() || Ty->isPPC_FP128Ty()) {
    821         APInt api = CFP->getValueAPF().bitcastToAPInt();
    822         const uint64_t *p = api.getRawData();
    823         Record.push_back(p[0]);
    824         Record.push_back(p[1]);
    825       } else {
    826         assert (0 && "Unknown FP type!");
    827       }
    828     } else if (isa<ConstantDataSequential>(C) &&
    829                cast<ConstantDataSequential>(C)->isString()) {
    830       const ConstantDataSequential *Str = cast<ConstantDataSequential>(C);
    831       // Emit constant strings specially.
    832       unsigned NumElts = Str->getNumElements();
    833       // If this is a null-terminated string, use the denser CSTRING encoding.
    834       if (Str->isCString()) {
    835         Code = bitc::CST_CODE_CSTRING;
    836         --NumElts;  // Don't encode the null, which isn't allowed by char6.
    837       } else {
    838         Code = bitc::CST_CODE_STRING;
    839         AbbrevToUse = String8Abbrev;
    840       }
    841       bool isCStr7 = Code == bitc::CST_CODE_CSTRING;
    842       bool isCStrChar6 = Code == bitc::CST_CODE_CSTRING;
    843       for (unsigned i = 0; i != NumElts; ++i) {
    844         unsigned char V = Str->getElementAsInteger(i);
    845         Record.push_back(V);
    846         isCStr7 &= (V & 128) == 0;
    847         if (isCStrChar6)
    848           isCStrChar6 = BitCodeAbbrevOp::isChar6(V);
    849       }
    850 
    851       if (isCStrChar6)
    852         AbbrevToUse = CString6Abbrev;
    853       else if (isCStr7)
    854         AbbrevToUse = CString7Abbrev;
    855     } else if (const ConstantDataSequential *CDS =
    856                   dyn_cast<ConstantDataSequential>(C)) {
    857       // We must replace ConstantDataSequential's representation with the
    858       // legacy ConstantArray/ConstantVector/ConstantStruct version.
    859       // ValueEnumerator is similarly modified to mark the appropriate
    860       // Constants as used (so they are emitted).
    861       Code = bitc::CST_CODE_AGGREGATE;
    862       for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i)
    863         Record.push_back(VE.getValueID(CDS->getElementAsConstant(i)));
    864       AbbrevToUse = AggregateAbbrev;
    865     } else if (isa<ConstantArray>(C) || isa<ConstantStruct>(C) ||
    866                isa<ConstantVector>(C)) {
    867       Code = bitc::CST_CODE_AGGREGATE;
    868       for (unsigned i = 0, e = C->getNumOperands(); i != e; ++i)
    869         Record.push_back(VE.getValueID(C->getOperand(i)));
    870       AbbrevToUse = AggregateAbbrev;
    871     } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
    872       switch (CE->getOpcode()) {
    873       default:
    874         if (Instruction::isCast(CE->getOpcode())) {
    875           Code = bitc::CST_CODE_CE_CAST;
    876           Record.push_back(GetEncodedCastOpcode(CE->getOpcode()));
    877           Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
    878           Record.push_back(VE.getValueID(C->getOperand(0)));
    879           AbbrevToUse = CONSTANTS_CE_CAST_Abbrev;
    880         } else {
    881           assert(CE->getNumOperands() == 2 && "Unknown constant expr!");
    882           Code = bitc::CST_CODE_CE_BINOP;
    883           Record.push_back(GetEncodedBinaryOpcode(CE->getOpcode()));
    884           Record.push_back(VE.getValueID(C->getOperand(0)));
    885           Record.push_back(VE.getValueID(C->getOperand(1)));
    886           uint64_t Flags = GetOptimizationFlags(CE);
    887           if (Flags != 0)
    888             Record.push_back(Flags);
    889         }
    890         break;
    891       case Instruction::GetElementPtr:
    892         Code = bitc::CST_CODE_CE_GEP;
    893         if (cast<GEPOperator>(C)->isInBounds())
    894           Code = bitc::CST_CODE_CE_INBOUNDS_GEP;
    895         for (unsigned i = 0, e = CE->getNumOperands(); i != e; ++i) {
    896           Record.push_back(VE.getTypeID(C->getOperand(i)->getType()));
    897           Record.push_back(VE.getValueID(C->getOperand(i)));
    898         }
    899         break;
    900       case Instruction::Select:
    901         Code = bitc::CST_CODE_CE_SELECT;
    902         Record.push_back(VE.getValueID(C->getOperand(0)));
    903         Record.push_back(VE.getValueID(C->getOperand(1)));
    904         Record.push_back(VE.getValueID(C->getOperand(2)));
    905         break;
    906       case Instruction::ExtractElement:
    907         Code = bitc::CST_CODE_CE_EXTRACTELT;
    908         Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
    909         Record.push_back(VE.getValueID(C->getOperand(0)));
    910         Record.push_back(VE.getValueID(C->getOperand(1)));
    911         break;
    912       case Instruction::InsertElement:
    913         Code = bitc::CST_CODE_CE_INSERTELT;
    914         Record.push_back(VE.getValueID(C->getOperand(0)));
    915         Record.push_back(VE.getValueID(C->getOperand(1)));
    916         Record.push_back(VE.getValueID(C->getOperand(2)));
    917         break;
    918       case Instruction::ShuffleVector:
    919         // If the return type and argument types are the same, this is a
    920         // standard shufflevector instruction.  If the types are different,
    921         // then the shuffle is widening or truncating the input vectors, and
    922         // the argument type must also be encoded.
    923         if (C->getType() == C->getOperand(0)->getType()) {
    924           Code = bitc::CST_CODE_CE_SHUFFLEVEC;
    925         } else {
    926           Code = bitc::CST_CODE_CE_SHUFVEC_EX;
    927           Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
    928         }
    929         Record.push_back(VE.getValueID(C->getOperand(0)));
    930         Record.push_back(VE.getValueID(C->getOperand(1)));
    931         Record.push_back(VE.getValueID(C->getOperand(2)));
    932         break;
    933       case Instruction::ICmp:
    934       case Instruction::FCmp:
    935         Code = bitc::CST_CODE_CE_CMP;
    936         Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
    937         Record.push_back(VE.getValueID(C->getOperand(0)));
    938         Record.push_back(VE.getValueID(C->getOperand(1)));
    939         Record.push_back(CE->getPredicate());
    940         break;
    941       }
    942     } else if (const BlockAddress *BA = dyn_cast<BlockAddress>(C)) {
    943       Code = bitc::CST_CODE_BLOCKADDRESS;
    944       Record.push_back(VE.getTypeID(BA->getFunction()->getType()));
    945       Record.push_back(VE.getValueID(BA->getFunction()));
    946       Record.push_back(VE.getGlobalBasicBlockID(BA->getBasicBlock()));
    947     } else {
    948 #ifndef NDEBUG
    949       C->dump();
    950 #endif
    951       llvm_unreachable("Unknown constant!");
    952     }
    953     Stream.EmitRecord(Code, Record, AbbrevToUse);
    954     Record.clear();
    955   }
    956 
    957   Stream.ExitBlock();
    958 }
    959 
    960 static void WriteModuleConstants(const llvm_2_9_func::ValueEnumerator &VE,
    961                                  BitstreamWriter &Stream) {
    962   const llvm_2_9_func::ValueEnumerator::ValueList &Vals = VE.getValues();
    963 
    964   // Find the first constant to emit, which is the first non-globalvalue value.
    965   // We know globalvalues have been emitted by WriteModuleInfo.
    966   for (unsigned i = 0, e = Vals.size(); i != e; ++i) {
    967     if (!isa<GlobalValue>(Vals[i].first)) {
    968       WriteConstants(i, Vals.size(), VE, Stream, true);
    969       return;
    970     }
    971   }
    972 }
    973 
    974 /// PushValueAndType - The file has to encode both the value and type id for
    975 /// many values, because we need to know what type to create for forward
    976 /// references.  However, most operands are not forward references, so this type
    977 /// field is not needed.
    978 ///
    979 /// This function adds V's value ID to Vals.  If the value ID is higher than the
    980 /// instruction ID, then it is a forward reference, and it also includes the
    981 /// type ID.
    982 static bool PushValueAndType(const Value *V, unsigned InstID,
    983                              SmallVector<unsigned, 64> &Vals,
    984                              llvm_2_9_func::ValueEnumerator &VE) {
    985   unsigned ValID = VE.getValueID(V);
    986   Vals.push_back(ValID);
    987   if (ValID >= InstID) {
    988     Vals.push_back(VE.getTypeID(V->getType()));
    989     return true;
    990   }
    991   return false;
    992 }
    993 
    994 /// WriteInstruction - Emit an instruction to the specified stream.
    995 static void WriteInstruction(const Instruction &I, unsigned InstID,
    996                              llvm_2_9_func::ValueEnumerator &VE,
    997                              BitstreamWriter &Stream,
    998                              SmallVector<unsigned, 64> &Vals) {
    999   unsigned Code = 0;
   1000   unsigned AbbrevToUse = 0;
   1001   VE.setInstructionID(&I);
   1002   switch (I.getOpcode()) {
   1003   default:
   1004     if (Instruction::isCast(I.getOpcode())) {
   1005       Code = bitc::FUNC_CODE_INST_CAST;
   1006       if (!PushValueAndType(I.getOperand(0), InstID, Vals, VE))
   1007         AbbrevToUse = FUNCTION_INST_CAST_ABBREV;
   1008       Vals.push_back(VE.getTypeID(I.getType()));
   1009       Vals.push_back(GetEncodedCastOpcode(I.getOpcode()));
   1010     } else {
   1011       assert(isa<BinaryOperator>(I) && "Unknown instruction!");
   1012       Code = bitc::FUNC_CODE_INST_BINOP;
   1013       if (!PushValueAndType(I.getOperand(0), InstID, Vals, VE))
   1014         AbbrevToUse = FUNCTION_INST_BINOP_ABBREV;
   1015       Vals.push_back(VE.getValueID(I.getOperand(1)));
   1016       Vals.push_back(GetEncodedBinaryOpcode(I.getOpcode()));
   1017       uint64_t Flags = GetOptimizationFlags(&I);
   1018       if (Flags != 0) {
   1019         if (AbbrevToUse == FUNCTION_INST_BINOP_ABBREV)
   1020           AbbrevToUse = FUNCTION_INST_BINOP_FLAGS_ABBREV;
   1021         Vals.push_back(Flags);
   1022       }
   1023     }
   1024     break;
   1025 
   1026   case Instruction::GetElementPtr:
   1027     Code = bitc::FUNC_CODE_INST_GEP;
   1028     if (cast<GEPOperator>(&I)->isInBounds())
   1029       Code = bitc::FUNC_CODE_INST_INBOUNDS_GEP;
   1030     for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
   1031       PushValueAndType(I.getOperand(i), InstID, Vals, VE);
   1032     break;
   1033   case Instruction::ExtractValue: {
   1034     Code = bitc::FUNC_CODE_INST_EXTRACTVAL;
   1035     PushValueAndType(I.getOperand(0), InstID, Vals, VE);
   1036     const ExtractValueInst *EVI = cast<ExtractValueInst>(&I);
   1037     for (const unsigned *i = EVI->idx_begin(), *e = EVI->idx_end(); i != e; ++i)
   1038       Vals.push_back(*i);
   1039     break;
   1040   }
   1041   case Instruction::InsertValue: {
   1042     Code = bitc::FUNC_CODE_INST_INSERTVAL;
   1043     PushValueAndType(I.getOperand(0), InstID, Vals, VE);
   1044     PushValueAndType(I.getOperand(1), InstID, Vals, VE);
   1045     const InsertValueInst *IVI = cast<InsertValueInst>(&I);
   1046     for (const unsigned *i = IVI->idx_begin(), *e = IVI->idx_end(); i != e; ++i)
   1047       Vals.push_back(*i);
   1048     break;
   1049   }
   1050   case Instruction::Select:
   1051     Code = bitc::FUNC_CODE_INST_VSELECT;
   1052     PushValueAndType(I.getOperand(1), InstID, Vals, VE);
   1053     Vals.push_back(VE.getValueID(I.getOperand(2)));
   1054     PushValueAndType(I.getOperand(0), InstID, Vals, VE);
   1055     break;
   1056   case Instruction::ExtractElement:
   1057     Code = bitc::FUNC_CODE_INST_EXTRACTELT;
   1058     PushValueAndType(I.getOperand(0), InstID, Vals, VE);
   1059     Vals.push_back(VE.getValueID(I.getOperand(1)));
   1060     break;
   1061   case Instruction::InsertElement:
   1062     Code = bitc::FUNC_CODE_INST_INSERTELT;
   1063     PushValueAndType(I.getOperand(0), InstID, Vals, VE);
   1064     Vals.push_back(VE.getValueID(I.getOperand(1)));
   1065     Vals.push_back(VE.getValueID(I.getOperand(2)));
   1066     break;
   1067   case Instruction::ShuffleVector:
   1068     Code = bitc::FUNC_CODE_INST_SHUFFLEVEC;
   1069     PushValueAndType(I.getOperand(0), InstID, Vals, VE);
   1070     Vals.push_back(VE.getValueID(I.getOperand(1)));
   1071     Vals.push_back(VE.getValueID(I.getOperand(2)));
   1072     break;
   1073   case Instruction::ICmp:
   1074   case Instruction::FCmp:
   1075     // compare returning Int1Ty or vector of Int1Ty
   1076     Code = bitc::FUNC_CODE_INST_CMP2;
   1077     PushValueAndType(I.getOperand(0), InstID, Vals, VE);
   1078     Vals.push_back(VE.getValueID(I.getOperand(1)));
   1079     Vals.push_back(cast<CmpInst>(I).getPredicate());
   1080     break;
   1081 
   1082   case Instruction::Ret:
   1083     {
   1084       Code = bitc::FUNC_CODE_INST_RET;
   1085       unsigned NumOperands = I.getNumOperands();
   1086       if (NumOperands == 0)
   1087         AbbrevToUse = FUNCTION_INST_RET_VOID_ABBREV;
   1088       else if (NumOperands == 1) {
   1089         if (!PushValueAndType(I.getOperand(0), InstID, Vals, VE))
   1090           AbbrevToUse = FUNCTION_INST_RET_VAL_ABBREV;
   1091       } else {
   1092         for (unsigned i = 0, e = NumOperands; i != e; ++i)
   1093           PushValueAndType(I.getOperand(i), InstID, Vals, VE);
   1094       }
   1095     }
   1096     break;
   1097   case Instruction::Br:
   1098     {
   1099       Code = bitc::FUNC_CODE_INST_BR;
   1100       const BranchInst &II = cast<BranchInst>(I);
   1101       Vals.push_back(VE.getValueID(II.getSuccessor(0)));
   1102       if (II.isConditional()) {
   1103         Vals.push_back(VE.getValueID(II.getSuccessor(1)));
   1104         Vals.push_back(VE.getValueID(II.getCondition()));
   1105       }
   1106     }
   1107     break;
   1108   case Instruction::Switch:
   1109     {
   1110       Code = bitc::FUNC_CODE_INST_SWITCH;
   1111       const SwitchInst &SI = cast<SwitchInst>(I);
   1112 
   1113       Vals.push_back(VE.getTypeID(SI.getCondition()->getType()));
   1114       Vals.push_back(VE.getValueID(SI.getCondition()));
   1115       Vals.push_back(VE.getValueID(SI.getDefaultDest()));
   1116       for (SwitchInst::ConstCaseIt i = SI.case_begin(), e = SI.case_end();
   1117            i != e; ++i) {
   1118         const IntegersSubset& CaseRanges = i.getCaseValueEx();
   1119 
   1120         if (CaseRanges.isSingleNumber()) {
   1121           Vals.push_back(VE.getValueID(CaseRanges.getSingleNumber(0).toConstantInt()));
   1122           Vals.push_back(VE.getValueID(i.getCaseSuccessor()));
   1123         } else if (CaseRanges.isSingleNumbersOnly()) {
   1124           for (unsigned ri = 0, rn = CaseRanges.getNumItems();
   1125                ri != rn; ++ri) {
   1126             Vals.push_back(VE.getValueID(CaseRanges.getSingleNumber(ri).toConstantInt()));
   1127             Vals.push_back(VE.getValueID(i.getCaseSuccessor()));
   1128           }
   1129         } else {
   1130           llvm_unreachable("Not single number?");
   1131         }
   1132       }
   1133     }
   1134     break;
   1135   case Instruction::IndirectBr:
   1136     Code = bitc::FUNC_CODE_INST_INDIRECTBR;
   1137     Vals.push_back(VE.getTypeID(I.getOperand(0)->getType()));
   1138     for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
   1139       Vals.push_back(VE.getValueID(I.getOperand(i)));
   1140     break;
   1141 
   1142   case Instruction::Invoke: {
   1143     const InvokeInst *II = cast<InvokeInst>(&I);
   1144     const Value *Callee(II->getCalledValue());
   1145     PointerType *PTy = cast<PointerType>(Callee->getType());
   1146     FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
   1147     Code = bitc::FUNC_CODE_INST_INVOKE;
   1148 
   1149     Vals.push_back(VE.getAttributeID(II->getAttributes()));
   1150     Vals.push_back(II->getCallingConv());
   1151     Vals.push_back(VE.getValueID(II->getNormalDest()));
   1152     Vals.push_back(VE.getValueID(II->getUnwindDest()));
   1153     PushValueAndType(Callee, InstID, Vals, VE);
   1154 
   1155     // Emit value #'s for the fixed parameters.
   1156     for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
   1157       Vals.push_back(VE.getValueID(I.getOperand(i)));  // fixed param.
   1158 
   1159     // Emit type/value pairs for varargs params.
   1160     if (FTy->isVarArg()) {
   1161       for (unsigned i = FTy->getNumParams(), e = I.getNumOperands()-3;
   1162            i != e; ++i)
   1163         PushValueAndType(I.getOperand(i), InstID, Vals, VE); // vararg
   1164     }
   1165     break;
   1166   }
   1167   case Instruction::Resume:
   1168     Code = bitc::FUNC_CODE_INST_RESUME;
   1169     PushValueAndType(I.getOperand(0), InstID, Vals, VE);
   1170     break;
   1171   case Instruction::Unreachable:
   1172     Code = bitc::FUNC_CODE_INST_UNREACHABLE;
   1173     AbbrevToUse = FUNCTION_INST_UNREACHABLE_ABBREV;
   1174     break;
   1175 
   1176   case Instruction::PHI: {
   1177     const PHINode &PN = cast<PHINode>(I);
   1178     Code = bitc::FUNC_CODE_INST_PHI;
   1179     Vals.push_back(VE.getTypeID(PN.getType()));
   1180     for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
   1181       Vals.push_back(VE.getValueID(PN.getIncomingValue(i)));
   1182       Vals.push_back(VE.getValueID(PN.getIncomingBlock(i)));
   1183     }
   1184     break;
   1185   }
   1186 
   1187   case Instruction::LandingPad: {
   1188     const LandingPadInst &LP = cast<LandingPadInst>(I);
   1189     Code = bitc::FUNC_CODE_INST_LANDINGPAD;
   1190     Vals.push_back(VE.getTypeID(LP.getType()));
   1191     PushValueAndType(LP.getPersonalityFn(), InstID, Vals, VE);
   1192     Vals.push_back(LP.isCleanup());
   1193     Vals.push_back(LP.getNumClauses());
   1194     for (unsigned I = 0, E = LP.getNumClauses(); I != E; ++I) {
   1195       if (LP.isCatch(I))
   1196         Vals.push_back(LandingPadInst::Catch);
   1197       else
   1198         Vals.push_back(LandingPadInst::Filter);
   1199       PushValueAndType(LP.getClause(I), InstID, Vals, VE);
   1200     }
   1201     break;
   1202   }
   1203 
   1204   case Instruction::Alloca:
   1205     Code = bitc::FUNC_CODE_INST_ALLOCA;
   1206     Vals.push_back(VE.getTypeID(I.getType()));
   1207     Vals.push_back(VE.getTypeID(I.getOperand(0)->getType()));
   1208     Vals.push_back(VE.getValueID(I.getOperand(0))); // size.
   1209     Vals.push_back(Log2_32(cast<AllocaInst>(I).getAlignment())+1);
   1210     break;
   1211 
   1212   case Instruction::Load:
   1213     if (cast<LoadInst>(I).isAtomic()) {
   1214       Code = bitc::FUNC_CODE_INST_LOADATOMIC;
   1215       PushValueAndType(I.getOperand(0), InstID, Vals, VE);
   1216     } else {
   1217       Code = bitc::FUNC_CODE_INST_LOAD;
   1218       if (!PushValueAndType(I.getOperand(0), InstID, Vals, VE))  // ptr
   1219         AbbrevToUse = FUNCTION_INST_LOAD_ABBREV;
   1220     }
   1221     Vals.push_back(Log2_32(cast<LoadInst>(I).getAlignment())+1);
   1222     Vals.push_back(cast<LoadInst>(I).isVolatile());
   1223     if (cast<LoadInst>(I).isAtomic()) {
   1224       Vals.push_back(GetEncodedOrdering(cast<LoadInst>(I).getOrdering()));
   1225       Vals.push_back(GetEncodedSynchScope(cast<LoadInst>(I).getSynchScope()));
   1226     }
   1227     break;
   1228   case Instruction::Store:
   1229     if (cast<StoreInst>(I).isAtomic())
   1230       Code = bitc::FUNC_CODE_INST_STOREATOMIC;
   1231     else
   1232       Code = bitc::FUNC_CODE_INST_STORE;
   1233     PushValueAndType(I.getOperand(1), InstID, Vals, VE);  // ptrty + ptr
   1234     Vals.push_back(VE.getValueID(I.getOperand(0)));       // val.
   1235     Vals.push_back(Log2_32(cast<StoreInst>(I).getAlignment())+1);
   1236     Vals.push_back(cast<StoreInst>(I).isVolatile());
   1237     if (cast<StoreInst>(I).isAtomic()) {
   1238       Vals.push_back(GetEncodedOrdering(cast<StoreInst>(I).getOrdering()));
   1239       Vals.push_back(GetEncodedSynchScope(cast<StoreInst>(I).getSynchScope()));
   1240     }
   1241     break;
   1242   case Instruction::AtomicCmpXchg:
   1243     Code = bitc::FUNC_CODE_INST_CMPXCHG;
   1244     PushValueAndType(I.getOperand(0), InstID, Vals, VE);  // ptrty + ptr
   1245     Vals.push_back(VE.getValueID(I.getOperand(1)));       // cmp.
   1246     Vals.push_back(VE.getValueID(I.getOperand(2)));       // newval.
   1247     Vals.push_back(cast<AtomicCmpXchgInst>(I).isVolatile());
   1248     Vals.push_back(GetEncodedOrdering(
   1249                      cast<AtomicCmpXchgInst>(I).getOrdering()));
   1250     Vals.push_back(GetEncodedSynchScope(
   1251                      cast<AtomicCmpXchgInst>(I).getSynchScope()));
   1252     break;
   1253   case Instruction::AtomicRMW:
   1254     Code = bitc::FUNC_CODE_INST_ATOMICRMW;
   1255     PushValueAndType(I.getOperand(0), InstID, Vals, VE);  // ptrty + ptr
   1256     Vals.push_back(VE.getValueID(I.getOperand(1)));       // val.
   1257     Vals.push_back(GetEncodedRMWOperation(
   1258                      cast<AtomicRMWInst>(I).getOperation()));
   1259     Vals.push_back(cast<AtomicRMWInst>(I).isVolatile());
   1260     Vals.push_back(GetEncodedOrdering(cast<AtomicRMWInst>(I).getOrdering()));
   1261     Vals.push_back(GetEncodedSynchScope(
   1262                      cast<AtomicRMWInst>(I).getSynchScope()));
   1263     break;
   1264   case Instruction::Fence:
   1265     Code = bitc::FUNC_CODE_INST_FENCE;
   1266     Vals.push_back(GetEncodedOrdering(cast<FenceInst>(I).getOrdering()));
   1267     Vals.push_back(GetEncodedSynchScope(cast<FenceInst>(I).getSynchScope()));
   1268     break;
   1269   case Instruction::Call: {
   1270     const CallInst &CI = cast<CallInst>(I);
   1271     PointerType *PTy = cast<PointerType>(CI.getCalledValue()->getType());
   1272     FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
   1273 
   1274     Code = bitc::FUNC_CODE_INST_CALL;
   1275 
   1276     Vals.push_back(VE.getAttributeID(CI.getAttributes()));
   1277     Vals.push_back((CI.getCallingConv() << 1) | unsigned(CI.isTailCall()));
   1278     PushValueAndType(CI.getCalledValue(), InstID, Vals, VE);  // Callee
   1279 
   1280     // Emit value #'s for the fixed parameters.
   1281     for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
   1282       Vals.push_back(VE.getValueID(CI.getArgOperand(i)));  // fixed param.
   1283 
   1284     // Emit type/value pairs for varargs params.
   1285     if (FTy->isVarArg()) {
   1286       for (unsigned i = FTy->getNumParams(), e = CI.getNumArgOperands();
   1287            i != e; ++i)
   1288         PushValueAndType(CI.getArgOperand(i), InstID, Vals, VE);  // varargs
   1289     }
   1290     break;
   1291   }
   1292   case Instruction::VAArg:
   1293     Code = bitc::FUNC_CODE_INST_VAARG;
   1294     Vals.push_back(VE.getTypeID(I.getOperand(0)->getType()));   // valistty
   1295     Vals.push_back(VE.getValueID(I.getOperand(0))); // valist.
   1296     Vals.push_back(VE.getTypeID(I.getType())); // restype.
   1297     break;
   1298   }
   1299 
   1300   Stream.EmitRecord(Code, Vals, AbbrevToUse);
   1301   Vals.clear();
   1302 }
   1303 
   1304 // Emit names for globals/functions etc.
   1305 static void WriteValueSymbolTable(const ValueSymbolTable &VST,
   1306                                   const llvm_2_9_func::ValueEnumerator &VE,
   1307                                   BitstreamWriter &Stream) {
   1308   if (VST.empty()) return;
   1309   Stream.EnterSubblock(bitc::VALUE_SYMTAB_BLOCK_ID, 4);
   1310 
   1311   // FIXME: Set up the abbrev, we know how many values there are!
   1312   // FIXME: We know if the type names can use 7-bit ascii.
   1313   SmallVector<unsigned, 64> NameVals;
   1314 
   1315   for (ValueSymbolTable::const_iterator SI = VST.begin(), SE = VST.end();
   1316        SI != SE; ++SI) {
   1317 
   1318     const ValueName &Name = *SI;
   1319 
   1320     // Figure out the encoding to use for the name.
   1321     bool is7Bit = true;
   1322     bool isChar6 = true;
   1323     for (const char *C = Name.getKeyData(), *E = C+Name.getKeyLength();
   1324          C != E; ++C) {
   1325       if (isChar6)
   1326         isChar6 = BitCodeAbbrevOp::isChar6(*C);
   1327       if ((unsigned char)*C & 128) {
   1328         is7Bit = false;
   1329         break;  // don't bother scanning the rest.
   1330       }
   1331     }
   1332 
   1333     unsigned AbbrevToUse = VST_ENTRY_8_ABBREV;
   1334 
   1335     // VST_ENTRY:   [valueid, namechar x N]
   1336     // VST_BBENTRY: [bbid, namechar x N]
   1337     unsigned Code;
   1338     if (isa<BasicBlock>(SI->getValue())) {
   1339       Code = bitc::VST_CODE_BBENTRY;
   1340       if (isChar6)
   1341         AbbrevToUse = VST_BBENTRY_6_ABBREV;
   1342     } else {
   1343       Code = bitc::VST_CODE_ENTRY;
   1344       if (isChar6)
   1345         AbbrevToUse = VST_ENTRY_6_ABBREV;
   1346       else if (is7Bit)
   1347         AbbrevToUse = VST_ENTRY_7_ABBREV;
   1348     }
   1349 
   1350     NameVals.push_back(VE.getValueID(SI->getValue()));
   1351     for (const char *P = Name.getKeyData(),
   1352          *E = Name.getKeyData()+Name.getKeyLength(); P != E; ++P)
   1353       NameVals.push_back((unsigned char)*P);
   1354 
   1355     // Emit the finished record.
   1356     Stream.EmitRecord(Code, NameVals, AbbrevToUse);
   1357     NameVals.clear();
   1358   }
   1359   Stream.ExitBlock();
   1360 }
   1361 
   1362 /// WriteFunction - Emit a function body to the module stream.
   1363 static void WriteFunction(const Function &F, llvm_2_9_func::ValueEnumerator &VE,
   1364                           BitstreamWriter &Stream) {
   1365   Stream.EnterSubblock(bitc::FUNCTION_BLOCK_ID, 4);
   1366   VE.incorporateFunction(F);
   1367 
   1368   SmallVector<unsigned, 64> Vals;
   1369 
   1370   // Emit the number of basic blocks, so the reader can create them ahead of
   1371   // time.
   1372   Vals.push_back(VE.getBasicBlocks().size());
   1373   Stream.EmitRecord(bitc::FUNC_CODE_DECLAREBLOCKS, Vals);
   1374   Vals.clear();
   1375 
   1376   // If there are function-local constants, emit them now.
   1377   unsigned CstStart, CstEnd;
   1378   VE.getFunctionConstantRange(CstStart, CstEnd);
   1379   WriteConstants(CstStart, CstEnd, VE, Stream, false);
   1380 
   1381   // If there is function-local metadata, emit it now.
   1382   WriteFunctionLocalMetadata(F, VE, Stream);
   1383 
   1384   // Keep a running idea of what the instruction ID is.
   1385   unsigned InstID = CstEnd;
   1386 
   1387   bool NeedsMetadataAttachment = false;
   1388 
   1389   DebugLoc LastDL;
   1390 
   1391   // Finally, emit all the instructions, in order.
   1392   for (Function::const_iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
   1393     for (BasicBlock::const_iterator I = BB->begin(), E = BB->end();
   1394          I != E; ++I) {
   1395       WriteInstruction(*I, InstID, VE, Stream, Vals);
   1396 
   1397       if (!I->getType()->isVoidTy())
   1398         ++InstID;
   1399 
   1400       // If the instruction has metadata, write a metadata attachment later.
   1401       NeedsMetadataAttachment |= I->hasMetadataOtherThanDebugLoc();
   1402 
   1403       // If the instruction has a debug location, emit it.
   1404       DebugLoc DL = I->getDebugLoc();
   1405       if (DL.isUnknown()) {
   1406         // nothing todo.
   1407       } else if (DL == LastDL) {
   1408         // Just repeat the same debug loc as last time.
   1409         Stream.EmitRecord(bitc::FUNC_CODE_DEBUG_LOC_AGAIN, Vals);
   1410       } else {
   1411         MDNode *Scope, *IA;
   1412         DL.getScopeAndInlinedAt(Scope, IA, I->getContext());
   1413 
   1414         Vals.push_back(DL.getLine());
   1415         Vals.push_back(DL.getCol());
   1416         Vals.push_back(Scope ? VE.getValueID(Scope)+1 : 0);
   1417         Vals.push_back(IA ? VE.getValueID(IA)+1 : 0);
   1418         Stream.EmitRecord(bitc::FUNC_CODE_DEBUG_LOC, Vals);
   1419         Vals.clear();
   1420 
   1421         LastDL = DL;
   1422       }
   1423     }
   1424 
   1425   // Emit names for all the instructions etc.
   1426   WriteValueSymbolTable(F.getValueSymbolTable(), VE, Stream);
   1427 
   1428   if (NeedsMetadataAttachment)
   1429     WriteMetadataAttachment(F, VE, Stream);
   1430   VE.purgeFunction();
   1431   Stream.ExitBlock();
   1432 }
   1433 
   1434 // Emit blockinfo, which defines the standard abbreviations etc.
   1435 static void WriteBlockInfo(const llvm_2_9_func::ValueEnumerator &VE,
   1436                            BitstreamWriter &Stream) {
   1437   // We only want to emit block info records for blocks that have multiple
   1438   // instances: CONSTANTS_BLOCK, FUNCTION_BLOCK and VALUE_SYMTAB_BLOCK.  Other
   1439   // blocks can defined their abbrevs inline.
   1440   Stream.EnterBlockInfoBlock(2);
   1441 
   1442   { // 8-bit fixed-width VST_ENTRY/VST_BBENTRY strings.
   1443     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
   1444     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 3));
   1445     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
   1446     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
   1447     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
   1448     if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID,
   1449                                    Abbv) != VST_ENTRY_8_ABBREV)
   1450       llvm_unreachable("Unexpected abbrev ordering!");
   1451   }
   1452 
   1453   { // 7-bit fixed width VST_ENTRY strings.
   1454     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
   1455     Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_ENTRY));
   1456     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
   1457     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
   1458     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7));
   1459     if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID,
   1460                                    Abbv) != VST_ENTRY_7_ABBREV)
   1461       llvm_unreachable("Unexpected abbrev ordering!");
   1462   }
   1463   { // 6-bit char6 VST_ENTRY strings.
   1464     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
   1465     Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_ENTRY));
   1466     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
   1467     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
   1468     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
   1469     if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID,
   1470                                    Abbv) != VST_ENTRY_6_ABBREV)
   1471       llvm_unreachable("Unexpected abbrev ordering!");
   1472   }
   1473   { // 6-bit char6 VST_BBENTRY strings.
   1474     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
   1475     Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_BBENTRY));
   1476     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
   1477     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
   1478     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
   1479     if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID,
   1480                                    Abbv) != VST_BBENTRY_6_ABBREV)
   1481       llvm_unreachable("Unexpected abbrev ordering!");
   1482   }
   1483 
   1484 
   1485 
   1486   { // SETTYPE abbrev for CONSTANTS_BLOCK.
   1487     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
   1488     Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_SETTYPE));
   1489     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
   1490                               Log2_32_Ceil(VE.getTypes().size()+1)));
   1491     if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID,
   1492                                    Abbv) != CONSTANTS_SETTYPE_ABBREV)
   1493       llvm_unreachable("Unexpected abbrev ordering!");
   1494   }
   1495 
   1496   { // INTEGER abbrev for CONSTANTS_BLOCK.
   1497     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
   1498     Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_INTEGER));
   1499     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
   1500     if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID,
   1501                                    Abbv) != CONSTANTS_INTEGER_ABBREV)
   1502       llvm_unreachable("Unexpected abbrev ordering!");
   1503   }
   1504 
   1505   { // CE_CAST abbrev for CONSTANTS_BLOCK.
   1506     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
   1507     Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_CE_CAST));
   1508     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4));  // cast opc
   1509     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,       // typeid
   1510                               Log2_32_Ceil(VE.getTypes().size()+1)));
   1511     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));    // value id
   1512 
   1513     if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID,
   1514                                    Abbv) != CONSTANTS_CE_CAST_Abbrev)
   1515       llvm_unreachable("Unexpected abbrev ordering!");
   1516   }
   1517   { // NULL abbrev for CONSTANTS_BLOCK.
   1518     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
   1519     Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_NULL));
   1520     if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID,
   1521                                    Abbv) != CONSTANTS_NULL_Abbrev)
   1522       llvm_unreachable("Unexpected abbrev ordering!");
   1523   }
   1524 
   1525   // FIXME: This should only use space for first class types!
   1526 
   1527   { // INST_LOAD abbrev for FUNCTION_BLOCK.
   1528     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
   1529     Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_LOAD));
   1530     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Ptr
   1531     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // Align
   1532     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // volatile
   1533     if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
   1534                                    Abbv) != FUNCTION_INST_LOAD_ABBREV)
   1535       llvm_unreachable("Unexpected abbrev ordering!");
   1536   }
   1537   { // INST_BINOP abbrev for FUNCTION_BLOCK.
   1538     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
   1539     Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_BINOP));
   1540     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // LHS
   1541     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // RHS
   1542     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
   1543     if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
   1544                                    Abbv) != FUNCTION_INST_BINOP_ABBREV)
   1545       llvm_unreachable("Unexpected abbrev ordering!");
   1546   }
   1547   { // INST_BINOP_FLAGS abbrev for FUNCTION_BLOCK.
   1548     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
   1549     Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_BINOP));
   1550     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // LHS
   1551     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // RHS
   1552     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
   1553     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7)); // flags
   1554     if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
   1555                                    Abbv) != FUNCTION_INST_BINOP_FLAGS_ABBREV)
   1556       llvm_unreachable("Unexpected abbrev ordering!");
   1557   }
   1558   { // INST_CAST abbrev for FUNCTION_BLOCK.
   1559     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
   1560     Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_CAST));
   1561     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));    // OpVal
   1562     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,       // dest ty
   1563                               Log2_32_Ceil(VE.getTypes().size()+1)));
   1564     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4));  // opc
   1565     if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
   1566                                    Abbv) != FUNCTION_INST_CAST_ABBREV)
   1567       llvm_unreachable("Unexpected abbrev ordering!");
   1568   }
   1569 
   1570   { // INST_RET abbrev for FUNCTION_BLOCK.
   1571     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
   1572     Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_RET));
   1573     if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
   1574                                    Abbv) != FUNCTION_INST_RET_VOID_ABBREV)
   1575       llvm_unreachable("Unexpected abbrev ordering!");
   1576   }
   1577   { // INST_RET abbrev for FUNCTION_BLOCK.
   1578     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
   1579     Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_RET));
   1580     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // ValID
   1581     if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
   1582                                    Abbv) != FUNCTION_INST_RET_VAL_ABBREV)
   1583       llvm_unreachable("Unexpected abbrev ordering!");
   1584   }
   1585   { // INST_UNREACHABLE abbrev for FUNCTION_BLOCK.
   1586     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
   1587     Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_UNREACHABLE));
   1588     if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
   1589                                    Abbv) != FUNCTION_INST_UNREACHABLE_ABBREV)
   1590       llvm_unreachable("Unexpected abbrev ordering!");
   1591   }
   1592 
   1593   Stream.ExitBlock();
   1594 }
   1595 
   1596 
   1597 /// WriteModule - Emit the specified module to the bitstream.
   1598 static void WriteModule(const Module *M, BitstreamWriter &Stream) {
   1599   Stream.EnterSubblock(bitc::MODULE_BLOCK_ID, 3);
   1600 
   1601   // Emit the version number if it is non-zero.
   1602   if (CurVersion) {
   1603     SmallVector<unsigned, 1> Vals;
   1604     Vals.push_back(CurVersion);
   1605     Stream.EmitRecord(bitc::MODULE_CODE_VERSION, Vals);
   1606   }
   1607 
   1608   // Analyze the module, enumerating globals, functions, etc.
   1609   llvm_2_9_func::ValueEnumerator VE(M);
   1610 
   1611   // Emit blockinfo, which defines the standard abbreviations etc.
   1612   WriteBlockInfo(VE, Stream);
   1613 
   1614   // Emit information about parameter attributes.
   1615   WriteAttributeTable(VE, Stream);
   1616 
   1617   // Emit information describing all of the types in the module.
   1618   WriteTypeTable(VE, Stream);
   1619 
   1620   // Emit top-level description of module, including target triple, inline asm,
   1621   // descriptors for global variables, and function prototype info.
   1622   WriteModuleInfo(M, VE, Stream);
   1623 
   1624   // Emit constants.
   1625   WriteModuleConstants(VE, Stream);
   1626 
   1627   // Emit metadata.
   1628   WriteModuleMetadata(M, VE, Stream);
   1629 
   1630   // Emit function bodies.
   1631   for (Module::const_iterator F = M->begin(), E = M->end(); F != E; ++F)
   1632     if (!F->isDeclaration())
   1633       WriteFunction(*F, VE, Stream);
   1634 
   1635   // Emit metadata.
   1636   WriteModuleMetadataStore(M, Stream);
   1637 
   1638   // Emit names for globals/functions etc.
   1639   WriteValueSymbolTable(M->getValueSymbolTable(), VE, Stream);
   1640 
   1641   Stream.ExitBlock();
   1642 }
   1643 
   1644 /// EmitDarwinBCHeader - If generating a bc file on darwin, we have to emit a
   1645 /// header and trailer to make it compatible with the system archiver.  To do
   1646 /// this we emit the following header, and then emit a trailer that pads the
   1647 /// file out to be a multiple of 16 bytes.
   1648 ///
   1649 /// struct bc_header {
   1650 ///   uint32_t Magic;         // 0x0B17C0DE
   1651 ///   uint32_t Version;       // Version, currently always 0.
   1652 ///   uint32_t BitcodeOffset; // Offset to traditional bitcode file.
   1653 ///   uint32_t BitcodeSize;   // Size of traditional bitcode file.
   1654 ///   uint32_t CPUType;       // CPU specifier.
   1655 ///   ... potentially more later ...
   1656 /// };
   1657 enum {
   1658   DarwinBCSizeFieldOffset = 3*4, // Offset to bitcode_size.
   1659   DarwinBCHeaderSize = 5*4
   1660 };
   1661 
   1662 static void WriteInt32ToBuffer(uint32_t Value, SmallVectorImpl<char> &Buffer,
   1663                                uint32_t &Position) {
   1664   Buffer[Position + 0] = (unsigned char) (Value >>  0);
   1665   Buffer[Position + 1] = (unsigned char) (Value >>  8);
   1666   Buffer[Position + 2] = (unsigned char) (Value >> 16);
   1667   Buffer[Position + 3] = (unsigned char) (Value >> 24);
   1668   Position += 4;
   1669 }
   1670 
   1671 static void EmitDarwinBCHeaderAndTrailer(SmallVectorImpl<char> &Buffer,
   1672                                          const Triple &TT) {
   1673   unsigned CPUType = ~0U;
   1674 
   1675   // Match x86_64-*, i[3-9]86-*, powerpc-*, powerpc64-*, arm-*, thumb-*,
   1676   // armv[0-9]-*, thumbv[0-9]-*, armv5te-*, or armv6t2-*. The CPUType is a magic
   1677   // number from /usr/include/mach/machine.h.  It is ok to reproduce the
   1678   // specific constants here because they are implicitly part of the Darwin ABI.
   1679   enum {
   1680     DARWIN_CPU_ARCH_ABI64      = 0x01000000,
   1681     DARWIN_CPU_TYPE_X86        = 7,
   1682     DARWIN_CPU_TYPE_ARM        = 12,
   1683     DARWIN_CPU_TYPE_POWERPC    = 18
   1684   };
   1685 
   1686   Triple::ArchType Arch = TT.getArch();
   1687   if (Arch == Triple::x86_64)
   1688     CPUType = DARWIN_CPU_TYPE_X86 | DARWIN_CPU_ARCH_ABI64;
   1689   else if (Arch == Triple::x86)
   1690     CPUType = DARWIN_CPU_TYPE_X86;
   1691   else if (Arch == Triple::ppc)
   1692     CPUType = DARWIN_CPU_TYPE_POWERPC;
   1693   else if (Arch == Triple::ppc64)
   1694     CPUType = DARWIN_CPU_TYPE_POWERPC | DARWIN_CPU_ARCH_ABI64;
   1695   else if (Arch == Triple::arm || Arch == Triple::thumb)
   1696     CPUType = DARWIN_CPU_TYPE_ARM;
   1697 
   1698   // Traditional Bitcode starts after header.
   1699   assert(Buffer.size() >= DarwinBCHeaderSize &&
   1700          "Expected header size to be reserved");
   1701   unsigned BCOffset = DarwinBCHeaderSize;
   1702   unsigned BCSize = Buffer.size()-DarwinBCHeaderSize;
   1703 
   1704   // Write the magic and version.
   1705   unsigned Position = 0;
   1706   WriteInt32ToBuffer(0x0B17C0DE , Buffer, Position);
   1707   WriteInt32ToBuffer(0          , Buffer, Position); // Version.
   1708   WriteInt32ToBuffer(BCOffset   , Buffer, Position);
   1709   WriteInt32ToBuffer(BCSize     , Buffer, Position);
   1710   WriteInt32ToBuffer(CPUType    , Buffer, Position);
   1711 
   1712   // If the file is not a multiple of 16 bytes, insert dummy padding.
   1713   while (Buffer.size() & 15)
   1714     Buffer.push_back(0);
   1715 }
   1716 
   1717 /// WriteBitcodeToFile - Write the specified module to the specified output
   1718 /// stream.
   1719 void llvm_2_9_func::WriteBitcodeToFile(const Module *M, raw_ostream &Out) {
   1720   SmallVector<char, 1024> Buffer;
   1721   Buffer.reserve(256*1024);
   1722 
   1723   // If this is darwin or another generic macho target, reserve space for the
   1724   // header.
   1725   Triple TT(M->getTargetTriple());
   1726   if (TT.isOSDarwin())
   1727     Buffer.insert(Buffer.begin(), DarwinBCHeaderSize, 0);
   1728 
   1729   // Emit the module into the buffer.
   1730   {
   1731     BitstreamWriter Stream(Buffer);
   1732 
   1733     // Emit the file header.
   1734     Stream.Emit((unsigned)'B', 8);
   1735     Stream.Emit((unsigned)'C', 8);
   1736     Stream.Emit(0x0, 4);
   1737     Stream.Emit(0xC, 4);
   1738     Stream.Emit(0xE, 4);
   1739     Stream.Emit(0xD, 4);
   1740 
   1741     // Emit the module.
   1742     WriteModule(M, Stream);
   1743   }
   1744 
   1745   if (TT.isOSDarwin())
   1746     EmitDarwinBCHeaderAndTrailer(Buffer, TT);
   1747 
   1748   // Write the generated bitstream to "Out".
   1749   Out.write((char*)&Buffer.front(), Buffer.size());
   1750 }
   1751