For PR411:
[oota-llvm.git] / lib / Bytecode / Writer / Writer.cpp
index 9bc5ce600a7adfcf12586804a10dc2f0787a371f..a2e8fe566d35633bfe55c7751ccb04126c0841bf 100644 (file)
@@ -1,10 +1,10 @@
 //===-- Writer.cpp - Library for writing LLVM bytecode files --------------===//
-// 
+//
 //                     The LLVM Compiler Infrastructure
 //
 // This file was developed by the LLVM research group and is distributed under
 // the University of Illinois Open Source License. See LICENSE.TXT for details.
-// 
+//
 //===----------------------------------------------------------------------===//
 //
 // This library implements the functionality defined in llvm/Bytecode/Writer.h
 //
 //===----------------------------------------------------------------------===//
 
+#define DEBUG_TYPE "bytecodewriter"
 #include "WriterInternals.h"
 #include "llvm/Bytecode/WriteBytecodePass.h"
+#include "llvm/CallingConv.h"
 #include "llvm/Constants.h"
 #include "llvm/DerivedTypes.h"
+#include "llvm/InlineAsm.h"
 #include "llvm/Instructions.h"
 #include "llvm/Module.h"
-#include "llvm/SymbolTable.h"
+#include "llvm/TypeSymbolTable.h"
+#include "llvm/ValueSymbolTable.h"
 #include "llvm/Support/GetElementPtrTypeIterator.h"
-#include "Support/STLExtras.h"
-#include "Support/Statistic.h"
+#include "llvm/Support/Compressor.h"
+#include "llvm/Support/MathExtras.h"
+#include "llvm/Support/Streams.h"
+#include "llvm/System/Program.h"
+#include "llvm/ADT/STLExtras.h"
+#include "llvm/ADT/Statistic.h"
 #include <cstring>
 #include <algorithm>
 using namespace llvm;
 
+/// This value needs to be incremented every time the bytecode format changes
+/// so that the reader can distinguish which format of the bytecode file has
+/// been written.
+/// @brief The bytecode version number
+const unsigned BCVersionNum = 7;
+
 static RegisterPass<WriteBytecodePass> X("emitbytecode", "Bytecode Writer");
 
-static Statistic<> 
-BytesWritten("bytecodewriter", "Number of bytecode bytes written");
+STATISTIC(BytesWritten, "Number of bytecode bytes written");
 
 //===----------------------------------------------------------------------===//
 //===                           Output Primitives                          ===//
 //===----------------------------------------------------------------------===//
 
 // output - If a position is specified, it must be in the valid portion of the
