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 "llvm/Bitcode/BitstreamWriter.h"
00016 #include "llvm/Bitcode/LLVMBitCodes.h"
00017 #include "ValueEnumerator.h"
00018 #include "llvm/Constants.h"
00019 #include "llvm/DerivedTypes.h"
00020 #include "llvm/InlineAsm.h"
00021 #include "llvm/Instructions.h"
00022 #include "llvm/Metadata.h"
00023 #include "llvm/Module.h"
00024 #include "llvm/Operator.h"
00025 #include "llvm/TypeSymbolTable.h"
00026 #include "llvm/ValueSymbolTable.h"
00027 #include "llvm/Support/ErrorHandling.h"
00028 #include "llvm/Support/MathExtras.h"
00029 #include "llvm/Support/Streams.h"
00030 #include "llvm/Support/raw_ostream.h"
00031 #include "llvm/System/Program.h"
00032 using namespace llvm;
00033 
00034 /// These are manifest constants used by the bitcode writer. They do not need to
00035 /// be kept in sync with the reader, but need to be consistent within this file.
00036 enum {
00037   CurVersion = 0,
00038   
00039   // VALUE_SYMTAB_BLOCK abbrev id's.
00040   VST_ENTRY_8_ABBREV = bitc::FIRST_APPLICATION_ABBREV,
00041   VST_ENTRY_7_ABBREV,
00042   VST_ENTRY_6_ABBREV,
00043   VST_BBENTRY_6_ABBREV,
00044   
00045   // CONSTANTS_BLOCK abbrev id's.
00046   CONSTANTS_SETTYPE_ABBREV = bitc::FIRST_APPLICATION_ABBREV,
00047   CONSTANTS_INTEGER_ABBREV,
00048   CONSTANTS_CE_CAST_Abbrev,
00049   CONSTANTS_NULL_Abbrev,
00050   
00051   // FUNCTION_BLOCK abbrev id's.
00052   FUNCTION_INST_LOAD_ABBREV = bitc::FIRST_APPLICATION_ABBREV,
00053   FUNCTION_INST_BINOP_ABBREV,
00054   FUNCTION_INST_BINOP_FLAGS_ABBREV,
00055   FUNCTION_INST_CAST_ABBREV,
00056   FUNCTION_INST_RET_VOID_ABBREV,
00057   FUNCTION_INST_RET_VAL_ABBREV,
00058   FUNCTION_INST_UNREACHABLE_ABBREV
00059 };
00060 
00061 
00062 static unsigned GetEncodedCastOpcode(unsigned Opcode) {
00063   switch (Opcode) {
00064   default: llvm_unreachable("Unknown cast instruction!");
00065   case Instruction::Trunc   : return bitc::CAST_TRUNC;
00066   case Instruction::ZExt    : return bitc::CAST_ZEXT;
00067   case Instruction::SExt    : return bitc::CAST_SEXT;
00068   case Instruction::FPToUI  : return bitc::CAST_FPTOUI;
00069   case Instruction::FPToSI  : return bitc::CAST_FPTOSI;
00070   case Instruction::UIToFP  : return bitc::CAST_UITOFP;
00071   case Instruction::SIToFP  : return bitc::CAST_SITOFP;
00072   case Instruction::FPTrunc : return bitc::CAST_FPTRUNC;
00073   case Instruction::FPExt   : return bitc::CAST_FPEXT;
00074   case Instruction::PtrToInt: return bitc::CAST_PTRTOINT;
00075   case Instruction::IntToPtr: return bitc::CAST_INTTOPTR;
00076   case Instruction::BitCast : return bitc::CAST_BITCAST;
00077   }
00078 }
00079 
00080 static unsigned GetEncodedBinaryOpcode(unsigned Opcode) {
00081   switch (Opcode) {
00082   default: llvm_unreachable("Unknown binary instruction!");
00083   case Instruction::Add:
00084   case Instruction::FAdd: return bitc::BINOP_ADD;
00085   case Instruction::Sub:
00086   case Instruction::FSub: return bitc::BINOP_SUB;
00087   case Instruction::Mul:
00088   case Instruction::FMul: return bitc::BINOP_MUL;
00089   case Instruction::UDiv: return bitc::BINOP_UDIV;
00090   case Instruction::FDiv:
00091   case Instruction::SDiv: return bitc::BINOP_SDIV;
00092   case Instruction::URem: return bitc::BINOP_UREM;
00093   case Instruction::FRem:
00094   case Instruction::SRem: return bitc::BINOP_SREM;
00095   case Instruction::Shl:  return bitc::BINOP_SHL;
00096   case Instruction::LShr: return bitc::BINOP_LSHR;
00097   case Instruction::AShr: return bitc::BINOP_ASHR;
00098   case Instruction::And:  return bitc::BINOP_AND;
00099   case Instruction::Or:   return bitc::BINOP_OR;
00100   case Instruction::Xor:  return bitc::BINOP_XOR;
00101   }
00102 }
00103 
00104 
00105 
00106 static void WriteStringRecord(unsigned Code, const std::string &Str, 
00107                               unsigned AbbrevToUse, BitstreamWriter &Stream) {
00108   SmallVector<unsigned, 64> Vals;
00109   
00110   // Code: [strchar x N]
00111   for (unsigned i = 0, e = Str.size(); i != e; ++i)
00112     Vals.push_back(Str[i]);
00113     
00114   // Emit the finished record.
00115   Stream.EmitRecord(Code, Vals, AbbrevToUse);
00116 }
00117 
00118 // Emit information about parameter attributes.
00119 static void WriteAttributeTable(const ValueEnumerator &VE, 
00120                                 BitstreamWriter &Stream) {
00121   const std::vector<AttrListPtr> &Attrs = VE.getAttributes();
00122   if (Attrs.empty()) return;
00123   
00124   Stream.EnterSubblock(bitc::PARAMATTR_BLOCK_ID, 3);
00125 
00126   SmallVector<uint64_t, 64> Record;
00127   for (unsigned i = 0, e = Attrs.size(); i != e; ++i) {
00128     const AttrListPtr &A = Attrs[i];
00129     for (unsigned i = 0, e = A.getNumSlots(); i != e; ++i) {
00130       const AttributeWithIndex &PAWI = A.getSlot(i);
00131       Record.push_back(PAWI.Index);
00132 
00133       // FIXME: remove in LLVM 3.0
00134       // Store the alignment in the bitcode as a 16-bit raw value instead of a
00135       // 5-bit log2 encoded value. Shift the bits above the alignment up by
00136       // 11 bits.
00137       uint64_t FauxAttr = PAWI.Attrs & 0xffff;
00138       if (PAWI.Attrs & Attribute::Alignment)
00139         FauxAttr |= (1ull<<16)<<(((PAWI.Attrs & Attribute::Alignment)-1) >> 16);
00140       FauxAttr |= (PAWI.Attrs & (0x3FFull << 21)) << 11;
00141 
00142       Record.push_back(FauxAttr);
00143     }
00144     
00145     Stream.EmitRecord(bitc::PARAMATTR_CODE_ENTRY, Record);
00146     Record.clear();
00147   }
00148   
00149   Stream.ExitBlock();
00150 }
00151 
00152 /// WriteTypeTable - Write out the type table for a module.
00153 static void WriteTypeTable(const ValueEnumerator &VE, BitstreamWriter &Stream) {
00154   const ValueEnumerator::TypeList &TypeList = VE.getTypes();
00155   
00156   Stream.EnterSubblock(bitc::TYPE_BLOCK_ID, 4 /*count from # abbrevs */);
00157   SmallVector<uint64_t, 64> TypeVals;
00158   
00159   // Abbrev for TYPE_CODE_POINTER.
00160   BitCodeAbbrev *Abbv = new BitCodeAbbrev();
00161   Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_POINTER));
00162   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
00163                             Log2_32_Ceil(VE.getTypes().size()+1)));
00164   Abbv->Add(BitCodeAbbrevOp(0));  // Addrspace = 0
00165   unsigned PtrAbbrev = Stream.EmitAbbrev(Abbv);
00166   
00167   // Abbrev for TYPE_CODE_FUNCTION.
00168   Abbv = new BitCodeAbbrev();
00169   Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_FUNCTION));
00170   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));  // isvararg
00171   Abbv->Add(BitCodeAbbrevOp(0));  // FIXME: DEAD value, remove in LLVM 3.0
00172   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
00173   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
00174                             Log2_32_Ceil(VE.getTypes().size()+1)));
00175   unsigned FunctionAbbrev = Stream.EmitAbbrev(Abbv);
00176   
00177   // Abbrev for TYPE_CODE_STRUCT.
00178   Abbv = new BitCodeAbbrev();
00179   Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_STRUCT));
00180   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));  // ispacked
00181   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
00182   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
00183                             Log2_32_Ceil(VE.getTypes().size()+1)));
00184   unsigned StructAbbrev = Stream.EmitAbbrev(Abbv);
00185  
00186   // Abbrev for TYPE_CODE_ARRAY.
00187   Abbv = new BitCodeAbbrev();
00188   Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_ARRAY));
00189   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));   // size
00190   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
00191                             Log2_32_Ceil(VE.getTypes().size()+1)));
00192   unsigned ArrayAbbrev = Stream.EmitAbbrev(Abbv);
00193   
00194   // Emit an entry count so the reader can reserve space.
00195   TypeVals.push_back(TypeList.size());
00196   Stream.EmitRecord(bitc::TYPE_CODE_NUMENTRY, TypeVals);
00197   TypeVals.clear();
00198   
00199   // Loop over all of the types, emitting each in turn.
00200   for (unsigned i = 0, e = TypeList.size(); i != e; ++i) {
00201     const Type *T = TypeList[i].first;
00202     int AbbrevToUse = 0;
00203     unsigned Code = 0;
00204     
00205     switch (T->getTypeID()) {
00206     default: llvm_unreachable("Unknown type!");
00207     case Type::VoidTyID:   Code = bitc::TYPE_CODE_VOID;   break;
00208     case Type::FloatTyID:  Code = bitc::TYPE_CODE_FLOAT;  break;
00209     case Type::DoubleTyID: Code = bitc::TYPE_CODE_DOUBLE; break;
00210     case Type::X86_FP80TyID: Code = bitc::TYPE_CODE_X86_FP80; break;
00211     case Type::FP128TyID: Code = bitc::TYPE_CODE_FP128; break;
00212     case Type::PPC_FP128TyID: Code = bitc::TYPE_CODE_PPC_FP128; break;
00213     case Type::LabelTyID:  Code = bitc::TYPE_CODE_LABEL;  break;
00214     case Type::OpaqueTyID: Code = bitc::TYPE_CODE_OPAQUE; break;
00215     case Type::MetadataTyID: Code = bitc::TYPE_CODE_METADATA; break;
00216     case Type::IntegerTyID:
00217       // INTEGER: [width]
00218       Code = bitc::TYPE_CODE_INTEGER;
00219       TypeVals.push_back(cast<IntegerType>(T)->getBitWidth());
00220       break;
00221     case Type::PointerTyID: {
00222       const PointerType *PTy = cast<PointerType>(T);
00223       // POINTER: [pointee type, address space]
00224       Code = bitc::TYPE_CODE_POINTER;
00225       TypeVals.push_back(VE.getTypeID(PTy->getElementType()));
00226       unsigned AddressSpace = PTy->getAddressSpace();
00227       TypeVals.push_back(AddressSpace);
00228       if (AddressSpace == 0) AbbrevToUse = PtrAbbrev;
00229       break;
00230     }
00231     case Type::FunctionTyID: {
00232       const FunctionType *FT = cast<FunctionType>(T);
00233       // FUNCTION: [isvararg, attrid, retty, paramty x N]
00234       Code = bitc::TYPE_CODE_FUNCTION;
00235       TypeVals.push_back(FT->isVarArg());
00236       TypeVals.push_back(0);  // FIXME: DEAD: remove in llvm 3.0
00237       TypeVals.push_back(VE.getTypeID(FT->getReturnType()));
00238       for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i)
00239         TypeVals.push_back(VE.getTypeID(FT->getParamType(i)));
00240       AbbrevToUse = FunctionAbbrev;
00241       break;
00242     }
00243     case Type::StructTyID: {
00244       const StructType *ST = cast<StructType>(T);
00245       // STRUCT: [ispacked, eltty x N]
00246       Code = bitc::TYPE_CODE_STRUCT;
00247       TypeVals.push_back(ST->isPacked());
00248       // Output all of the element types.
00249       for (StructType::element_iterator I = ST->element_begin(),
00250            E = ST->element_end(); I != E; ++I)
00251         TypeVals.push_back(VE.getTypeID(*I));
00252       AbbrevToUse = StructAbbrev;
00253       break;
00254     }
00255     case Type::ArrayTyID: {
00256       const ArrayType *AT = cast<ArrayType>(T);
00257       // ARRAY: [numelts, eltty]
00258       Code = bitc::TYPE_CODE_ARRAY;
00259       TypeVals.push_back(AT->getNumElements());
00260       TypeVals.push_back(VE.getTypeID(AT->getElementType()));
00261       AbbrevToUse = ArrayAbbrev;
00262       break;
00263     }
00264     case Type::VectorTyID: {
00265       const VectorType *VT = cast<VectorType>(T);
00266       // VECTOR [numelts, eltty]
00267       Code = bitc::TYPE_CODE_VECTOR;
00268       TypeVals.push_back(VT->getNumElements());
00269       TypeVals.push_back(VE.getTypeID(VT->getElementType()));
00270       break;
00271     }
00272     }
00273 
00274     // Emit the finished record.
00275     Stream.EmitRecord(Code, TypeVals, AbbrevToUse);
00276     TypeVals.clear();
00277   }
00278   
00279   Stream.ExitBlock();
00280 }
00281 
00282 static unsigned getEncodedLinkage(const GlobalValue *GV) {
00283   switch (GV->getLinkage()) {
00284   default: llvm_unreachable("Invalid linkage!");
00285   case GlobalValue::GhostLinkage:  // Map ghost linkage onto external.
00286   case GlobalValue::ExternalLinkage:            return 0;
00287   case GlobalValue::WeakAnyLinkage:             return 1;
00288   case GlobalValue::AppendingLinkage:           return 2;
00289   case GlobalValue::InternalLinkage:            return 3;
00290   case GlobalValue::LinkOnceAnyLinkage:         return 4;
00291   case GlobalValue::DLLImportLinkage:           return 5;
00292   case GlobalValue::DLLExportLinkage:           return 6;
00293   case GlobalValue::ExternalWeakLinkage:        return 7;
00294   case GlobalValue::CommonLinkage:              return 8;
00295   case GlobalValue::PrivateLinkage:             return 9;
00296   case GlobalValue::WeakODRLinkage:             return 10;
00297   case GlobalValue::LinkOnceODRLinkage:         return 11;
00298   case GlobalValue::AvailableExternallyLinkage: return 12;
00299   case GlobalValue::LinkerPrivateLinkage:       return 13;
00300   }
00301 }
00302 
00303 static unsigned getEncodedVisibility(const GlobalValue *GV) {
00304   switch (GV->getVisibility()) {
00305   default: llvm_unreachable("Invalid visibility!");
00306   case GlobalValue::DefaultVisibility:   return 0;
00307   case GlobalValue::HiddenVisibility:    return 1;
00308   case GlobalValue::ProtectedVisibility: return 2;
00309   }
00310 }
00311 
00312 // Emit top-level description of module, including target triple, inline asm,
00313 // descriptors for global variables, and function prototype info.
00314 static void WriteModuleInfo(const Module *M, const ValueEnumerator &VE,
00315                             BitstreamWriter &Stream) {
00316   // Emit the list of dependent libraries for the Module.
00317   for (Module::lib_iterator I = M->lib_begin(), E = M->lib_end(); I != E; ++I)
00318     WriteStringRecord(bitc::MODULE_CODE_DEPLIB, *I, 0/*TODO*/, Stream);
00319 
00320   // Emit various pieces of data attached to a module.
00321   if (!M->getTargetTriple().empty())
00322     WriteStringRecord(bitc::MODULE_CODE_TRIPLE, M->getTargetTriple(),
00323                       0/*TODO*/, Stream);
00324   if (!M->getDataLayout().empty())
00325     WriteStringRecord(bitc::MODULE_CODE_DATALAYOUT, M->getDataLayout(),
00326                       0/*TODO*/, Stream);
00327   if (!M->getModuleInlineAsm().empty())
00328     WriteStringRecord(bitc::MODULE_CODE_ASM, M->getModuleInlineAsm(),
00329                       0/*TODO*/, Stream);
00330 
00331   // Emit information about sections and GC, computing how many there are. Also
00332   // compute the maximum alignment value.
00333   std::map<std::string, unsigned> SectionMap;
00334   std::map<std::string, unsigned> GCMap;
00335   unsigned MaxAlignment = 0;
00336   unsigned MaxGlobalType = 0;
00337   for (Module::const_global_iterator GV = M->global_begin(),E = M->global_end();
00338        GV != E; ++GV) {
00339     MaxAlignment = std::max(MaxAlignment, GV->getAlignment());
00340     MaxGlobalType = std::max(MaxGlobalType, VE.getTypeID(GV->getType()));
00341     
00342     if (!GV->hasSection()) continue;
00343     // Give section names unique ID's.
00344     unsigned &Entry = SectionMap[GV->getSection()];
00345     if (Entry != 0) continue;
00346     WriteStringRecord(bitc::MODULE_CODE_SECTIONNAME, GV->getSection(),
00347                       0/*TODO*/, Stream);
00348     Entry = SectionMap.size();
00349   }
00350   for (Module::const_iterator F = M->begin(), E = M->end(); F != E; ++F) {
00351     MaxAlignment = std::max(MaxAlignment, F->getAlignment());
00352     if (F->hasSection()) {
00353       // Give section names unique ID's.
00354       unsigned &Entry = SectionMap[F->getSection()];
00355       if (!Entry) {
00356         WriteStringRecord(bitc::MODULE_CODE_SECTIONNAME, F->getSection(),
00357                           0/*TODO*/, Stream);
00358         Entry = SectionMap.size();
00359       }
00360     }
00361     if (F->hasGC()) {
00362       // Same for GC names.
00363       unsigned &Entry = GCMap[F->getGC()];
00364       if (!Entry) {
00365         WriteStringRecord(bitc::MODULE_CODE_GCNAME, F->getGC(),
00366                           0/*TODO*/, Stream);
00367         Entry = GCMap.size();
00368       }
00369     }
00370   }
00371   
00372   // Emit abbrev for globals, now that we know # sections and max alignment.
00373   unsigned SimpleGVarAbbrev = 0;
00374   if (!M->global_empty()) { 
00375     // Add an abbrev for common globals with no visibility or thread localness.
00376     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
00377     Abbv->Add(BitCodeAbbrevOp(bitc::MODULE_CODE_GLOBALVAR));
00378     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
00379                               Log2_32_Ceil(MaxGlobalType+1)));
00380     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));      // Constant.
00381     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));        // Initializer.
00382     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4));      // Linkage.
00383     if (MaxAlignment == 0)                                      // Alignment.
00384       Abbv->Add(BitCodeAbbrevOp(0));
00385     else {
00386       unsigned MaxEncAlignment = Log2_32(MaxAlignment)+1;
00387       Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
00388                                Log2_32_Ceil(MaxEncAlignment+1)));
00389     }
00390     if (SectionMap.empty())                                    // Section.
00391       Abbv->Add(BitCodeAbbrevOp(0));
00392     else
00393       Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
00394                                Log2_32_Ceil(SectionMap.size()+1)));
00395     // Don't bother emitting vis + thread local.
00396     SimpleGVarAbbrev = Stream.EmitAbbrev(Abbv);
00397   }
00398   
00399   // Emit the global variable information.
00400   SmallVector<unsigned, 64> Vals;
00401   for (Module::const_global_iterator GV = M->global_begin(),E = M->global_end();
00402        GV != E; ++GV) {
00403     unsigned AbbrevToUse = 0;
00404 
00405     // GLOBALVAR: [type, isconst, initid, 
00406     //             linkage, alignment, section, visibility, threadlocal]
00407     Vals.push_back(VE.getTypeID(GV->getType()));
00408     Vals.push_back(GV->isConstant());
00409     Vals.push_back(GV->isDeclaration() ? 0 :
00410                    (VE.getValueID(GV->getInitializer()) + 1));
00411     Vals.push_back(getEncodedLinkage(GV));
00412     Vals.push_back(Log2_32(GV->getAlignment())+1);
00413     Vals.push_back(GV->hasSection() ? SectionMap[GV->getSection()] : 0);
00414     if (GV->isThreadLocal() || 
00415         GV->getVisibility() != GlobalValue::DefaultVisibility) {
00416       Vals.push_back(getEncodedVisibility(GV));
00417       Vals.push_back(GV->isThreadLocal());
00418     } else {
00419       AbbrevToUse = SimpleGVarAbbrev;
00420     }
00421     
00422     Stream.EmitRecord(bitc::MODULE_CODE_GLOBALVAR, Vals, AbbrevToUse);
00423     Vals.clear();
00424   }
00425 
00426   // Emit the function proto information.
00427   for (Module::const_iterator F = M->begin(), E = M->end(); F != E; ++F) {
00428     // FUNCTION:  [type, callingconv, isproto, paramattr,
00429     //             linkage, alignment, section, visibility, gc]
00430     Vals.push_back(VE.getTypeID(F->getType()));
00431     Vals.push_back(F->getCallingConv());
00432     Vals.push_back(F->isDeclaration());
00433     Vals.push_back(getEncodedLinkage(F));
00434     Vals.push_back(VE.getAttributeID(F->getAttributes()));
00435     Vals.push_back(Log2_32(F->getAlignment())+1);
00436     Vals.push_back(F->hasSection() ? SectionMap[F->getSection()] : 0);
00437     Vals.push_back(getEncodedVisibility(F));
00438     Vals.push_back(F->hasGC() ? GCMap[F->getGC()] : 0);
00439     
00440     unsigned AbbrevToUse = 0;
00441     Stream.EmitRecord(bitc::MODULE_CODE_FUNCTION, Vals, AbbrevToUse);
00442     Vals.clear();
00443   }
00444   
00445   
00446   // Emit the alias information.
00447   for (Module::const_alias_iterator AI = M->alias_begin(), E = M->alias_end();
00448        AI != E; ++AI) {
00449     Vals.push_back(VE.getTypeID(AI->getType()));
00450     Vals.push_back(VE.getValueID(AI->getAliasee()));
00451     Vals.push_back(getEncodedLinkage(AI));
00452     Vals.push_back(getEncodedVisibility(AI));
00453     unsigned AbbrevToUse = 0;
00454     Stream.EmitRecord(bitc::MODULE_CODE_ALIAS, Vals, AbbrevToUse);
00455     Vals.clear();
00456   }
00457 }
00458 
00459 static uint64_t GetOptimizationFlags(const Value *V) {
00460   uint64_t Flags = 0;
00461 
00462   if (const OverflowingBinaryOperator *OBO =
00463         dyn_cast<OverflowingBinaryOperator>(V)) {
00464     if (OBO->hasNoSignedWrap())
00465       Flags |= 1 << bitc::OBO_NO_SIGNED_WRAP;
00466     if (OBO->hasNoUnsignedWrap())
00467       Flags |= 1 << bitc::OBO_NO_UNSIGNED_WRAP;
00468   } else if (const SDivOperator *Div = dyn_cast<SDivOperator>(V)) {
00469     if (Div->isExact())
00470       Flags |= 1 << bitc::SDIV_EXACT;
00471   }
00472 
00473   return Flags;
00474 }
00475 
00476 static void WriteMDNode(const MDNode *N,
00477                         const ValueEnumerator &VE,
00478                         BitstreamWriter &Stream,
00479                         SmallVector<uint64_t, 64> &Record) {
00480   for (unsigned i = 0, e = N->getNumElements(); i != e; ++i) {
00481     if (N->getElement(i)) {
00482       Record.push_back(VE.getTypeID(N->getElement(i)->getType()));
00483       Record.push_back(VE.getValueID(N->getElement(i)));
00484     } else {
00485       Record.push_back(VE.getTypeID(Type::getVoidTy(N->getContext())));
00486       Record.push_back(0);
00487     }
00488   }
00489   Stream.EmitRecord(bitc::METADATA_NODE, Record, 0);
00490   Record.clear();
00491 }
00492 
00493 static void WriteModuleMetadata(const ValueEnumerator &VE,
00494                                 BitstreamWriter &Stream) {
00495   const ValueEnumerator::ValueList &Vals = VE.getMDValues();
00496   bool StartedMetadataBlock = false;
00497   unsigned MDSAbbrev = 0;
00498   SmallVector<uint64_t, 64> Record;
00499   for (unsigned i = 0, e = Vals.size(); i != e; ++i) {
00500     
00501     if (const MDNode *N = dyn_cast<MDNode>(Vals[i].first)) {
00502       if (!StartedMetadataBlock) {
00503         Stream.EnterSubblock(bitc::METADATA_BLOCK_ID, 3);
00504         StartedMetadataBlock = true;
00505       }
00506       WriteMDNode(N, VE, Stream, Record);
00507     } else if (const MDString *MDS = dyn_cast<MDString>(Vals[i].first)) {
00508       if (!StartedMetadataBlock)  {
00509         Stream.EnterSubblock(bitc::METADATA_BLOCK_ID, 3);
00510         
00511         // Abbrev for METADATA_STRING.
00512         BitCodeAbbrev *Abbv = new BitCodeAbbrev();
00513         Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_STRING));
00514         Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
00515         Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
00516         MDSAbbrev = Stream.EmitAbbrev(Abbv);
00517         StartedMetadataBlock = true;
00518       }
00519       
00520       // Code: [strchar x N]
00521       const char *StrBegin = MDS->begin();
00522       for (unsigned i = 0, e = MDS->length(); i != e; ++i)
00523         Record.push_back(StrBegin[i]);
00524       
00525       // Emit the finished record.
00526       Stream.EmitRecord(bitc::METADATA_STRING, Record, MDSAbbrev);
00527       Record.clear();
00528     } else if (const NamedMDNode *NMD = dyn_cast<NamedMDNode>(Vals[i].first)) {
00529       if (!StartedMetadataBlock)  {
00530         Stream.EnterSubblock(bitc::METADATA_BLOCK_ID, 3);
00531         StartedMetadataBlock = true;
00532       }
00533 
00534       // Write name.
00535       std::string Str = NMD->getNameStr();
00536       const char *StrBegin = Str.c_str();
00537       for (unsigned i = 0, e = Str.length(); i != e; ++i)
00538         Record.push_back(StrBegin[i]);
00539       Stream.EmitRecord(bitc::METADATA_NAME, Record, 0/*TODO*/);
00540       Record.clear();
00541 
00542       // Write named metadata elements.
00543       for (unsigned i = 0, e = NMD->getNumElements(); i != e; ++i) {
00544         if (NMD->getElement(i)) 
00545           Record.push_back(VE.getValueID(NMD->getElement(i)));
00546         else 
00547           Record.push_back(0);
00548       }
00549       Stream.EmitRecord(bitc::METADATA_NAMED_NODE, Record, 0);
00550       Record.clear();
00551     }
00552   }
00553   
00554   if (StartedMetadataBlock)
00555     Stream.ExitBlock();    
00556 }
00557 
00558 static void WriteConstants(unsigned FirstVal, unsigned LastVal,
00559                            const ValueEnumerator &VE,
00560                            BitstreamWriter &Stream, bool isGlobal) {
00561   if (FirstVal == LastVal) return;
00562   
00563   Stream.EnterSubblock(bitc::CONSTANTS_BLOCK_ID, 4);
00564 
00565   unsigned AggregateAbbrev = 0;
00566   unsigned String8Abbrev = 0;
00567   unsigned CString7Abbrev = 0;
00568   unsigned CString6Abbrev = 0;
00569   // If this is a constant pool for the module, emit module-specific abbrevs.
00570   if (isGlobal) {
00571     // Abbrev for CST_CODE_AGGREGATE.
00572     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
00573     Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_AGGREGATE));
00574     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
00575     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, Log2_32_Ceil(LastVal+1)));
00576     AggregateAbbrev = Stream.EmitAbbrev(Abbv);
00577 
00578     // Abbrev for CST_CODE_STRING.
00579     Abbv = new BitCodeAbbrev();
00580     Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_STRING));
00581     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
00582     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
00583     String8Abbrev = Stream.EmitAbbrev(Abbv);
00584     // Abbrev for CST_CODE_CSTRING.
00585     Abbv = new BitCodeAbbrev();
00586     Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_CSTRING));
00587     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
00588     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7));
00589     CString7Abbrev = Stream.EmitAbbrev(Abbv);
00590     // Abbrev for CST_CODE_CSTRING.
00591     Abbv = new BitCodeAbbrev();
00592     Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_CSTRING));
00593     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
00594     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
00595     CString6Abbrev = Stream.EmitAbbrev(Abbv);
00596   }  
00597   
00598   SmallVector<uint64_t, 64> Record;
00599 
00600   const ValueEnumerator::ValueList &Vals = VE.getValues();
00601   const Type *LastTy = 0;
00602   for (unsigned i = FirstVal; i != LastVal; ++i) {
00603     const Value *V = Vals[i].first;
00604     // If we need to switch types, do so now.
00605     if (V->getType() != LastTy) {
00606       LastTy = V->getType();
00607       Record.push_back(VE.getTypeID(LastTy));
00608       Stream.EmitRecord(bitc::CST_CODE_SETTYPE, Record,
00609                         CONSTANTS_SETTYPE_ABBREV);
00610       Record.clear();
00611     }
00612     
00613     if (const InlineAsm *IA = dyn_cast<InlineAsm>(V)) {
00614       Record.push_back(unsigned(IA->hasSideEffects()));
00615       
00616       // Add the asm string.
00617       const std::string &AsmStr = IA->getAsmString();
00618       Record.push_back(AsmStr.size());
00619       for (unsigned i = 0, e = AsmStr.size(); i != e; ++i)
00620         Record.push_back(AsmStr[i]);
00621       
00622       // Add the constraint string.
00623       const std::string &ConstraintStr = IA->getConstraintString();
00624       Record.push_back(ConstraintStr.size());
00625       for (unsigned i = 0, e = ConstraintStr.size(); i != e; ++i)
00626         Record.push_back(ConstraintStr[i]);
00627       Stream.EmitRecord(bitc::CST_CODE_INLINEASM, Record);
00628       Record.clear();
00629       continue;
00630     }
00631     const Constant *C = cast<Constant>(V);
00632     unsigned Code = -1U;
00633     unsigned AbbrevToUse = 0;
00634     if (C->isNullValue()) {
00635       Code = bitc::CST_CODE_NULL;
00636     } else if (isa<UndefValue>(C)) {
00637       Code = bitc::CST_CODE_UNDEF;
00638     } else if (const ConstantInt *IV = dyn_cast<ConstantInt>(C)) {
00639       if (IV->getBitWidth() <= 64) {
00640         int64_t V = IV->getSExtValue();
00641         if (V >= 0)
00642           Record.push_back(V << 1);
00643         else
00644           Record.push_back((-V << 1) | 1);
00645         Code = bitc::CST_CODE_INTEGER;
00646         AbbrevToUse = CONSTANTS_INTEGER_ABBREV;
00647       } else {                             // Wide integers, > 64 bits in size.
00648         // We have an arbitrary precision integer value to write whose 
00649         // bit width is > 64. However, in canonical unsigned integer 
00650         // format it is likely that the high bits are going to be zero.
00651         // So, we only write the number of active words.
00652         unsigned NWords = IV->getValue().getActiveWords(); 
00653         const uint64_t *RawWords = IV->getValue().getRawData();
00654         for (unsigned i = 0; i != NWords; ++i) {
00655           int64_t V = RawWords[i];
00656           if (V >= 0)
00657             Record.push_back(V << 1);
00658           else
00659             Record.push_back((-V << 1) | 1);
00660         }
00661         Code = bitc::CST_CODE_WIDE_INTEGER;
00662       }
00663     } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
00664       Code = bitc::CST_CODE_FLOAT;
00665       const Type *Ty = CFP->getType();
00666       if (Ty == Type::getFloatTy(Ty->getContext()) ||
00667           Ty == Type::getDoubleTy(Ty->getContext())) {
00668         Record.push_back(CFP->getValueAPF().bitcastToAPInt().getZExtValue());
00669       } else if (Ty == Type::getX86_FP80Ty(Ty->getContext())) {
00670         // api needed to prevent premature destruction
00671         // bits are not in the same order as a normal i80 APInt, compensate.
00672         APInt api = CFP->getValueAPF().bitcastToAPInt();
00673         const uint64_t *p = api.getRawData();
00674         Record.push_back((p[1] << 48) | (p[0] >> 16));
00675         Record.push_back(p[0] & 0xffffLL);
00676       } else if (Ty == Type::getFP128Ty(Ty->getContext()) ||
00677                  Ty == Type::getPPC_FP128Ty(Ty->getContext())) {
00678         APInt api = CFP->getValueAPF().bitcastToAPInt();
00679         const uint64_t *p = api.getRawData();
00680         Record.push_back(p[0]);
00681         Record.push_back(p[1]);
00682       } else {
00683         assert (0 && "Unknown FP type!");
00684       }
00685     } else if (isa<ConstantArray>(C) && cast<ConstantArray>(C)->isString()) {
00686       // Emit constant strings specially.
00687       unsigned NumOps = C->getNumOperands();
00688       // If this is a null-terminated string, use the denser CSTRING encoding.
00689       if (C->getOperand(NumOps-1)->isNullValue()) {
00690         Code = bitc::CST_CODE_CSTRING;
00691         --NumOps;  // Don't encode the null, which isn't allowed by char6.
00692       } else {
00693         Code = bitc::CST_CODE_STRING;
00694         AbbrevToUse = String8Abbrev;
00695       }
00696       bool isCStr7 = Code == bitc::CST_CODE_CSTRING;
00697       bool isCStrChar6 = Code == bitc::CST_CODE_CSTRING;
00698       for (unsigned i = 0; i != NumOps; ++i) {
00699         unsigned char V = cast<ConstantInt>(C->getOperand(i))->getZExtValue();
00700         Record.push_back(V);
00701         isCStr7 &= (V & 128) == 0;
00702         if (isCStrChar6) 
00703           isCStrChar6 = BitCodeAbbrevOp::isChar6(V);
00704       }
00705       
00706       if (isCStrChar6)
00707         AbbrevToUse = CString6Abbrev;
00708       else if (isCStr7)
00709         AbbrevToUse = CString7Abbrev;
00710     } else if (isa<ConstantArray>(C) || isa<ConstantStruct>(V) ||
00711                isa<ConstantVector>(V)) {
00712       Code = bitc::CST_CODE_AGGREGATE;
00713       for (unsigned i = 0, e = C->getNumOperands(); i != e; ++i)
00714         Record.push_back(VE.getValueID(C->getOperand(i)));
00715       AbbrevToUse = AggregateAbbrev;
00716     } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
00717       switch (CE->getOpcode()) {
00718       default:
00719         if (Instruction::isCast(CE->getOpcode())) {
00720           Code = bitc::CST_CODE_CE_CAST;
00721           Record.push_back(GetEncodedCastOpcode(CE->getOpcode()));
00722           Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
00723           Record.push_back(VE.getValueID(C->getOperand(0)));
00724           AbbrevToUse = CONSTANTS_CE_CAST_Abbrev;
00725         } else {
00726           assert(CE->getNumOperands() == 2 && "Unknown constant expr!");
00727           Code = bitc::CST_CODE_CE_BINOP;
00728           Record.push_back(GetEncodedBinaryOpcode(CE->getOpcode()));
00729           Record.push_back(VE.getValueID(C->getOperand(0)));
00730           Record.push_back(VE.getValueID(C->getOperand(1)));
00731           uint64_t Flags = GetOptimizationFlags(CE);
00732           if (Flags != 0)
00733             Record.push_back(Flags);
00734         }
00735         break;
00736       case Instruction::GetElementPtr:
00737         Code = bitc::CST_CODE_CE_GEP;
00738         if (cast<GEPOperator>(C)->isInBounds())
00739           Code = bitc::CST_CODE_CE_INBOUNDS_GEP;
00740         for (unsigned i = 0, e = CE->getNumOperands(); i != e; ++i) {
00741           Record.push_back(VE.getTypeID(C->getOperand(i)->getType()));
00742           Record.push_back(VE.getValueID(C->getOperand(i)));
00743         }
00744         break;
00745       case Instruction::Select:
00746         Code = bitc::CST_CODE_CE_SELECT;
00747         Record.push_back(VE.getValueID(C->getOperand(0)));
00748         Record.push_back(VE.getValueID(C->getOperand(1)));
00749         Record.push_back(VE.getValueID(C->getOperand(2)));
00750         break;
00751       case Instruction::ExtractElement:
00752         Code = bitc::CST_CODE_CE_EXTRACTELT;
00753         Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
00754         Record.push_back(VE.getValueID(C->getOperand(0)));
00755         Record.push_back(VE.getValueID(C->getOperand(1)));
00756         break;
00757       case Instruction::InsertElement:
00758         Code = bitc::CST_CODE_CE_INSERTELT;
00759         Record.push_back(VE.getValueID(C->getOperand(0)));
00760         Record.push_back(VE.getValueID(C->getOperand(1)));
00761         Record.push_back(VE.getValueID(C->getOperand(2)));
00762         break;
00763       case Instruction::ShuffleVector:
00764         // If the return type and argument types are the same, this is a
00765         // standard shufflevector instruction.  If the types are different,
00766         // then the shuffle is widening or truncating the input vectors, and
00767         // the argument type must also be encoded.
00768         if (C->getType() == C->getOperand(0)->getType()) {
00769           Code = bitc::CST_CODE_CE_SHUFFLEVEC;
00770         } else {
00771           Code = bitc::CST_CODE_CE_SHUFVEC_EX;
00772           Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
00773         }
00774         Record.push_back(VE.getValueID(C->getOperand(0)));
00775         Record.push_back(VE.getValueID(C->getOperand(1)));
00776         Record.push_back(VE.getValueID(C->getOperand(2)));
00777         break;
00778       case Instruction::ICmp:
00779       case Instruction::FCmp:
00780         Code = bitc::CST_CODE_CE_CMP;
00781         Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
00782         Record.push_back(VE.getValueID(C->getOperand(0)));
00783         Record.push_back(VE.getValueID(C->getOperand(1)));
00784         Record.push_back(CE->getPredicate());
00785         break;
00786       }
00787     } else {
00788       llvm_unreachable("Unknown constant!");
00789     }
00790     Stream.EmitRecord(Code, Record, AbbrevToUse);
00791     Record.clear();
00792   }
00793 
00794   Stream.ExitBlock();
00795 }
00796 
00797 static void WriteModuleConstants(const ValueEnumerator &VE,
00798                                  BitstreamWriter &Stream) {
00799   const ValueEnumerator::ValueList &Vals = VE.getValues();
00800   
00801   // Find the first constant to emit, which is the first non-globalvalue value.
00802   // We know globalvalues have been emitted by WriteModuleInfo.
00803   for (unsigned i = 0, e = Vals.size(); i != e; ++i) {
00804     if (!isa<GlobalValue>(Vals[i].first)) {
00805       WriteConstants(i, Vals.size(), VE, Stream, true);
00806       return;
00807     }
00808   }
00809 }
00810 
00811 /// PushValueAndType - The file has to encode both the value and type id for
00812 /// many values, because we need to know what type to create for forward
00813 /// references.  However, most operands are not forward references, so this type
00814 /// field is not needed.
00815 ///
00816 /// This function adds V's value ID to Vals.  If the value ID is higher than the
00817 /// instruction ID, then it is a forward reference, and it also includes the
00818 /// type ID.
00819 static bool PushValueAndType(const Value *V, unsigned InstID,
00820                              SmallVector<unsigned, 64> &Vals, 
00821                              ValueEnumerator &VE) {
00822   unsigned ValID = VE.getValueID(V);
00823   Vals.push_back(ValID);
00824   if (ValID >= InstID) {
00825     Vals.push_back(VE.getTypeID(V->getType()));
00826     return true;
00827   }
00828   return false;
00829 }
00830 
00831 /// WriteInstruction - Emit an instruction to the specified stream.
00832 static void WriteInstruction(const Instruction &I, unsigned InstID,
00833                              ValueEnumerator &VE, BitstreamWriter &Stream,
00834                              SmallVector<unsigned, 64> &Vals) {
00835   unsigned Code = 0;
00836   unsigned AbbrevToUse = 0;
00837   switch (I.getOpcode()) {
00838   default:
00839     if (Instruction::isCast(I.getOpcode())) {
00840       Code = bitc::FUNC_CODE_INST_CAST;
00841       if (!PushValueAndType(I.getOperand(0), InstID, Vals, VE))
00842         AbbrevToUse = FUNCTION_INST_CAST_ABBREV;
00843       Vals.push_back(VE.getTypeID(I.getType()));
00844       Vals.push_back(GetEncodedCastOpcode(I.getOpcode()));
00845     } else {
00846       assert(isa<BinaryOperator>(I) && "Unknown instruction!");
00847       Code = bitc::FUNC_CODE_INST_BINOP;
00848       if (!PushValueAndType(I.getOperand(0), InstID, Vals, VE))
00849         AbbrevToUse = FUNCTION_INST_BINOP_ABBREV;
00850       Vals.push_back(VE.getValueID(I.getOperand(1)));
00851       Vals.push_back(GetEncodedBinaryOpcode(I.getOpcode()));
00852       uint64_t Flags = GetOptimizationFlags(&I);
00853       if (Flags != 0) {
00854         if (AbbrevToUse == FUNCTION_INST_BINOP_ABBREV)
00855           AbbrevToUse = FUNCTION_INST_BINOP_FLAGS_ABBREV;
00856         Vals.push_back(Flags);
00857       }
00858     }
00859     break;
00860 
00861   case Instruction::GetElementPtr:
00862     Code = bitc::FUNC_CODE_INST_GEP;
00863     if (cast<GEPOperator>(&I)->isInBounds())
00864       Code = bitc::FUNC_CODE_INST_INBOUNDS_GEP;
00865     for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
00866       PushValueAndType(I.getOperand(i), InstID, Vals, VE);
00867     break;
00868   case Instruction::ExtractValue: {
00869     Code = bitc::FUNC_CODE_INST_EXTRACTVAL;
00870     PushValueAndType(I.getOperand(0), InstID, Vals, VE);
00871     const ExtractValueInst *EVI = cast<ExtractValueInst>(&I);
00872     for (const unsigned *i = EVI->idx_begin(), *e = EVI->idx_end(); i != e; ++i)
00873       Vals.push_back(*i);
00874     break;
00875   }
00876   case Instruction::InsertValue: {
00877     Code = bitc::FUNC_CODE_INST_INSERTVAL;
00878     PushValueAndType(I.getOperand(0), InstID, Vals, VE);
00879     PushValueAndType(I.getOperand(1), InstID, Vals, VE);
00880     const InsertValueInst *IVI = cast<InsertValueInst>(&I);
00881     for (const unsigned *i = IVI->idx_begin(), *e = IVI->idx_end(); i != e; ++i)
00882       Vals.push_back(*i);
00883     break;
00884   }
00885   case Instruction::Select:
00886     Code = bitc::FUNC_CODE_INST_VSELECT;
00887     PushValueAndType(I.getOperand(1), InstID, Vals, VE);
00888     Vals.push_back(VE.getValueID(I.getOperand(2)));
00889     PushValueAndType(I.getOperand(0), InstID, Vals, VE);
00890     break;
00891   case Instruction::ExtractElement:
00892     Code = bitc::FUNC_CODE_INST_EXTRACTELT;
00893     PushValueAndType(I.getOperand(0), InstID, Vals, VE);
00894     Vals.push_back(VE.getValueID(I.getOperand(1)));
00895     break;
00896   case Instruction::InsertElement:
00897     Code = bitc::FUNC_CODE_INST_INSERTELT;
00898     PushValueAndType(I.getOperand(0), InstID, Vals, VE);
00899     Vals.push_back(VE.getValueID(I.getOperand(1)));
00900     Vals.push_back(VE.getValueID(I.getOperand(2)));
00901     break;
00902   case Instruction::ShuffleVector:
00903     Code = bitc::FUNC_CODE_INST_SHUFFLEVEC;
00904     PushValueAndType(I.getOperand(0), InstID, Vals, VE);
00905     Vals.push_back(VE.getValueID(I.getOperand(1)));
00906     Vals.push_back(VE.getValueID(I.getOperand(2)));
00907     break;
00908   case Instruction::ICmp:
00909   case Instruction::FCmp:
00910     // compare returning Int1Ty or vector of Int1Ty
00911     Code = bitc::FUNC_CODE_INST_CMP2;
00912     PushValueAndType(I.getOperand(0), InstID, Vals, VE);
00913     Vals.push_back(VE.getValueID(I.getOperand(1)));
00914     Vals.push_back(cast<CmpInst>(I).getPredicate());
00915     break;
00916 
00917   case Instruction::Ret: 
00918     {
00919       Code = bitc::FUNC_CODE_INST_RET;
00920       unsigned NumOperands = I.getNumOperands();
00921       if (NumOperands == 0)
00922         AbbrevToUse = FUNCTION_INST_RET_VOID_ABBREV;
00923       else if (NumOperands == 1) {
00924         if (!PushValueAndType(I.getOperand(0), InstID, Vals, VE))
00925           AbbrevToUse = FUNCTION_INST_RET_VAL_ABBREV;
00926       } else {
00927         for (unsigned i = 0, e = NumOperands; i != e; ++i)
00928           PushValueAndType(I.getOperand(i), InstID, Vals, VE);
00929       }
00930     }
00931     break;
00932   case Instruction::Br:
00933     {
00934       Code = bitc::FUNC_CODE_INST_BR;
00935       BranchInst &II(cast<BranchInst>(I));
00936       Vals.push_back(VE.getValueID(II.getSuccessor(0)));
00937       if (II.isConditional()) {
00938         Vals.push_back(VE.getValueID(II.getSuccessor(1)));
00939         Vals.push_back(VE.getValueID(II.getCondition()));
00940       }
00941     }
00942     break;
00943   case Instruction::Switch:
00944     Code = bitc::FUNC_CODE_INST_SWITCH;
00945     Vals.push_back(VE.getTypeID(I.getOperand(0)->getType()));
00946     for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
00947       Vals.push_back(VE.getValueID(I.getOperand(i)));
00948     break;
00949   case Instruction::Invoke: {
00950     const InvokeInst *II = cast<InvokeInst>(&I);
00951     const Value *Callee(II->getCalledValue());
00952     const PointerType *PTy = cast<PointerType>(Callee->getType());
00953     const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
00954     Code = bitc::FUNC_CODE_INST_INVOKE;
00955     
00956     Vals.push_back(VE.getAttributeID(II->getAttributes()));
00957     Vals.push_back(II->getCallingConv());
00958     Vals.push_back(VE.getValueID(II->getNormalDest()));
00959     Vals.push_back(VE.getValueID(II->getUnwindDest()));
00960     PushValueAndType(Callee, InstID, Vals, VE);
00961     
00962     // Emit value #'s for the fixed parameters.
00963     for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
00964       Vals.push_back(VE.getValueID(I.getOperand(i+3)));  // fixed param.
00965 
00966     // Emit type/value pairs for varargs params.
00967     if (FTy->isVarArg()) {
00968       for (unsigned i = 3+FTy->getNumParams(), e = I.getNumOperands();
00969            i != e; ++i)
00970         PushValueAndType(I.getOperand(i), InstID, Vals, VE); // vararg
00971     }
00972     break;
00973   }
00974   case Instruction::Unwind:
00975     Code = bitc::FUNC_CODE_INST_UNWIND;
00976     break;
00977   case Instruction::Unreachable:
00978     Code = bitc::FUNC_CODE_INST_UNREACHABLE;
00979     AbbrevToUse = FUNCTION_INST_UNREACHABLE_ABBREV;
00980     break;
00981   
00982   case Instruction::PHI:
00983     Code = bitc::FUNC_CODE_INST_PHI;
00984     Vals.push_back(VE.getTypeID(I.getType()));
00985     for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
00986       Vals.push_back(VE.getValueID(I.getOperand(i)));
00987     break;
00988     
00989   case Instruction::Malloc:
00990     Code = bitc::FUNC_CODE_INST_MALLOC;
00991     Vals.push_back(VE.getTypeID(I.getType()));
00992     Vals.push_back(VE.getValueID(I.getOperand(0))); // size.
00993     Vals.push_back(Log2_32(cast<MallocInst>(I).getAlignment())+1);
00994     break;
00995     
00996   case Instruction::Free:
00997     Code = bitc::FUNC_CODE_INST_FREE;
00998     PushValueAndType(I.getOperand(0), InstID, Vals, VE);
00999     break;
01000     
01001   case Instruction::Alloca:
01002     Code = bitc::FUNC_CODE_INST_ALLOCA;
01003     Vals.push_back(VE.getTypeID(I.getType()));
01004     Vals.push_back(VE.getValueID(I.getOperand(0))); // size.
01005     Vals.push_back(Log2_32(cast<AllocaInst>(I).getAlignment())+1);
01006     break;
01007     
01008   case Instruction::Load:
01009     Code = bitc::FUNC_CODE_INST_LOAD;
01010     if (!PushValueAndType(I.getOperand(0), InstID, Vals, VE))  // ptr
01011       AbbrevToUse = FUNCTION_INST_LOAD_ABBREV;
01012       
01013     Vals.push_back(Log2_32(cast<LoadInst>(I).getAlignment())+1);
01014     Vals.push_back(cast<LoadInst>(I).isVolatile());
01015     break;
01016   case Instruction::Store:
01017     Code = bitc::FUNC_CODE_INST_STORE2;
01018     PushValueAndType(I.getOperand(1), InstID, Vals, VE);  // ptrty + ptr
01019     Vals.push_back(VE.getValueID(I.getOperand(0)));       // val.
01020     Vals.push_back(Log2_32(cast<StoreInst>(I).getAlignment())+1);
01021     Vals.push_back(cast<StoreInst>(I).isVolatile());
01022     break;
01023   case Instruction::Call: {
01024     const PointerType *PTy = cast<PointerType>(I.getOperand(0)->getType());
01025     const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
01026 
01027     Code = bitc::FUNC_CODE_INST_CALL;
01028     
01029     const CallInst *CI = cast<CallInst>(&I);
01030     Vals.push_back(VE.getAttributeID(CI->getAttributes()));
01031     Vals.push_back((CI->getCallingConv() << 1) | unsigned(CI->isTailCall()));
01032     PushValueAndType(CI->getOperand(0), InstID, Vals, VE);  // Callee
01033     
01034     // Emit value #'s for the fixed parameters.
01035     for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
01036       Vals.push_back(VE.getValueID(I.getOperand(i+1)));  // fixed param.
01037       
01038     // Emit type/value pairs for varargs params.
01039     if (FTy->isVarArg()) {
01040       unsigned NumVarargs = I.getNumOperands()-1-FTy->getNumParams();
01041       for (unsigned i = I.getNumOperands()-NumVarargs, e = I.getNumOperands();
01042            i != e; ++i)
01043         PushValueAndType(I.getOperand(i), InstID, Vals, VE);  // varargs
01044     }
01045     break;
01046   }
01047   case Instruction::VAArg:
01048     Code = bitc::FUNC_CODE_INST_VAARG;
01049     Vals.push_back(VE.getTypeID(I.getOperand(0)->getType()));   // valistty
01050     Vals.push_back(VE.getValueID(I.getOperand(0))); // valist.
01051     Vals.push_back(VE.getTypeID(I.getType())); // restype.
01052     break;
01053   }
01054   
01055   Stream.EmitRecord(Code, Vals, AbbrevToUse);
01056   Vals.clear();
01057 }
01058 
01059 // Emit names for globals/functions etc.
01060 static void WriteValueSymbolTable(const ValueSymbolTable &VST,
01061                                   const ValueEnumerator &VE,
01062                                   BitstreamWriter &Stream) {
01063   if (VST.empty()) return;
01064   Stream.EnterSubblock(bitc::VALUE_SYMTAB_BLOCK_ID, 4);
01065 
01066   // FIXME: Set up the abbrev, we know how many values there are!
01067   // FIXME: We know if the type names can use 7-bit ascii.
01068   SmallVector<unsigned, 64> NameVals;
01069   
01070   for (ValueSymbolTable::const_iterator SI = VST.begin(), SE = VST.end();
01071        SI != SE; ++SI) {
01072     
01073     const ValueName &Name = *SI;
01074     
01075     // Figure out the encoding to use for the name.
01076     bool is7Bit = true;
01077     bool isChar6 = true;
01078     for (const char *C = Name.getKeyData(), *E = C+Name.getKeyLength();
01079          C != E; ++C) {
01080       if (isChar6) 
01081         isChar6 = BitCodeAbbrevOp::isChar6(*C);
01082       if ((unsigned char)*C & 128) {
01083         is7Bit = false;
01084         break;  // don't bother scanning the rest.
01085       }
01086     }
01087     
01088     unsigned AbbrevToUse = VST_ENTRY_8_ABBREV;
01089     
01090     // VST_ENTRY:   [valueid, namechar x N]
01091     // VST_BBENTRY: [bbid, namechar x N]
01092     unsigned Code;
01093     if (isa<BasicBlock>(SI->getValue())) {
01094       Code = bitc::VST_CODE_BBENTRY;
01095       if (isChar6)
01096         AbbrevToUse = VST_BBENTRY_6_ABBREV;
01097     } else {
01098       Code = bitc::VST_CODE_ENTRY;
01099       if (isChar6)
01100         AbbrevToUse = VST_ENTRY_6_ABBREV;
01101       else if (is7Bit)
01102         AbbrevToUse = VST_ENTRY_7_ABBREV;
01103     }
01104     
01105     NameVals.push_back(VE.getValueID(SI->getValue()));
01106     for (const char *P = Name.getKeyData(),
01107          *E = Name.getKeyData()+Name.getKeyLength(); P != E; ++P)
01108       NameVals.push_back((unsigned char)*P);
01109     
01110     // Emit the finished record.
01111     Stream.EmitRecord(Code, NameVals, AbbrevToUse);
01112     NameVals.clear();
01113   }
01114   Stream.ExitBlock();
01115 }
01116 
01117 /// WriteFunction - Emit a function body to the module stream.
01118 static void WriteFunction(const Function &F, ValueEnumerator &VE, 
01119                           BitstreamWriter &Stream) {
01120   Stream.EnterSubblock(bitc::FUNCTION_BLOCK_ID, 4);
01121   VE.incorporateFunction(F);
01122 
01123   SmallVector<unsigned, 64> Vals;
01124   
01125   // Emit the number of basic blocks, so the reader can create them ahead of
01126   // time.
01127   Vals.push_back(VE.getBasicBlocks().size());
01128   Stream.EmitRecord(bitc::FUNC_CODE_DECLAREBLOCKS, Vals);
01129   Vals.clear();
01130   
01131   // If there are function-local constants, emit them now.
01132   unsigned CstStart, CstEnd;
01133   VE.getFunctionConstantRange(CstStart, CstEnd);
01134   WriteConstants(CstStart, CstEnd, VE, Stream, false);
01135   
01136   // Keep a running idea of what the instruction ID is. 
01137   unsigned InstID = CstEnd;
01138   
01139   // Finally, emit all the instructions, in order.
01140   for (Function::const_iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
01141     for (BasicBlock::const_iterator I = BB->begin(), E = BB->end();
01142          I != E; ++I) {
01143       WriteInstruction(*I, InstID, VE, Stream, Vals);
01144       if (I->getType() != Type::getVoidTy(F.getContext()))
01145         ++InstID;
01146     }
01147   
01148   // Emit names for all the instructions etc.
01149   WriteValueSymbolTable(F.getValueSymbolTable(), VE, Stream);
01150     
01151   VE.purgeFunction();
01152   Stream.ExitBlock();
01153 }
01154 
01155 /// WriteTypeSymbolTable - Emit a block for the specified type symtab.
01156 static void WriteTypeSymbolTable(const TypeSymbolTable &TST,
01157                                  const ValueEnumerator &VE,
01158                                  BitstreamWriter &Stream) {
01159   if (TST.empty()) return;
01160   
01161   Stream.EnterSubblock(bitc::TYPE_SYMTAB_BLOCK_ID, 3);
01162   
01163   // 7-bit fixed width VST_CODE_ENTRY strings.
01164   BitCodeAbbrev *Abbv = new BitCodeAbbrev();
01165   Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_ENTRY));
01166   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
01167                             Log2_32_Ceil(VE.getTypes().size()+1)));
01168   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
01169   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7));
01170   unsigned V7Abbrev = Stream.EmitAbbrev(Abbv);
01171   
01172   SmallVector<unsigned, 64> NameVals;
01173   
01174   for (TypeSymbolTable::const_iterator TI = TST.begin(), TE = TST.end(); 
01175        TI != TE; ++TI) {
01176     // TST_ENTRY: [typeid, namechar x N]
01177     NameVals.push_back(VE.getTypeID(TI->second));
01178     
01179     const std::string &Str = TI->first;
01180     bool is7Bit = true;
01181     for (unsigned i = 0, e = Str.size(); i != e; ++i) {
01182       NameVals.push_back((unsigned char)Str[i]);
01183       if (Str[i] & 128)
01184         is7Bit = false;
01185     }
01186     
01187     // Emit the finished record.
01188     Stream.EmitRecord(bitc::VST_CODE_ENTRY, NameVals, is7Bit ? V7Abbrev : 0);
01189     NameVals.clear();
01190   }
01191   
01192   Stream.ExitBlock();
01193 }
01194 
01195 // Emit blockinfo, which defines the standard abbreviations etc.
01196 static void WriteBlockInfo(const ValueEnumerator &VE, BitstreamWriter &Stream) {
01197   // We only want to emit block info records for blocks that have multiple
01198   // instances: CONSTANTS_BLOCK, FUNCTION_BLOCK and VALUE_SYMTAB_BLOCK.  Other
01199   // blocks can defined their abbrevs inline.
01200   Stream.EnterBlockInfoBlock(2);
01201   
01202   { // 8-bit fixed-width VST_ENTRY/VST_BBENTRY strings.
01203     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
01204     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 3));
01205     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
01206     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
01207     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
01208     if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID, 
01209                                    Abbv) != VST_ENTRY_8_ABBREV)
01210       llvm_unreachable("Unexpected abbrev ordering!");
01211   }
01212   
01213   { // 7-bit fixed width VST_ENTRY strings.
01214     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
01215     Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_ENTRY));
01216     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
01217     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
01218     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7));
01219     if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID,
01220                                    Abbv) != VST_ENTRY_7_ABBREV)
01221       llvm_unreachable("Unexpected abbrev ordering!");
01222   }
01223   { // 6-bit char6 VST_ENTRY strings.
01224     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
01225     Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_ENTRY));
01226     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
01227     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
01228     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
01229     if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID,
01230                                    Abbv) != VST_ENTRY_6_ABBREV)
01231       llvm_unreachable("Unexpected abbrev ordering!");
01232   }
01233   { // 6-bit char6 VST_BBENTRY strings.
01234     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
01235     Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_BBENTRY));
01236     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
01237     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
01238     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
01239     if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID,
01240                                    Abbv) != VST_BBENTRY_6_ABBREV)
01241       llvm_unreachable("Unexpected abbrev ordering!");
01242   }
01243   
01244   
01245   
01246   { // SETTYPE abbrev for CONSTANTS_BLOCK.
01247     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
01248     Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_SETTYPE));
01249     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
01250                               Log2_32_Ceil(VE.getTypes().size()+1)));
01251     if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID,
01252                                    Abbv) != CONSTANTS_SETTYPE_ABBREV)
01253       llvm_unreachable("Unexpected abbrev ordering!");
01254   }
01255   
01256   { // INTEGER abbrev for CONSTANTS_BLOCK.
01257     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
01258     Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_INTEGER));
01259     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
01260     if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID,
01261                                    Abbv) != CONSTANTS_INTEGER_ABBREV)
01262       llvm_unreachable("Unexpected abbrev ordering!");
01263   }
01264   
01265   { // CE_CAST abbrev for CONSTANTS_BLOCK.
01266     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
01267     Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_CE_CAST));
01268     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4));  // cast opc
01269     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,       // typeid
01270                               Log2_32_Ceil(VE.getTypes().size()+1)));
01271     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));    // value id
01272 
01273     if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID,
01274                                    Abbv) != CONSTANTS_CE_CAST_Abbrev)
01275       llvm_unreachable("Unexpected abbrev ordering!");
01276   }
01277   { // NULL abbrev for CONSTANTS_BLOCK.
01278     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
01279     Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_NULL));
01280     if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID,
01281                                    Abbv) != CONSTANTS_NULL_Abbrev)
01282       llvm_unreachable("Unexpected abbrev ordering!");
01283   }
01284   
01285   // FIXME: This should only use space for first class types!
01286  
01287   { // INST_LOAD abbrev for FUNCTION_BLOCK.
01288     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
01289     Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_LOAD));
01290     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Ptr
01291     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // Align
01292     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // volatile
01293     if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
01294                                    Abbv) != FUNCTION_INST_LOAD_ABBREV)
01295       llvm_unreachable("Unexpected abbrev ordering!");
01296   }
01297   { // INST_BINOP abbrev for FUNCTION_BLOCK.
01298     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
01299     Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_BINOP));
01300     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // LHS
01301     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // RHS
01302     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
01303     if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
01304                                    Abbv) != FUNCTION_INST_BINOP_ABBREV)
01305       llvm_unreachable("Unexpected abbrev ordering!");
01306   }
01307   { // INST_BINOP_FLAGS abbrev for FUNCTION_BLOCK.
01308     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
01309     Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_BINOP));
01310     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // LHS
01311     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // RHS
01312     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
01313     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7)); // flags
01314     if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
01315                                    Abbv) != FUNCTION_INST_BINOP_FLAGS_ABBREV)
01316       llvm_unreachable("Unexpected abbrev ordering!");
01317   }
01318   { // INST_CAST abbrev for FUNCTION_BLOCK.
01319     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
01320     Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_CAST));
01321     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));    // OpVal
01322     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,       // dest ty
01323                               Log2_32_Ceil(VE.getTypes().size()+1)));
01324     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4));  // opc
01325     if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
01326                                    Abbv) != FUNCTION_INST_CAST_ABBREV)
01327       llvm_unreachable("Unexpected abbrev ordering!");
01328   }
01329   
01330   { // INST_RET abbrev for FUNCTION_BLOCK.
01331     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
01332     Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_RET));
01333     if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
01334                                    Abbv) != FUNCTION_INST_RET_VOID_ABBREV)
01335       llvm_unreachable("Unexpected abbrev ordering!");
01336   }
01337   { // INST_RET abbrev for FUNCTION_BLOCK.
01338     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
01339     Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_RET));
01340     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // ValID
01341     if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
01342                                    Abbv) != FUNCTION_INST_RET_VAL_ABBREV)
01343       llvm_unreachable("Unexpected abbrev ordering!");
01344   }
01345   { // INST_UNREACHABLE abbrev for FUNCTION_BLOCK.
01346     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
01347     Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_UNREACHABLE));
01348     if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
01349                                    Abbv) != FUNCTION_INST_UNREACHABLE_ABBREV)
01350       llvm_unreachable("Unexpected abbrev ordering!");
01351   }
01352   
01353   Stream.ExitBlock();
01354 }
01355 
01356 
01357 /// WriteModule - Emit the specified module to the bitstream.
01358 static void WriteModule(const Module *M, BitstreamWriter &Stream) {
01359   Stream.EnterSubblock(bitc::MODULE_BLOCK_ID, 3);
01360   
01361   // Emit the version number if it is non-zero.
01362   if (CurVersion) {
01363     SmallVector<unsigned, 1> Vals;
01364     Vals.push_back(CurVersion);
01365     Stream.EmitRecord(bitc::MODULE_CODE_VERSION, Vals);
01366   }
01367   
01368   // Analyze the module, enumerating globals, functions, etc.
01369   ValueEnumerator VE(M);
01370 
01371   // Emit blockinfo, which defines the standard abbreviations etc.
01372   WriteBlockInfo(VE, Stream);
01373   
01374   // Emit information about parameter attributes.
01375   WriteAttributeTable(VE, Stream);
01376   
01377   // Emit information describing all of the types in the module.
01378   WriteTypeTable(VE, Stream);
01379   
01380   // Emit top-level description of module, including target triple, inline asm,
01381   // descriptors for global variables, and function prototype info.
01382   WriteModuleInfo(M, VE, Stream);
01383 
01384   // Emit constants.
01385   WriteModuleConstants(VE, Stream);
01386 
01387   // Emit metadata.
01388   WriteModuleMetadata(VE, Stream);
01389 
01390   // Emit function bodies.
01391   for (Module::const_iterator I = M->begin(), E = M->end(); I != E; ++I)
01392     if (!I->isDeclaration())
01393       WriteFunction(*I, VE, Stream);
01394   
01395   // Emit the type symbol table information.
01396   WriteTypeSymbolTable(M->getTypeSymbolTable(), VE, Stream);
01397   
01398   // Emit names for globals/functions etc.
01399   WriteValueSymbolTable(M->getValueSymbolTable(), VE, Stream);
01400   
01401   Stream.ExitBlock();
01402 }
01403 
01404 /// EmitDarwinBCHeader - If generating a bc file on darwin, we have to emit a
01405 /// header and trailer to make it compatible with the system archiver.  To do
01406 /// this we emit the following header, and then emit a trailer that pads the
01407 /// file out to be a multiple of 16 bytes.
01408 /// 
01409 /// struct bc_header {
01410 ///   uint32_t Magic;         // 0x0B17C0DE
01411 ///   uint32_t Version;       // Version, currently always 0.
01412 ///   uint32_t BitcodeOffset; // Offset to traditional bitcode file.
01413 ///   uint32_t BitcodeSize;   // Size of traditional bitcode file.
01414 ///   uint32_t CPUType;       // CPU specifier.
01415 ///   ... potentially more later ...
01416 /// };
01417 enum {
01418   DarwinBCSizeFieldOffset = 3*4, // Offset to bitcode_size.
01419   DarwinBCHeaderSize = 5*4
01420 };
01421 
01422 static void EmitDarwinBCHeader(BitstreamWriter &Stream,
01423                                const std::string &TT) {
01424   unsigned CPUType = ~0U;
01425   
01426   // Match x86_64-*, i[3-9]86-*, powerpc-*, powerpc64-*.  The CPUType is a
01427   // magic number from /usr/include/mach/machine.h.  It is ok to reproduce the
01428   // specific constants here because they are implicitly part of the Darwin ABI.
01429   enum {
01430     DARWIN_CPU_ARCH_ABI64      = 0x01000000,
01431     DARWIN_CPU_TYPE_X86        = 7,
01432     DARWIN_CPU_TYPE_POWERPC    = 18
01433   };
01434   
01435   if (TT.find("x86_64-") == 0)
01436     CPUType = DARWIN_CPU_TYPE_X86 | DARWIN_CPU_ARCH_ABI64;
01437   else if (TT.size() >= 5 && TT[0] == 'i' && TT[2] == '8' && TT[3] == '6' &&
01438            TT[4] == '-' && TT[1] - '3' < 6)
01439     CPUType = DARWIN_CPU_TYPE_X86;
01440   else if (TT.find("powerpc-") == 0)
01441     CPUType = DARWIN_CPU_TYPE_POWERPC;
01442   else if (TT.find("powerpc64-") == 0)
01443     CPUType = DARWIN_CPU_TYPE_POWERPC | DARWIN_CPU_ARCH_ABI64;
01444   
01445   // Traditional Bitcode starts after header.
01446   unsigned BCOffset = DarwinBCHeaderSize;
01447   
01448   Stream.Emit(0x0B17C0DE, 32);
01449   Stream.Emit(0         , 32);  // Version.
01450   Stream.Emit(BCOffset  , 32);
01451   Stream.Emit(0         , 32);  // Filled in later.
01452   Stream.Emit(CPUType   , 32);
01453 }
01454 
01455 /// EmitDarwinBCTrailer - Emit the darwin epilog after the bitcode file and
01456 /// finalize the header.
01457 static void EmitDarwinBCTrailer(BitstreamWriter &Stream, unsigned BufferSize) {
01458   // Update the size field in the header.
01459   Stream.BackpatchWord(DarwinBCSizeFieldOffset, BufferSize-DarwinBCHeaderSize);
01460   
01461   // If the file is not a multiple of 16 bytes, insert dummy padding.
01462   while (BufferSize & 15) {
01463     Stream.Emit(0, 8);
01464     ++BufferSize;
01465   }
01466 }
01467 
01468 
01469 /// WriteBitcodeToFile - Write the specified module to the specified output
01470 /// stream.
01471 void llvm::WriteBitcodeToFile(const Module *M, std::ostream &Out) {
01472   raw_os_ostream RawOut(Out);
01473   // If writing to stdout, set binary mode.
01474   if (llvm::cout == Out)
01475     sys::Program::ChangeStdoutToBinary();
01476   WriteBitcodeToFile(M, RawOut);
01477 }
01478 
01479 /// WriteBitcodeToFile - Write the specified module to the specified output
01480 /// stream.
01481 void llvm::WriteBitcodeToFile(const Module *M, raw_ostream &Out) {
01482   std::vector<unsigned char> Buffer;
01483   BitstreamWriter Stream(Buffer);
01484   
01485   Buffer.reserve(256*1024);
01486 
01487   WriteBitcodeToStream( M, Stream );
01488   
01489   // If writing to stdout, set binary mode.
01490   if (&llvm::outs() == &Out)
01491     sys::Program::ChangeStdoutToBinary();
01492 
01493   // Write the generated bitstream to "Out".
01494   Out.write((char*)&Buffer.front(), Buffer.size());
01495   
01496   // Make sure it hits disk now.
01497   Out.flush();
01498 }
01499 
01500 /// WriteBitcodeToStream - Write the specified module to the specified output
01501 /// stream.
01502 void llvm::WriteBitcodeToStream(const Module *M, BitstreamWriter &Stream) {
01503   // If this is darwin, emit a file header and trailer if needed.
01504   bool isDarwin = M->getTargetTriple().find("-darwin") != std::string::npos;
01505   if (isDarwin)
01506     EmitDarwinBCHeader(Stream, M->getTargetTriple());
01507   
01508   // Emit the file header.
01509   Stream.Emit((unsigned)'B', 8);
01510   Stream.Emit((unsigned)'C', 8);
01511   Stream.Emit(0x0, 4);
01512   Stream.Emit(0xC, 4);
01513   Stream.Emit(0xE, 4);
01514   Stream.Emit(0xD, 4);
01515 
01516   // Emit the module.
01517   WriteModule(M, Stream);
01518 
01519   if (isDarwin)
01520     EmitDarwinBCTrailer(Stream, Stream.getBuffer().size());
01521 }