-// string... note that this should be inlined always so only the relevant IF 
+// string... note that this should be inlined always so only the relevant IF
 // body should be included.
 inline void BytecodeWriter::output(unsigned i, int pos) {
   if (pos == -1) { // Be endian clean, little endian is our friend
-    Out.push_back((unsigned char)i); 
+    Out.push_back((unsigned char)i);
     Out.push_back((unsigned char)(i >> 8));
     Out.push_back((unsigned char)(i >> 16));
     Out.push_back((unsigned char)(i >> 24));
@@ -64,16 +77,15 @@ inline void BytecodeWriter::output(int i) {
 /// output_vbr - Output an unsigned value, by using the least number of bytes
 /// possible.  This is useful because many of our "infinite" values are really
 /// very small most of the time; but can be large a few times.
-/// Data format used:  If you read a byte with the high bit set, use the low 
-/// seven bits as data and then read another byte. Note that using this may 
-/// cause the output buffer to become unaligned.
+/// Data format used:  If you read a byte with the high bit set, use the low
+/// seven bits as data and then read another byte.
 inline void BytecodeWriter::output_vbr(uint64_t i) {
   while (1) {
     if (i < 0x80) { // done?
       Out.push_back((unsigned char)i);   // We know the high bit is clear...
       return;
     }
-    
+
     // Nope, we are bigger than a character, output the next 7 bits and set the
     // high bit to say that there is more coming...
     Out.push_back(0x80 | ((unsigned char)i & 0x7F));
@@ -87,7 +99,7 @@ inline void BytecodeWriter::output_vbr(unsigned i) {
       Out.push_back((unsigned char)i);   // We know the high bit is clear...
       return;
     }
-    
+
     // Nope, we are bigger than a character, output the next 7 bits and set the
     // high bit to say that there is more coming...
     Out.push_back(0x80 | ((unsigned char)i & 0x7F));
@@ -105,7 +117,7 @@ inline void BytecodeWriter::output_typeid(unsigned i) {
 }
 
 inline void BytecodeWriter::output_vbr(int64_t i) {
-  if (i < 0) 
+  if (i < 0)
     output_vbr(((uint64_t)(-i) << 1) | 1); // Set low order sign bit...
   else
     output_vbr((uint64_t)i << 1);          // Low order bit is clear.
@@ -113,27 +125,16 @@ inline void BytecodeWriter::output_vbr(int64_t i) {
 
 
 inline void BytecodeWriter::output_vbr(int i) {
-  if (i < 0) 
+  if (i < 0)
     output_vbr(((unsigned)(-i) << 1) | 1); // Set low order sign bit...
   else
     output_vbr((unsigned)i << 1);          // Low order bit is clear.
 }
 
-// align32 - emit the minimal number of bytes that will bring us to 32 bit 
-// alignment...
-//
-inline void BytecodeWriter::align32() {
-  int NumPads = (4-(Out.size() & 3)) & 3; // Bytes to get padding to 32 bits
-  while (NumPads--) Out.push_back((unsigned char)0xAB);
-}
-
-inline void BytecodeWriter::output(const std::string &s, bool Aligned ) {
+inline void BytecodeWriter::output(const std::string &s) {
   unsigned Len = s.length();
-  output_vbr(Len );             // Strings may have an arbitrary length...
+  output_vbr(Len);             // Strings may have an arbitrary length.
   Out.insert(Out.end(), s.begin(), s.end());
-
-  if (Aligned)
-    align32();                   // Make sure we are now aligned...
 }
 
 inline void BytecodeWriter::output_data(const void *Ptr, const void *End) {
@@ -143,37 +144,29 @@ inline void BytecodeWriter::output_data(const void *Ptr, const void *End) {
 inline void BytecodeWriter::output_float(float& FloatVal) {
   /// FIXME: This isn't optimal, it has size problems on some platforms
   /// where FP is not IEEE.
-  union {
-    float f;
-    uint32_t i;
-  } FloatUnion;
-  FloatUnion.f = FloatVal;
-  Out.push_back( static_cast<unsigned char>( (FloatUnion.i & 0xFF )));
-  Out.push_back( static_cast<unsigned char>( (FloatUnion.i >> 8) & 0xFF));
-  Out.push_back( static_cast<unsigned char>( (FloatUnion.i >> 16) & 0xFF));
-  Out.push_back( static_cast<unsigned char>( (FloatUnion.i >> 24) & 0xFF));
+  uint32_t i = FloatToBits(FloatVal);
+  Out.push_back( static_cast<unsigned char>( (i      ) & 0xFF));
+  Out.push_back( static_cast<unsigned char>( (i >> 8 ) & 0xFF));
+  Out.push_back( static_cast<unsigned char>( (i >> 16) & 0xFF));
+  Out.push_back( static_cast<unsigned char>( (i >> 24) & 0xFF));
 }
 
 inline void BytecodeWriter::output_double(double& DoubleVal) {
   /// FIXME: This isn't optimal, it has size problems on some platforms
   /// where FP is not IEEE.
-  union {
-    double d;
-    uint64_t i;
-  } DoubleUnion;
-  DoubleUnion.d = DoubleVal;
-  Out.push_back( static_cast<unsigned char>( (DoubleUnion.i & 0xFF )));
-  Out.push_back( static_cast<unsigned char>( (DoubleUnion.i >> 8) & 0xFF));
-  Out.push_back( static_cast<unsigned char>( (DoubleUnion.i >> 16) & 0xFF));
-  Out.push_back( static_cast<unsigned char>( (DoubleUnion.i >> 24) & 0xFF));
-  Out.push_back( static_cast<unsigned char>( (DoubleUnion.i >> 32) & 0xFF));
-  Out.push_back( static_cast<unsigned char>( (DoubleUnion.i >> 40) & 0xFF));
-  Out.push_back( static_cast<unsigned char>( (DoubleUnion.i >> 48) & 0xFF));
-  Out.push_back( static_cast<unsigned char>( (DoubleUnion.i >> 56) & 0xFF));
+  uint64_t i = DoubleToBits(DoubleVal);
+  Out.push_back( static_cast<unsigned char>( (i      ) & 0xFF));
+  Out.push_back( static_cast<unsigned char>( (i >> 8 ) & 0xFF));
+  Out.push_back( static_cast<unsigned char>( (i >> 16) & 0xFF));
+  Out.push_back( static_cast<unsigned char>( (i >> 24) & 0xFF));
+  Out.push_back( static_cast<unsigned char>( (i >> 32) & 0xFF));
+  Out.push_back( static_cast<unsigned char>( (i >> 40) & 0xFF));
+  Out.push_back( static_cast<unsigned char>( (i >> 48) & 0xFF));
+  Out.push_back( static_cast<unsigned char>( (i >> 56) & 0xFF));
 }
 
-inline BytecodeBlock::BytecodeBlock(unsigned ID, BytecodeWriterw,
-                    bool elideIfEmpty, bool hasLongFormat )
+inline BytecodeBlock::BytecodeBlock(unsigned ID, BytecodeWriter &w,
+                                    bool elideIfEmpty, bool hasLongFormat)
   : Id(ID), Writer(w), ElideIfEmpty(elideIfEmpty), HasLongFormat(hasLongFormat){
 
   if (HasLongFormat) {
@@ -185,8 +178,8 @@ inline BytecodeBlock::BytecodeBlock(unsigned ID, BytecodeWriter& w,
   Loc = w.size();
 }
 
-inline BytecodeBlock::~BytecodeBlock() {           // Do backpatch when block goes out
-                                   // of scope...
+inline BytecodeBlock::~BytecodeBlock() { // Do backpatch when block goes out
+                                         // of scope...
   if (Loc == Writer.size() && ElideIfEmpty) {
     // If the block is empty, and we are allowed to, do not emit the block at
     // all!
@@ -194,13 +187,10 @@ inline BytecodeBlock::~BytecodeBlock() {           // Do backpatch when block go
     return;
   }
 
-  //cerr << "OldLoc = " << Loc << " NewLoc = " << NewLoc << " diff = "
-  //     << (NewLoc-Loc) << endl;
   if (HasLongFormat)
     Writer.output(unsigned(Writer.size()-Loc), int(Loc-4));
   else
     Writer.output(unsigned(Writer.size()-Loc) << 5 | (Id & 0x1F), int(Loc-4));
-  Writer.align32();  // Blocks must ALWAYS be aligned
 }
 
 //===----------------------------------------------------------------------===//
@@ -208,29 +198,39 @@ inline BytecodeBlock::~BytecodeBlock() {           // Do backpatch when block go
 //===----------------------------------------------------------------------===//
 
 void BytecodeWriter::outputType(const Type *T) {
-  output_vbr((unsigned)T->getTypeID());
-  
+  const StructType* STy = dyn_cast<StructType>(T);
+  if(STy && STy->isPacked())
+    output_vbr((unsigned)Type::PackedStructTyID);
+  else
+    output_vbr((unsigned)T->getTypeID());
+
   // That's all there is to handling primitive types...
-  if (T->isPrimitiveType()) {
+  if (T->isPrimitiveType())
     return;     // We might do this if we alias a prim type: %x = type int
-  }
 
   switch (T->getTypeID()) {   // Handle derived types now.
+  case Type::IntegerTyID:
+    output_vbr(cast<IntegerType>(T)->getBitWidth());
+    break;
   case Type::FunctionTyID: {
     const FunctionType *MT = cast<FunctionType>(T);
     int Slot = Table.getSlot(MT->getReturnType());
     assert(Slot != -1 && "Type used but not available!!");
     output_typeid((unsigned)Slot);
+    output_vbr(unsigned(MT->getParamAttrs(0)));
 
     // Output the number of arguments to function (+1 if varargs):
     output_vbr((unsigned)MT->getNumParams()+MT->isVarArg());
 
     // Output all of the arguments...
     FunctionType::param_iterator I = MT->param_begin();
+    unsigned Idx = 1;
     for (; I != MT->param_end(); ++I) {
       Slot = Table.getSlot(*I);
       assert(Slot != -1 && "Type used but not available!!");
       output_typeid((unsigned)Slot);
+      output_vbr(unsigned(MT->getParamAttrs(Idx)));
+      Idx++;
     }
 
     // Terminate list with VoidTy if we are a varargs function...
@@ -244,15 +244,21 @@ void BytecodeWriter::outputType(const Type *T) {
     int Slot = Table.getSlot(AT->getElementType());
     assert(Slot != -1 && "Type used but not available!!");
     output_typeid((unsigned)Slot);
-    //std::cerr << "Type slot = " << Slot << " Type = " << T->getName() << endl;
-
     output_vbr(AT->getNumElements());
     break;
   }
 
+ case Type::PackedTyID: {
+    const PackedType *PT = cast<PackedType>(T);
+    int Slot = Table.getSlot(PT->getElementType());
+    assert(Slot != -1 && "Type used but not available!!");
+    output_typeid((unsigned)Slot);
+    output_vbr(PT->getNumElements());
+    break;
+  }
+
   case Type::StructTyID: {
     const StructType *ST = cast<StructType>(T);
-
     // Output all of the element types...
     for (StructType::element_iterator I = ST->element_begin(),
            E = ST->element_end(); I != E; ++I) {
@@ -274,32 +280,31 @@ void BytecodeWriter::outputType(const Type *T) {
     break;
   }
 
-  case Type::OpaqueTyID: {
+  case Type::OpaqueTyID:
     // No need to emit anything, just the count of opaque types is enough.
     break;
-  }
 
-  //case Type::PackedTyID:
   default:
-    std::cerr << __FILE__ << ":" << __LINE__ << ": Don't know how to serialize"
-              << " Type '" << T->getDescription() << "'\n";
+    cerr << __FILE__ << ":" << __LINE__ << ": Don't know how to serialize"
+         << " Type '" << T->getDescription() << "'\n";
     break;
   }
 }
 
 void BytecodeWriter::outputConstant(const Constant *CPV) {
-  assert((CPV->getType()->isPrimitiveType() || !CPV->isNullValue()) &&
-         "Shouldn't output null constants!");
+  assert(((CPV->getType()->isPrimitiveType() || CPV->getType()->isInteger()) ||
+          !CPV->isNullValue()) && "Shouldn't output null constants!");
 
   // We must check for a ConstantExpr before switching by type because
   // a ConstantExpr can be of any type, and has no explicit value.
-  // 
+  //
   if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CPV)) {
     // FIXME: Encoding of constant exprs could be much more compact!
     assert(CE->getNumOperands() > 0 && "ConstantExpr with 0 operands");
-    output_vbr(CE->getNumOperands());   // flags as an expr
-    output_vbr(CE->getOpcode());        // flags as an expr
-    
+    assert(CE->getNumOperands() != 1 || CE->isCast());
+    output_vbr(1+CE->getNumOperands());   // flags as an expr
+    output_vbr(CE->getOpcode());          // Put out the CE op code
+
     for (User::const_op_iterator OI = CE->op_begin(); OI != CE->op_end(); ++OI){
       int Slot = Table.getSlot(*OI);
       assert(Slot != -1 && "Unknown constant used in ConstantExpr!!");
@@ -307,38 +312,33 @@ void BytecodeWriter::outputConstant(const Constant *CPV) {
       Slot = Table.getSlot((*OI)->getType());
       output_typeid((unsigned)Slot);
     }
+    if (CE->isCompare())
+      output_vbr((unsigned)CE->getPredicate());
+    return;
+  } else if (isa<UndefValue>(CPV)) {
+    output_vbr(1U);       // 1 -> UndefValue constant.
     return;
   } else {
-    output_vbr(0U);       // flag as not a ConstantExpr
+    output_vbr(0U);       // flag as not a ConstantExpr (i.e. 0 operands)
   }
-  
-  switch (CPV->getType()->getTypeID()) {
-  case Type::BoolTyID:    // Boolean Types
-    if (cast<ConstantBool>(CPV)->getValue())
-      output_vbr(1U);
-    else
-      output_vbr(0U);
-    break;
-
-  case Type::UByteTyID:   // Unsigned integer types...
-  case Type::UShortTyID:
-  case Type::UIntTyID:
-  case Type::ULongTyID:
-    output_vbr(cast<ConstantUInt>(CPV)->getValue());
-    break;
 
-  case Type::SByteTyID:   // Signed integer types...
-  case Type::ShortTyID:
-  case Type::IntTyID:
-  case Type::LongTyID:
-    output_vbr(cast<ConstantSInt>(CPV)->getValue());
+  switch (CPV->getType()->getTypeID()) {
+  case Type::IntegerTyID: { // Integer types...
+    unsigned NumBits = cast<IntegerType>(CPV->getType())->getBitWidth();
+    if (NumBits <= 32)
+      output_vbr(uint32_t(cast<ConstantInt>(CPV)->getZExtValue()));
+    else if (NumBits <= 64)
+      output_vbr(uint64_t(cast<ConstantInt>(CPV)->getZExtValue()));
+    else 
+      assert("Integer types > 64 bits not supported.");
     break;
+  }
 
   case Type::ArrayTyID: {
     const ConstantArray *CPA = cast<ConstantArray>(CPV);
     assert(!CPA->isString() && "Constant strings should be handled specially!");
 
-    for (unsigned i = 0; i != CPA->getNumOperands(); ++i) {
+    for (unsigned i = 0, e = CPA->getNumOperands(); i != e; ++i) {
       int Slot = Table.getSlot(CPA->getOperand(i));
       assert(Slot != -1 && "Constant used but not available!!");
       output_vbr((unsigned)Slot);
@@ -346,12 +346,22 @@ void BytecodeWriter::outputConstant(const Constant *CPV) {
     break;
   }
 
+  case Type::PackedTyID: {
+    const ConstantPacked *CP = cast<ConstantPacked>(CPV);
+
+    for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i) {
+      int Slot = Table.getSlot(CP->getOperand(i));
+      assert(Slot != -1 && "Constant used but not available!!");
+      output_vbr((unsigned)Slot);
+    }
+    break;
+  }
+
   case Type::StructTyID: {
     const ConstantStruct *CPS = cast<ConstantStruct>(CPV);
-    const std::vector<Use> &Vals = CPS->getValues();
 
-    for (unsigned i = 0; i < Vals.size(); ++i) {
-      int Slot = Table.getSlot(Vals[i]);
+    for (unsigned i = 0, e = CPS->getNumOperands(); i != e; ++i) {
+      int Slot = Table.getSlot(CPS->getOperand(i));
       assert(Slot != -1 && "Constant used but not available!!");
       output_vbr((unsigned)Slot);
     }
@@ -373,16 +383,29 @@ void BytecodeWriter::outputConstant(const Constant *CPV) {
     break;
   }
 
-  case Type::VoidTyID: 
+  case Type::VoidTyID:
   case Type::LabelTyID:
   default:
-    std::cerr << __FILE__ << ":" << __LINE__ << ": Don't know how to serialize"
-              << " type '" << *CPV->getType() << "'\n";
+    cerr << __FILE__ << ":" << __LINE__ << ": Don't know how to serialize"
+         << " type '" << *CPV->getType() << "'\n";
     break;
   }
   return;
 }
 
+/// outputInlineAsm - InlineAsm's get emitted to the constant pool, so they can
+/// be shared by multiple uses.
+void BytecodeWriter::outputInlineAsm(const InlineAsm *IA) {
+  // Output a marker, so we know when we have one one parsing the constant pool.
+  // Note that this encoding is 5 bytes: not very efficient for a marker.  Since
+  // unique inline asms are rare, this should hardly matter.
+  output_vbr(~0U);
+  
+  output(IA->getAsmString());
+  output(IA->getConstraintString());
+  output_vbr(unsigned(IA->hasSideEffects()));
+}
+
 void BytecodeWriter::outputConstantStrings() {
   SlotCalculator::string_iterator I = Table.string_begin();
   SlotCalculator::string_iterator E = Table.string_end();
@@ -392,14 +415,14 @@ void BytecodeWriter::outputConstantStrings() {
   // the 'void' type plane.
   output_vbr(unsigned(E-I));
   output_typeid(Type::VoidTyID);
-    
+
   // Emit all of the strings.
   for (I = Table.string_begin(); I != E; ++I) {
     const ConstantArray *Str = *I;
     int Slot = Table.getSlot(Str->getType());
     assert(Slot != -1 && "Constant string of unknown type?");
     output_typeid((unsigned)Slot);
-    
+
     // Now that we emitted the type (which indicates the size of the string),
     // emit all of the characters.
     std::string Val = Str->getAsString();
@@ -410,28 +433,28 @@ void BytecodeWriter::outputConstantStrings() {
 //===----------------------------------------------------------------------===//
 //===                           Instruction Output                         ===//
 //===----------------------------------------------------------------------===//
-typedef unsigned char uchar;
 
-// outputInstructionFormat0 - Output those wierd instructions that have a large
-// number of operands or have large operands themselves...
+// outputInstructionFormat0 - Output those weird instructions that have a large
+// number of operands or have large operands themselves.
 //
 // Format: [opcode] [type] [numargs] [arg0] [arg1] ... [arg<numargs-1>]
 //
-void BytecodeWriter::outputInstructionFormat0(const Instruction *I, unsigned Opcode,
-                                    const SlotCalculator &Table,
-                                    unsigned Type) {
+void BytecodeWriter::outputInstructionFormat0(const Instruction *I,
+                                              unsigned Opcode,
+                                              const SlotCalculator &Table,
+                                              unsigned Type) {
   // Opcode must have top two bits clear...
   output_vbr(Opcode << 2);                  // Instruction Opcode ID
   output_typeid(Type);                      // Result type
 
   unsigned NumArgs = I->getNumOperands();
-  output_vbr(NumArgs + (isa<CastInst>(I) || isa<VANextInst>(I) ||
-                        isa<VAArgInst>(I)));
+  output_vbr(NumArgs + (isa<CastInst>(I)  || isa<InvokeInst>(I) || 
+                        isa<CmpInst>(I) || isa<VAArgInst>(I) || Opcode == 58));
 
   if (!isa<GetElementPtrInst>(&I)) {
     for (unsigned i = 0; i < NumArgs; ++i) {
       int Slot = Table.getSlot(I->getOperand(i));
-      assert(Slot >= 0 && "No slot number for value!?!?");      
+      assert(Slot >= 0 && "No slot number for value!?!?");
       output_vbr((unsigned)Slot);
     }
 
@@ -439,15 +462,17 @@ void BytecodeWriter::outputInstructionFormat0(const Instruction *I, unsigned Opc
       int Slot = Table.getSlot(I->getType());
       assert(Slot != -1 && "Cast return type unknown?");
       output_typeid((unsigned)Slot);
-    } else if (const VANextInst *VAI = dyn_cast<VANextInst>(I)) {
-      int Slot = Table.getSlot(VAI->getArgType());
-      assert(Slot != -1 && "VarArg argument type unknown?");
-      output_typeid((unsigned)Slot);
+    } else if (isa<CmpInst>(I)) {
+      output_vbr(unsigned(cast<CmpInst>(I)->getPredicate()));
+    } else if (isa<InvokeInst>(I)) {  
+      output_vbr(cast<InvokeInst>(I)->getCallingConv());
+    } else if (Opcode == 58) {  // Call escape sequence
+      output_vbr((cast<CallInst>(I)->getCallingConv() << 1) |
+                 unsigned(cast<CallInst>(I)->isTailCall()));
     }
-
   } else {
     int Slot = Table.getSlot(I->getOperand(0));
-    assert(Slot >= 0 && "No slot number for value!?!?");      
+    assert(Slot >= 0 && "No slot number for value!?!?");
     output_vbr(unsigned(Slot));
 
     // We need to encode the type of sequential type indices into their slot #
@@ -455,24 +480,22 @@ void BytecodeWriter::outputInstructionFormat0(const Instruction *I, unsigned Opc
     for (gep_type_iterator TI = gep_type_begin(I), E = gep_type_end(I);
          Idx != NumArgs; ++TI, ++Idx) {
       Slot = Table.getSlot(I->getOperand(Idx));
-      assert(Slot >= 0 && "No slot number for value!?!?");      
-    
+      assert(Slot >= 0 && "No slot number for value!?!?");
+
       if (isa<SequentialType>(*TI)) {
-        unsigned IdxId;
-        switch (I->getOperand(Idx)->getType()->getTypeID()) {
-        default: assert(0 && "Unknown index type!");
-        case Type::UIntTyID:  IdxId = 0; break;
-        case Type::IntTyID:   IdxId = 1; break;
-        case Type::ULongTyID: IdxId = 2; break;
-        case Type::LongTyID:  IdxId = 3; break;
-        }
-        Slot = (Slot << 2) | IdxId;
+        // These should be either 32-bits or 64-bits, however, with bit
+        // accurate types we just distinguish between less than or equal to
+        // 32-bits or greater than 32-bits.
+        unsigned BitWidth = 
+          cast<IntegerType>(I->getOperand(Idx)->getType())->getBitWidth();
+        assert(BitWidth == 32 || BitWidth == 64 && 
+               "Invalid bitwidth for GEP index");
+        unsigned IdxId = BitWidth == 32 ? 0 : 1;
+        Slot = (Slot << 1) | IdxId;
       }
       output_vbr(unsigned(Slot));
     }
   }
-
-  align32();    // We must maintain correct alignment!
 }
 
 
@@ -485,10 +508,10 @@ void BytecodeWriter::outputInstructionFormat0(const Instruction *I, unsigned Opc
 //
 // Format: [opcode] [type] [numargs] [arg0] [arg1] ... [arg<numargs-1>]
 //
-void BytecodeWriter::outputInstrVarArgsCall(const Instruction *I, 
-                                           unsigned Opcode,
-                                           const SlotCalculator &Table,
-                                           unsigned Type) {
+void BytecodeWriter::outputInstrVarArgsCall(const Instruction *I,
+                                            unsigned Opcode,
+                                            const SlotCalculator &Table,
+                                            unsigned Type) {
   assert(isa<CallInst>(I) || isa<InvokeInst>(I));
   // Opcode must have top two bits clear...
   output_vbr(Opcode << 2);                  // Instruction Opcode ID
@@ -509,38 +532,46 @@ void BytecodeWriter::outputInstrVarArgsCall(const Instruction *I,
     // variable argument.
     NumFixedOperands = 3+NumParams;
   }
-  output_vbr(2 * I->getNumOperands()-NumFixedOperands);
+  output_vbr(2 * I->getNumOperands()-NumFixedOperands + 
+      unsigned(Opcode == 58 || isa<InvokeInst>(I)));
 
   // The type for the function has already been emitted in the type field of the
   // instruction.  Just emit the slot # now.
   for (unsigned i = 0; i != NumFixedOperands; ++i) {
     int Slot = Table.getSlot(I->getOperand(i));
-    assert(Slot >= 0 && "No slot number for value!?!?");      
+    assert(Slot >= 0 && "No slot number for value!?!?");
     output_vbr((unsigned)Slot);
   }
 
   for (unsigned i = NumFixedOperands, e = I->getNumOperands(); i != e; ++i) {
     // Output Arg Type ID
     int Slot = Table.getSlot(I->getOperand(i)->getType());
-    assert(Slot >= 0 && "No slot number for value!?!?");      
+    assert(Slot >= 0 && "No slot number for value!?!?");
     output_typeid((unsigned)Slot);
-    
+
     // Output arg ID itself
     Slot = Table.getSlot(I->getOperand(i));
-    assert(Slot >= 0 && "No slot number for value!?!?");      
+    assert(Slot >= 0 && "No slot number for value!?!?");
     output_vbr((unsigned)Slot);
   }
-  align32();    // We must maintain correct alignment!
+  
+  if (isa<InvokeInst>(I)) {
+    // Emit the tail call/calling conv for invoke instructions
+    output_vbr(cast<InvokeInst>(I)->getCallingConv());
+  } else if (Opcode == 58) {
+    const CallInst *CI = cast<CallInst>(I);
+    output_vbr((CI->getCallingConv() << 1) | unsigned(CI->isTailCall()));
+  }
 }
 
 
 // outputInstructionFormat1 - Output one operand instructions, knowing that no
 // operand index is >= 2^12.
 //
-inline void BytecodeWriter::outputInstructionFormat1(const Instruction *I, 
-                                                    unsigned Opcode,
-                                                    unsigned *Slots, 
-                                                    unsigned Type) {
+inline void BytecodeWriter::outputInstructionFormat1(const Instruction *I,
+                                                     unsigned Opcode,
+                                                     unsigned *Slots,
+                                                     unsigned Type) {
   // bits   Instruction format:
   // --------------------------
   // 01-00: Opcode type, fixed to 1.
@@ -548,42 +579,36 @@ inline void BytecodeWriter::outputInstructionFormat1(const Instruction *I,
   // 19-08: Resulting type plane
   // 31-20: Operand #1 (if set to (2^12-1), then zero operands)
   //
-  unsigned Bits = 1 | (Opcode << 2) | (Type << 8) | (Slots[0] << 20);
-  //  cerr << "1 " << IType << " " << Type << " " << Slots[0] << endl;
-  output(Bits);
+  output(1 | (Opcode << 2) | (Type << 8) | (Slots[0] << 20));
 }
 
 
 // outputInstructionFormat2 - Output two operand instructions, knowing that no
 // operand index is >= 2^8.
 //
-inline void BytecodeWriter::outputInstructionFormat2(const Instruction *I, 
-                                                    unsigned Opcode,
-                                                    unsigned *Slots, 
-                                                    unsigned Type) {
+inline void BytecodeWriter::outputInstructionFormat2(const Instruction *I,
+                                                     unsigned Opcode,
+                                                     unsigned *Slots,
+                                                     unsigned Type) {
   // bits   Instruction format:
   // --------------------------
   // 01-00: Opcode type, fixed to 2.
   // 07-02: Opcode
   // 15-08: Resulting type plane
   // 23-16: Operand #1
-  // 31-24: Operand #2  
+  // 31-24: Operand #2
   //
-  unsigned Bits = 2 | (Opcode << 2) | (Type << 8) |
-                    (Slots[0] << 16) | (Slots[1] << 24);
-  //  cerr << "2 " << IType << " " << Type << " " << Slots[0] << " " 
-  //       << Slots[1] << endl;
-  output(Bits);
+  output(2 | (Opcode << 2) | (Type << 8) | (Slots[0] << 16) | (Slots[1] << 24));
 }
 
 
 // outputInstructionFormat3 - Output three operand instructions, knowing that no
 // operand index is >= 2^6.
 //
-inline void BytecodeWriter::outputInstructionFormat3(const Instruction *I, 
+inline void BytecodeWriter::outputInstructionFormat3(const Instruction *I,
                                                      unsigned Opcode,
-                                                    unsigned *Slots, 
-                                                    unsigned Type) {
+                                                     unsigned *Slots,
+                                                     unsigned Type) {
   // bits   Instruction format:
   // --------------------------
   // 01-00: Opcode type, fixed to 3.
@@ -593,29 +618,42 @@ inline void BytecodeWriter::outputInstructionFormat3(const Instruction *I,
   // 25-20: Operand #2
   // 31-26: Operand #3
   //
-  unsigned Bits = 3 | (Opcode << 2) | (Type << 8) |
-          (Slots[0] << 14) | (Slots[1] << 20) | (Slots[2] << 26);
-  //cerr << "3 " << IType << " " << Type << " " << Slots[0] << " " 
-  //     << Slots[1] << " " << Slots[2] << endl;
-  output(Bits);
+  output(3 | (Opcode << 2) | (Type << 8) |
+          (Slots[0] << 14) | (Slots[1] << 20) | (Slots[2] << 26));
 }
 
 void BytecodeWriter::outputInstruction(const Instruction &I) {
-  assert(I.getOpcode() < 62 && "Opcode too big???");
+  assert(I.getOpcode() < 57 && "Opcode too big???");
   unsigned Opcode = I.getOpcode();
   unsigned NumOperands = I.getNumOperands();
 
-  // Encode 'volatile load' as 62 and 'volatile store' as 63.
-  if (isa<LoadInst>(I) && cast<LoadInst>(I).isVolatile())
+  // Encode 'tail call' as 61, 'volatile load' as 62, and 'volatile store' as
+  // 63.
+  if (const CallInst *CI = dyn_cast<CallInst>(&I)) {
+    if (CI->getCallingConv() == CallingConv::C) {
+      if (CI->isTailCall())
+        Opcode = 61;   // CCC + Tail Call
+      else
+        ;     // Opcode = Instruction::Call
+    } else if (CI->getCallingConv() == CallingConv::Fast) {
+      if (CI->isTailCall())
+        Opcode = 59;    // FastCC + TailCall
+      else
+        Opcode = 60;    // FastCC + Not Tail Call
+    } else {
+      Opcode = 58;      // Call escape sequence.
+    }
+  } else if (isa<LoadInst>(I) && cast<LoadInst>(I).isVolatile()) {
     Opcode = 62;
-  if (isa<StoreInst>(I) && cast<StoreInst>(I).isVolatile())
+  } else if (isa<StoreInst>(I) && cast<StoreInst>(I).isVolatile()) {
     Opcode = 63;
+  }
 
   // Figure out which type to encode with the instruction.  Typically we want
   // the type of the first parameter, as opposed to the type of the instruction
   // (for example, with setcc, we always know it returns bool, but the type of
   // the first param is actually interesting).  But if we have no arguments
-  // we take the type of the instruction itself.  
+  // we take the type of the instruction itself.
   //
   const Type *Ty;
   switch (I.getOpcode()) {
@@ -660,7 +698,7 @@ void BytecodeWriter::outputInstruction(const Instruction &I) {
     //
     unsigned MaxOpSlot = Type;
     unsigned Slots[3]; Slots[0] = (1 << 12)-1;   // Marker to signify 0 operands
-    
+
     for (unsigned i = 0; i != NumOperands; ++i) {
       int slot = Table.getSlot(I.getOperand(i));
       assert(slot != -1 && "Broken bytecode!");
@@ -676,28 +714,52 @@ void BytecodeWriter::outputInstruction(const Instruction &I) {
       assert(Slots[1] != ~0U && "Cast return type unknown?");
       if (Slots[1] > MaxOpSlot) MaxOpSlot = Slots[1];
       NumOperands++;
-    } else if (const VANextInst *VANI = dyn_cast<VANextInst>(&I)) {
-      Slots[1] = Table.getSlot(VANI->getArgType());
-      assert(Slots[1] != ~0U && "va_next return type unknown?");
-      if (Slots[1] > MaxOpSlot) MaxOpSlot = Slots[1];
+    } else if (const AllocationInst *AI = dyn_cast<AllocationInst>(&I)) {
+      assert(NumOperands == 1 && "Bogus allocation!");
+      if (AI->getAlignment()) {
+        Slots[1] = Log2_32(AI->getAlignment())+1;
+        if (Slots[1] > MaxOpSlot) MaxOpSlot = Slots[1];
+        NumOperands = 2;
+      }
+    } else if (isa<ICmpInst>(I) || isa<FCmpInst>(I)) {
+      // We need to encode the compare instruction's predicate as the third
+      // operand. Its not really a slot, but we don't want to break the 
+      // instruction format for these instructions.
       NumOperands++;
+      assert(NumOperands == 3 && "CmpInst with wrong number of operands?");
+      Slots[2] = unsigned(cast<CmpInst>(&I)->getPredicate());
+      if (Slots[2] > MaxOpSlot)
+        MaxOpSlot = Slots[2];
     } else if (const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(&I)) {
       // We need to encode the type of sequential type indices into their slot #
       unsigned Idx = 1;
       for (gep_type_iterator I = gep_type_begin(GEP), E = gep_type_end(GEP);
            I != E; ++I, ++Idx)
         if (isa<SequentialType>(*I)) {
-          unsigned IdxId;
-          switch (GEP->getOperand(Idx)->getType()->getTypeID()) {
-          default: assert(0 && "Unknown index type!");
-          case Type::UIntTyID:  IdxId = 0; break;
-          case Type::IntTyID:   IdxId = 1; break;
-          case Type::ULongTyID: IdxId = 2; break;
-          case Type::LongTyID:  IdxId = 3; break;
-          }
-          Slots[Idx] = (Slots[Idx] << 2) | IdxId;
+          // These should be either 32-bits or 64-bits, however, with bit
+          // accurate types we just distinguish between less than or equal to
+          // 32-bits or greater than 32-bits.
+          unsigned BitWidth = 
+            cast<IntegerType>(GEP->getOperand(Idx)->getType())->getBitWidth();
+          assert(BitWidth == 32 || BitWidth == 64 && 
+                 "Invalid bitwidth for GEP index");
+          unsigned IdxId = BitWidth == 32 ? 0 : 1;
+          Slots[Idx] = (Slots[Idx] << 1) | IdxId;
           if (Slots[Idx] > MaxOpSlot) MaxOpSlot = Slots[Idx];
         }
+    } else if (Opcode == 58) {
+      // If this is the escape sequence for call, emit the tailcall/cc info.
+      const CallInst &CI = cast<CallInst>(I);
+      ++NumOperands;
+      if (NumOperands <= 3) {
+        Slots[NumOperands-1] =
+          (CI.getCallingConv() << 1)|unsigned(CI.isTailCall());
+        if (Slots[NumOperands-1] > MaxOpSlot)
+          MaxOpSlot = Slots[NumOperands-1];
+      }
+    } else if (isa<InvokeInst>(I)) {
+      // Invoke escape seq has at least 4 operands to encode.
+      ++NumOperands;
     }
 
     // Decide which instruction encoding to use.  This is determined primarily
@@ -741,32 +803,23 @@ void BytecodeWriter::outputInstruction(const Instruction &I) {
 //===                              Block Output                            ===//
 //===----------------------------------------------------------------------===//
 
-BytecodeWriter::BytecodeWriter(std::vector<unsigned char> &o, const Module *M) 
+BytecodeWriter::BytecodeWriter(std::vector<unsigned char> &o, const Module *M)
   : Out(o), Table(M) {
 
   // Emit the signature...
-  static const unsigned char *Sig =  (const unsigned char*)"llvm";
+  static const unsigned char *Sig = (const unsigned char*)"llvm";
   output_data(Sig, Sig+4);
 
   // Emit the top level CLASS block.
   BytecodeBlock ModuleBlock(BytecodeFormat::ModuleBlockID, *this, false, true);
 
-  bool isBigEndian      = M->getEndianness() == Module::BigEndian;
-  bool hasLongPointers  = M->getPointerSize() == Module::Pointer64;
-  bool hasNoEndianness  = M->getEndianness() == Module::AnyEndianness;
-  bool hasNoPointerSize = M->getPointerSize() == Module::AnyPointerSize;
-
-  // Output the version identifier... we are currently on bytecode version #2,
-  // which corresponds to LLVM v1.3.
-  unsigned Version = (3 << 4) | (unsigned)isBigEndian | (hasLongPointers << 1) |
-                     (hasNoEndianness << 2) | (hasNoPointerSize << 3);
-  output_vbr(Version);
-  align32();
+  // Output the version identifier
+  output_vbr(BCVersionNum);
 
   // The Global type plane comes first
   {
-      BytecodeBlock CPool(BytecodeFormat::GlobalTypePlaneBlockID, *this );
-      outputTypes(Type::FirstDerivedTyID);
+    BytecodeBlock CPool(BytecodeFormat::GlobalTypePlaneBlockID, *this);
+    outputTypes(Type::FirstDerivedTyID);
   }
 
   // The ModuleInfoBlock follows directly after the type information
@@ -779,12 +832,14 @@ BytecodeWriter::BytecodeWriter(std::vector<unsigned char> &o, const Module *M)
   for (Module::const_iterator I = M->begin(), E = M->end(); I != E; ++I)
     outputFunction(I);
 
-  // If needed, output the symbol table for the module...
-  outputSymbolTable(M->getSymbolTable());
+  // Output the symbole table for types
+  outputTypeSymbolTable(M->getTypeSymbolTable());
+
+  // Output the symbol table for values
+  outputValueSymbolTable(M->getValueSymbolTable());
 }
 
-void BytecodeWriter::outputTypes(unsigned TypeNum)
-{
+void BytecodeWriter::outputTypes(unsigned TypeNum) {
   // Write the type plane for types first because earlier planes (e.g. for a
   // primitive type like float) may have constants constructed using types
   // coming later (e.g., via getelementptr from a pointer type).  The type
@@ -794,7 +849,7 @@ void BytecodeWriter::outputTypes(unsigned TypeNum)
   assert(TypeNum <= Types.size() && "Invalid TypeNo index");
 
   unsigned NumEntries = Types.size() - TypeNum;
-  
+
   // Output type header: [num entries]
   output_vbr(NumEntries);
 
@@ -804,11 +859,11 @@ void BytecodeWriter::outputTypes(unsigned TypeNum)
 
 // Helper function for outputConstants().
 // Writes out all the constants in the plane Plane starting at entry StartNo.
-// 
+//
 void BytecodeWriter::outputConstantsInPlane(const std::vector<const Value*>
                                             &Plane, unsigned StartNo) {
   unsigned ValNo = StartNo;
-  
+
   // Scan through and ignore function arguments, global values, and constant
   // strings.
   for (; ValNo < Plane.size() &&
@@ -818,7 +873,8 @@ void BytecodeWriter::outputConstantsInPlane(const std::vector<const Value*>
     /*empty*/;
 
   unsigned NC = ValNo;              // Number of constants
-  for (; NC < Plane.size() && (isa<Constant>(Plane[NC])); NC++)
+  for (; NC < Plane.size() && (isa<Constant>(Plane[NC]) || 
+                               isa<InlineAsm>(Plane[NC])); NC++)
     /*empty*/;
   NC -= ValNo;                      // Convert from index into count
   if (NC == 0) return;              // Skip empty type planes...
@@ -826,25 +882,26 @@ void BytecodeWriter::outputConstantsInPlane(const std::vector<const Value*>
   // FIXME: Most slabs only have 1 or 2 entries!  We should encode this much
   // more compactly.
 
-  // Output type header: [num entries][type id number]
+  // Put out type header: [num entries][type id number]
   //
   output_vbr(NC);
 
-  // Output the Type ID Number...
+  // Put out the Type ID Number...
   int Slot = Table.getSlot(Plane.front()->getType());
   assert (Slot != -1 && "Type in constant pool but not in function!!");
   output_typeid((unsigned)Slot);
 
   for (unsigned i = ValNo; i < ValNo+NC; ++i) {
     const Value *V = Plane[i];
-    if (const Constant *C = dyn_cast<Constant>(V)) {
+    if (const Constant *C = dyn_cast<Constant>(V))
       outputConstant(C);
-    }
+    else
+      outputInlineAsm(cast<InlineAsm>(V));
   }
 }
 
-static inline bool hasNullValue(unsigned TyID) {
-  return TyID != Type::LabelTyID && TyID != Type::VoidTyID;
+static inline bool hasNullValue(const Type *Ty) {
+  return Ty != Type::LabelTy && Ty != Type::VoidTy && !isa<OpaqueType>(Ty);
 }
 
 void BytecodeWriter::outputConstants(bool isFunction) {
@@ -855,9 +912,9 @@ void BytecodeWriter::outputConstants(bool isFunction) {
 
   if (isFunction)
     // Output the type plane before any constants!
-    outputTypes( Table.getModuleTypeLevel() );
+    outputTypes(Table.getModuleTypeLevel());
   else
-    // Output module-level string constants before any other constants.x
+    // Output module-level string constants before any other constants.
     outputConstantStrings();
 
   for (unsigned pno = 0; pno != NumPlanes; pno++) {
@@ -866,13 +923,13 @@ void BytecodeWriter::outputConstants(bool isFunction) {
       unsigned ValNo = 0;
       if (isFunction)                  // Don't re-emit module constants
         ValNo += Table.getModuleLevel(pno);
-      
-      if (hasNullValue(pno)) {
+
+      if (hasNullValue(Plane[0]->getType())) {
         // Skip zero initializer
         if (ValNo == 0)
           ValNo = 1;
       }
-      
+
       // Write out constants in the plane
       outputConstantsInPlane(Plane, ValNo);
     }
@@ -882,27 +939,78 @@ void BytecodeWriter::outputConstants(bool isFunction) {
 static unsigned getEncodedLinkage(const GlobalValue *GV) {
   switch (GV->getLinkage()) {
   default: assert(0 && "Invalid linkage!");
-  case GlobalValue::ExternalLinkage:  return 0;
-  case GlobalValue::WeakLinkage:      return 1;
-  case GlobalValue::AppendingLinkage: return 2;
-  case GlobalValue::InternalLinkage:  return 3;
-  case GlobalValue::LinkOnceLinkage:  return 4;
+  case GlobalValue::ExternalLinkage:     return 0;
+  case GlobalValue::WeakLinkage:         return 1;
+  case GlobalValue::AppendingLinkage:    return 2;
+  case GlobalValue::InternalLinkage:     return 3;
+  case GlobalValue::LinkOnceLinkage:     return 4;
+  case GlobalValue::DLLImportLinkage:    return 5;
+  case GlobalValue::DLLExportLinkage:    return 6;
+  case GlobalValue::ExternalWeakLinkage: return 7;
+  }
+}
+
+static unsigned getEncodedVisibility(const GlobalValue *GV) {
+  switch (GV->getVisibility()) {
+  default: assert(0 && "Invalid visibility!");
+  case GlobalValue::DefaultVisibility: return 0;
+  case GlobalValue::HiddenVisibility:  return 1;
   }
 }
 
 void BytecodeWriter::outputModuleInfoBlock(const Module *M) {
   BytecodeBlock ModuleInfoBlock(BytecodeFormat::ModuleGlobalInfoBlockID, *this);
+
+  // Give numbers to sections as we encounter them.
+  unsigned SectionIDCounter = 0;
+  std::vector<std::string> SectionNames;
+  std::map<std::string, unsigned> SectionID;
   
   // Output the types for the global variables in the module...
-  for (Module::const_giterator I = M->gbegin(), End = M->gend(); I != End;++I) {
+  for (Module::const_global_iterator I = M->global_begin(),
+         End = M->global_end(); I != End; ++I) {
     int Slot = Table.getSlot(I->getType());
     assert(Slot != -1 && "Module global vars is broken!");
 
+    assert((I->hasInitializer() || !I->hasInternalLinkage()) &&
+           "Global must have an initializer or have external linkage!");
+    
     // Fields: bit0 = isConstant, bit1 = hasInitializer, bit2-4=Linkage,
-    // bit5+ = Slot # for type
-    unsigned oSlot = ((unsigned)Slot << 5) | (getEncodedLinkage(I) << 2) |
-                     (I->hasInitializer() << 1) | (unsigned)I->isConstant();
-    output_vbr(oSlot );
+    // bit5+ = Slot # for type.
+    bool HasExtensionWord = (I->getAlignment() != 0) ||
+                            I->hasSection() ||
+      (I->getVisibility() != GlobalValue::DefaultVisibility);
+    
+    // If we need to use the extension byte, set linkage=3(internal) and
+    // initializer = 0 (impossible!).
+    if (!HasExtensionWord) {
+      unsigned oSlot = ((unsigned)Slot << 5) | (getEncodedLinkage(I) << 2) |
+                        (I->hasInitializer() << 1) | (unsigned)I->isConstant();
+      output_vbr(oSlot);
+    } else {  
+      unsigned oSlot = ((unsigned)Slot << 5) | (3 << 2) |
+                        (0 << 1) | (unsigned)I->isConstant();
+      output_vbr(oSlot);
+      
+      // The extension word has this format: bit 0 = has initializer, bit 1-3 =
+      // linkage, bit 4-8 = alignment (log2), bit 9 = has SectionID,
+      // bits 10-12 = visibility, bits 13+ = future use.
+      unsigned ExtWord = (unsigned)I->hasInitializer() |
+                         (getEncodedLinkage(I) << 1) |
+                         ((Log2_32(I->getAlignment())+1) << 4) |
+                         ((unsigned)I->hasSection() << 9) |
+                         (getEncodedVisibility(I) << 10);
+      output_vbr(ExtWord);
+      if (I->hasSection()) {
+        // Give section names unique ID's.
+        unsigned &Entry = SectionID[I->getSection()];
+        if (Entry == 0) {
+          Entry = ++SectionIDCounter;
+          SectionNames.push_back(I->getSection());
+        }
+        output_vbr(Entry);
+      }
+    }
 
     // If we have an initializer, output it now.
     if (I->hasInitializer()) {
@@ -913,25 +1021,77 @@ void BytecodeWriter::outputModuleInfoBlock(const Module *M) {
   }
   output_typeid((unsigned)Table.getSlot(Type::VoidTy));
 
-  // Output the types of the functions in this module...
+  // Output the types of the functions in this module.
   for (Module::const_iterator I = M->begin(), End = M->end(); I != End; ++I) {
     int Slot = Table.getSlot(I->getType());
-    assert(Slot != -1 && "Module const pool is broken!");
+    assert(Slot != -1 && "Module slot calculator is broken!");
     assert(Slot >= Type::FirstDerivedTyID && "Derived type not in range!");
-    output_typeid((unsigned)Slot);
-  }
-  output_typeid((unsigned)Table.getSlot(Type::VoidTy));
+    assert(((Slot << 6) >> 6) == Slot && "Slot # too big!");
+    unsigned CC = I->getCallingConv()+1;
+    unsigned ID = (Slot << 5) | (CC & 15);
+
+    if (I->isDeclaration())   // If external, we don't have an FunctionInfo block.
+      ID |= 1 << 4;
+    
+    if (I->getAlignment() || I->hasSection() || (CC & ~15) != 0 ||
+        (I->isDeclaration() && I->hasDLLImportLinkage()) ||
+        (I->isDeclaration() && I->hasExternalWeakLinkage())
+       )
+      ID |= 1 << 31;       // Do we need an extension word?
+    
+    output_vbr(ID);
+    
+    if (ID & (1 << 31)) {
+      // Extension byte: bits 0-4 = alignment, bits 5-9 = top nibble of calling
+      // convention, bit 10 = hasSectionID., bits 11-12 = external linkage type
+      unsigned extLinkage = 0;
+
+      if (I->isDeclaration()) {
+        if (I->hasDLLImportLinkage()) {
+          extLinkage = 1;
+        } else if (I->hasExternalWeakLinkage()) {
+          extLinkage = 2;
+        }
+      }
 
-  // Put out the list of dependent libraries for the Module
-  Module::const_literator LI = M->lbegin();
-  Module::const_literator LE = M->lend();
-  output_vbr( unsigned(LE - LI) ); // Put out the number of dependent libraries
-  for ( ; LI != LE; ++LI ) {
-    output(*LI, /*aligned=*/false);
+      ID = (Log2_32(I->getAlignment())+1) | ((CC >> 4) << 5) | 
+        (I->hasSection() << 10) |
+        ((extLinkage & 3) << 11);
+      output_vbr(ID);
+      
+      // Give section names unique ID's.
+      if (I->hasSection()) {
+        unsigned &Entry = SectionID[I->getSection()];
+        if (Entry == 0) {
+          Entry = ++SectionIDCounter;
+          SectionNames.push_back(I->getSection());
+        }
+        output_vbr(Entry);
+      }
+    }
   }
+  output_vbr((unsigned)Table.getSlot(Type::VoidTy) << 5);
+
+  // Emit the list of dependent libraries for the Module.
+  Module::lib_iterator LI = M->lib_begin();
+  Module::lib_iterator LE = M->lib_end();
+  output_vbr(unsigned(LE - LI));   // Emit the number of dependent libraries.
+  for (; LI != LE; ++LI)
+    output(*LI);
 
   // Output the target triple from the module
-  output(M->getTargetTriple(), /*aligned=*/ true);
+  output(M->getTargetTriple());
+
+  // Output the data layout from the module
+  output(M->getDataLayout());
+  
+  // Emit the table of section names.
+  output_vbr((unsigned)SectionNames.size());
+  for (unsigned i = 0, e = SectionNames.size(); i != e; ++i)
+    output(SectionNames[i]);
+  
+  // Output the inline asm string.
+  output(M->getModuleInlineAsm());
 }
 
 void BytecodeWriter::outputInstructions(const Function *F) {
@@ -942,173 +1102,148 @@ void BytecodeWriter::outputInstructions(const Function *F) {
 }
 
 void BytecodeWriter::outputFunction(const Function *F) {
-  BytecodeBlock FunctionBlock(BytecodeFormat::FunctionBlockID, *this);
-  output_vbr(getEncodedLinkage(F));
-
   // If this is an external function, there is nothing else to emit!
-  if (F->isExternal()) return;
+  if (F->isDeclaration()) return;
+
+  BytecodeBlock FunctionBlock(BytecodeFormat::FunctionBlockID, *this);
+  unsigned rWord = (getEncodedVisibility(F) << 16) | getEncodedLinkage(F);
+  output_vbr(rWord);
 
   // Get slot information about the function...
   Table.incorporateFunction(F);
 
-  if (Table.getCompactionTable().empty()) {
-    // Output information about the constants in the function if the compaction
-    // table is not being used.
-    outputConstants(true);
-  } else {
-    // Otherwise, emit the compaction table.
-    outputCompactionTable();
-  }
-  
+  outputConstants(true);
+
   // Output all of the instructions in the body of the function
   outputInstructions(F);
-  
-  // If needed, output the symbol table for the function...
-  outputSymbolTable(F->getSymbolTable());
-  
-  Table.purgeFunction();
-}
 
-void BytecodeWriter::outputCompactionTablePlane(unsigned PlaneNo,
-                                         const std::vector<const Value*> &Plane,
-                                                unsigned StartNo) {
-  unsigned End = Table.getModuleLevel(PlaneNo);
-  if (Plane.empty() || StartNo == End || End == 0) return;   // Nothing to emit
-  assert(StartNo < End && "Cannot emit negative range!");
-  assert(StartNo < Plane.size() && End <= Plane.size());
-
-  // Do not emit the null initializer!
-  ++StartNo;
-
-  // Figure out which encoding to use.  By far the most common case we have is
-  // to emit 0-2 entries in a compaction table plane.
-  switch (End-StartNo) {
-  case 0:         // Avoid emitting two vbr's if possible.
-  case 1:
-  case 2:
-    output_vbr((PlaneNo << 2) | End-StartNo);
-    break;
-  default:
-    // Output the number of things.
-    output_vbr((unsigned(End-StartNo) << 2) | 3);
-    output_typeid(PlaneNo);                 // Emit the type plane this is
-    break;
-  }
+  // If needed, output the symbol table for the function...
+  outputValueSymbolTable(F->getValueSymbolTable());
 
-  for (unsigned i = StartNo; i != End; ++i)
-    output_vbr(Table.getGlobalSlot(Plane[i]));
+  Table.purgeFunction();
 }
 
-void BytecodeWriter::outputCompactionTypes(unsigned StartNo) {
-  // Get the compaction type table from the slot calculator
-  const std::vector<const Type*> &CTypes = Table.getCompactionTypes();
 
-  // The compaction types may have been uncompactified back to the
-  // global types. If so, we just write an empty table
-  if (CTypes.size() == 0 ) {
-    output_vbr(0U);
-    return;
+void BytecodeWriter::outputTypeSymbolTable(const TypeSymbolTable &TST) {
+  // Do not output the block for an empty symbol table, it just wastes
+  // space!
+  if (TST.empty()) return;
+
+  // Create a header for the symbol table
+  BytecodeBlock SymTabBlock(BytecodeFormat::TypeSymbolTableBlockID, *this,
+                            true/*ElideIfEmpty*/);
+  // Write the number of types
+  output_vbr(TST.size());
+
+  // Write each of the types
+  for (TypeSymbolTable::const_iterator TI = TST.begin(), TE = TST.end(); 
+       TI != TE; ++TI) {
+    // Symtab entry:[def slot #][name]
+    output_typeid((unsigned)Table.getSlot(TI->second));
+    output(TI->first);
   }
-
-  assert(CTypes.size() >= StartNo && "Invalid compaction types start index");
-
-  // Determine how many types to write
-  unsigned NumTypes = CTypes.size() - StartNo;
-
-  // Output the number of types.
-  output_vbr(NumTypes);
-
-  for (unsigned i = StartNo; i < StartNo+NumTypes; ++i)
-    output_typeid(Table.getGlobalSlot(CTypes[i]));
 }
 
-void BytecodeWriter::outputCompactionTable() {
-  BytecodeBlock CTB(BytecodeFormat::CompactionTableBlockID, *this, 
-                    true/*ElideIfEmpty*/);
-  const std::vector<std::vector<const Value*> > &CT =Table.getCompactionTable();
-  
-  // First thing is first, emit the type compaction table if there is one.
-  outputCompactionTypes(Type::FirstDerivedTyID);
-
-  for (unsigned i = 0, e = CT.size(); i != e; ++i)
-    outputCompactionTablePlane(i, CT[i], 0);
-}
-
-void BytecodeWriter::outputSymbolTable(const SymbolTable &MST) {
+void BytecodeWriter::outputValueSymbolTable(const ValueSymbolTable &VST) {
   // Do not output the Bytecode block for an empty symbol table, it just wastes
   // space!
-  if ( MST.isEmpty() ) return;
-
-  BytecodeBlock SymTabBlock(BytecodeFormat::SymbolTableBlockID, *this,
-                            true/* ElideIfEmpty*/);
+  if (VST.empty()) return;
+
+  BytecodeBlock SymTabBlock(BytecodeFormat::ValueSymbolTableBlockID, *this,
+                            true/*ElideIfEmpty*/);
+
+  // Organize the symbol table by type
+  typedef std::pair<std::string, const Value*> PlaneMapEntry;
+  typedef std::vector<PlaneMapEntry> PlaneMapVector;
+  typedef std::map<const Type*, PlaneMapVector > PlaneMap;
+  PlaneMap Planes;
+  for (ValueSymbolTable::const_iterator SI = VST.begin(), SE = VST.end();
+       SI != SE; ++SI) 
+    Planes[SI->second->getType()].push_back(
+        std::make_pair(SI->first,SI->second));
+
+  for (PlaneMap::const_iterator PI = Planes.begin(), PE = Planes.end();
+       PI != PE; ++PI) {
+    int Slot;
 
-  //Symtab block header for types: [num entries]
-  output_vbr(MST.num_types());
-  for (SymbolTable::type_const_iterator TI = MST.type_begin(),
-       TE = MST.type_end(); TI != TE; ++TI ) {
-    //Symtab entry:[def slot #][name]
-    output_typeid((unsigned)Table.getSlot(TI->second));
-    output(TI->first, /*align=*/false); 
-  }
+    PlaneMapVector::const_iterator I = PI->second.begin(); 
+    PlaneMapVector::const_iterator End = PI->second.end(); 
 
-  // Now do each of the type planes in order.
-  for (SymbolTable::plane_const_iterator PI = MST.plane_begin(), 
-       PE = MST.plane_end(); PI != PE;  ++PI) {
-    SymbolTable::value_const_iterator I = MST.value_begin(PI->first);
-    SymbolTable::value_const_iterator End = MST.value_end(PI->first);
-    int Slot;
-    
     if (I == End) continue;  // Don't mess with an absent type...
 
-    // Symtab block header: [num entries][type id number]
-    output_vbr(MST.type_size(PI->first));
+    // Write the number of values in this plane
+    output_vbr((unsigned)PI->second.size());
 
+    // Write the slot number of the type for this plane
     Slot = Table.getSlot(PI->first);
     assert(Slot != -1 && "Type in symtab, but not in table!");
     output_typeid((unsigned)Slot);
 
+    // Write each of the values in this plane
     for (; I != End; ++I) {
       // Symtab entry: [def slot #][name]
       Slot = Table.getSlot(I->second);
       assert(Slot != -1 && "Value in symtab but has no slot number!!");
       output_vbr((unsigned)Slot);
-      output(I->first, false); // Don't force alignment...
+      output(I->first);
     }
   }
 }
 
-void llvm::WriteBytecodeToFile(const Module *M, std::ostream &Out) {
+void llvm::WriteBytecodeToFile(const Module *M, OStream &Out,
+                               bool compress) {
   assert(M && "You can't write a null module!!");
 
+  // Make sure that std::cout is put into binary mode for systems
+  // that care.
+  if (Out == cout)
+    sys::Program::ChangeStdoutToBinary();
+
+  // Create a vector of unsigned char for the bytecode output. We
+  // reserve 256KBytes of space in the vector so that we avoid doing
+  // lots of little allocations. 256KBytes is sufficient for a large
+  // proportion of the bytecode files we will encounter. Larger files
+  // will be automatically doubled in size as needed (std::vector
+  // behavior).
   std::vector<unsigned char> Buffer;
-  Buffer.reserve(64 * 1024); // avoid lots of little reallocs
+  Buffer.reserve(256 * 1024);
 
-  // This object populates buffer for us...
+  // The BytecodeWriter populates Buffer for us.
   BytecodeWriter BCW(Buffer, M);
 
-  // Keep track of how much we've written...
+  // Keep track of how much we've written
   BytesWritten += Buffer.size();
 
-  // Okay, write the deque out to the ostream now... the deque is not
-  // sequential in memory, however, so write out as much as possible in big
-  // chunks, until we're done.
-  //
+  // Determine start and end points of the Buffer
+  const unsigned char *FirstByte = &Buffer.front();
 
-  std::vector<unsigned char>::const_iterator I = Buffer.begin(),E = Buffer.end();
-  while (I != E) {                           // Loop until it's all written
-    // Scan to see how big this chunk is...
-    const unsigned char *ChunkPtr = &*I;
-    const unsigned char *LastPtr = ChunkPtr;
-    while (I != E) {
-      const unsigned char *ThisPtr = &*++I;
-      if (++LastPtr != ThisPtr) // Advanced by more than a byte of memory?
-        break;
-    }
-    
-    // Write out the chunk...
-    Out.write((char*)ChunkPtr, unsigned(LastPtr-ChunkPtr));
+  // If we're supposed to compress this mess ...
+  if (compress) {
+
+    // We signal compression by using an alternate magic number for the
+    // file. The compressed bytecode file's magic number is "llvc" instead
+    // of "llvm".
+    char compressed_magic[4];
+    compressed_magic[0] = 'l';
+    compressed_magic[1] = 'l';
+    compressed_magic[2] = 'v';
+    compressed_magic[3] = 'c';
+
+    Out.stream()->write(compressed_magic,4);
+
+    // Compress everything after the magic number (which we altered)
+    Compressor::compressToStream(
+      (char*)(FirstByte+4),        // Skip the magic number
+      Buffer.size()-4,             // Skip the magic number
+      *Out.stream()                // Where to write compressed data
+    );
+
+  } else {
+
+    // We're not compressing, so just write the entire block.
+    Out.stream()->write((char*)FirstByte, Buffer.size());
   }
-  Out.flush();
-}
 
-// vim: sw=2 ai
+  // make sure it hits disk now
+  Out.stream()->flush();
+}