Eliminate all remaining tabs and trailing spaces.
[oota-llvm.git] / lib / Bytecode / Writer / Writer.cpp
index 92811ada5a992e650e9513c79cba249303369684..95bbd2e57540750ca1890e36d38aab47ac26a3f4 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
 
 #include "WriterInternals.h"
 #include "llvm/Bytecode/WriteBytecodePass.h"
+#include "llvm/CallingConv.h"
 #include "llvm/Constants.h"
 #include "llvm/DerivedTypes.h"
 #include "llvm/Instructions.h"
 #include "llvm/Module.h"
 #include "llvm/SymbolTable.h"
 #include "llvm/Support/GetElementPtrTypeIterator.h"
-#include "Support/STLExtras.h"
-#include "Support/Statistic.h"
+#include "llvm/Support/Compressor.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 = 5;
+
 static RegisterPass<WriteBytecodePass> X("emitbytecode", "Bytecode Writer");
 
-static Statistic<> 
+static Statistic<>
 BytesWritten("bytecodewriter", "Number of bytecode bytes written");
 
 //===----------------------------------------------------------------------===//
@@ -41,11 +49,11 @@ BytesWritten("bytecodewriter", "Number of bytecode bytes written");
 //===----------------------------------------------------------------------===//
 
 // 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 +72,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 +94,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 +112,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 +120,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...
   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) {
@@ -173,7 +169,7 @@ inline void BytecodeWriter::output_double(double& DoubleVal) {
 }
 
 inline BytecodeBlock::BytecodeBlock(unsigned ID, BytecodeWriter& w,
-                    bool elideIfEmpty, bool hasLongFormat )
+                                    bool elideIfEmpty, bool hasLongFormat )
   : Id(ID), Writer(w), ElideIfEmpty(elideIfEmpty), HasLongFormat(hasLongFormat){
 
   if (HasLongFormat) {
@@ -185,8 +181,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 +190,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
 }
 
 //===----------------------------------------------------------------------===//
@@ -209,7 +202,7 @@ inline BytecodeBlock::~BytecodeBlock() {           // Do backpatch when block go
 
 void BytecodeWriter::outputType(const Type *T) {
   output_vbr((unsigned)T->getTypeID());
-  
+
   // That's all there is to handling primitive types...
   if (T->isPrimitiveType()) {
     return;     // We might do this if we alias a prim type: %x = type int
@@ -244,12 +237,20 @@ 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);
 
@@ -274,12 +275,10 @@ 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";
@@ -293,13 +292,14 @@ void BytecodeWriter::outputConstant(const Constant *CPV) {
 
   // 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
+    assert(CE->getNumOperands() != 1 || CE->getOpcode() == Instruction::Cast);
+    output_vbr(1+CE->getNumOperands());   // flags as an expr
     output_vbr(CE->getOpcode());        // flags as an expr
-    
+
     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!!");
@@ -308,10 +308,13 @@ void BytecodeWriter::outputConstant(const Constant *CPV) {
       output_typeid((unsigned)Slot);
     }
     return;
+  } else if (isa<UndefValue>(CPV)) {
+    output_vbr(1U);       // 1 -> UndefValue constant.
+    return;
   } else {
     output_vbr(0U);       // flag as not a ConstantExpr
   }
-  
+
   switch (CPV->getType()->getTypeID()) {
   case Type::BoolTyID:    // Boolean Types
     if (cast<ConstantBool>(CPV)->getValue())
@@ -338,7 +341,7 @@ void BytecodeWriter::outputConstant(const Constant *CPV) {
     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 +349,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,7 +386,7 @@ 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"
@@ -392,14 +405,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();
@@ -412,26 +425,27 @@ void BytecodeWriter::outputConstantStrings() {
 //===----------------------------------------------------------------------===//
 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<VAArgInst>(I) || Opcode == 56 || 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 +453,15 @@ 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 (Opcode == 56) {  // Invoke escape sequence
+      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,8 +469,8 @@ 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()) {
@@ -471,8 +485,6 @@ void BytecodeWriter::outputInstructionFormat0(const Instruction *I, unsigned Opc
       output_vbr(unsigned(Slot));
     }
   }
-
-  align32();    // We must maintain correct alignment!
 }
 
 
@@ -485,10 +497,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
@@ -515,32 +527,31 @@ void BytecodeWriter::outputInstrVarArgsCall(const Instruction *I,
   // 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!
 }
 
 
 // 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 +559,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 +598,48 @@ 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() < 56 && "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 (const InvokeInst *II = dyn_cast<InvokeInst>(&I)) {
+    if (II->getCallingConv() == CallingConv::Fast)
+      Opcode = 57;      // FastCC invoke.
+    else if (II->getCallingConv() != CallingConv::C)
+      Opcode = 56;      // Invoke 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 +684,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,11 +700,6 @@ 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];
-      NumOperands++;
     } 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;
@@ -698,6 +717,18 @@ void BytecodeWriter::outputInstruction(const Instruction &I) {
           Slots[Idx] = (Slots[Idx] << 2) | 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 (Opcode == 56) {
+      // Invoke escape seq has at least 4 operands to encode.
+      ++NumOperands;
     }
 
     // Decide which instruction encoding to use.  This is determined primarily
@@ -741,7 +772,7 @@ 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...
@@ -756,12 +787,12 @@ BytecodeWriter::BytecodeWriter(std::vector<unsigned char> &o, const Module *M)
   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 the version identifier and other information.
+  unsigned Version = (BCVersionNum << 4) |
+                     (unsigned)isBigEndian | (hasLongPointers << 1) |
+                     (hasNoEndianness << 2) |
+                     (hasNoPointerSize << 3);
   output_vbr(Version);
-  align32();
 
   // The Global type plane comes first
   {
@@ -783,8 +814,7 @@ BytecodeWriter::BytecodeWriter(std::vector<unsigned char> &o, const Module *M)
   outputSymbolTable(M->getSymbolTable());
 }
 
-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 +824,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 +834,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() &&
@@ -843,8 +873,8 @@ void BytecodeWriter::outputConstantsInPlane(const std::vector<const Value*>
   }
 }
 
-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 +885,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 +896,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);
     }
@@ -892,9 +922,10 @@ static unsigned getEncodedLinkage(const GlobalValue *GV) {
 
 void BytecodeWriter::outputModuleInfoBlock(const Module *M) {
   BytecodeBlock ModuleInfoBlock(BytecodeFormat::ModuleGlobalInfoBlockID, *this);
-  
+
   // 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!");
 
@@ -902,7 +933,7 @@ void BytecodeWriter::outputModuleInfoBlock(const Module *M) {
     // bit5+ = Slot # for type
     unsigned oSlot = ((unsigned)Slot << 5) | (getEncodedLinkage(I) << 2) |
                      (I->hasInitializer() << 1) | (unsigned)I->isConstant();
-    output_vbr(oSlot );
+    output_vbr(oSlot);
 
     // If we have an initializer, output it now.
     if (I->hasInitializer()) {
@@ -913,25 +944,35 @@ 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);
+    assert(((Slot << 5) >> 5) == Slot && "Slot # too big!");
+    unsigned ID = (Slot << 5);
+
+    if (I->getCallingConv() < 15)
+      ID += I->getCallingConv()+1;
+
+    if (I->isExternal())   // If external, we don't have an FunctionInfo block.
+      ID |= 1 << 4;
+    output_vbr(ID);
+
+    if (I->getCallingConv() >= 15)
+      output_vbr(I->getCallingConv());
   }
-  output_typeid((unsigned)Table.getSlot(Type::VoidTy));
+  output_vbr((unsigned)Table.getSlot(Type::VoidTy) << 5);
 
-  // Put out the list of dependent libraries for the Module
+  // 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) ); // Put out the number of dependent libraries
-  for ( ; LI != LE; ++LI ) {
-    output(*LI, /*aligned=*/false);
-  }
+  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());
 }
 
 void BytecodeWriter::outputInstructions(const Function *F) {
@@ -942,12 +983,12 @@ 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;
 
+  BytecodeBlock FunctionBlock(BytecodeFormat::FunctionBlockID, *this);
+  output_vbr(getEncodedLinkage(F));
+
   // Get slot information about the function...
   Table.incorporateFunction(F);
 
@@ -959,13 +1000,13 @@ void BytecodeWriter::outputFunction(const Function *F) {
     // Otherwise, emit the compaction table.
     outputCompactionTable();
   }
-  
+
   // 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();
 }
 
@@ -1023,92 +1064,119 @@ void BytecodeWriter::outputCompactionTypes(unsigned StartNo) {
 }
 
 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);
+  // Avoid writing the compaction table at all if there is no content.
+  if (Table.getCompactionTypes().size() >= Type::FirstDerivedTyID ||
+      (!Table.CompactionTableIsEmpty())) {
+    BytecodeBlock CTB(BytecodeFormat::CompactionTableBlockID, *this,
+                      true/*ElideIfEmpty*/);
+    const std::vector<std::vector<const Value*> > &CT =
+      Table.getCompactionTable();
+
+    // First things 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) {
   // Do not output the Bytecode block for an empty symbol table, it just wastes
   // space!
-  if ( MST.isEmpty() ) return;
+  if (MST.isEmpty()) return;
 
   BytecodeBlock SymTabBlock(BytecodeFormat::SymbolTableBlockID, *this,
-                            true/* ElideIfEmpty*/);
+                            true/*ElideIfEmpty*/);
 
-  //Symtab block header for types: [num entries]
+  // Write the number of types
   output_vbr(MST.num_types());
+
+  // Write each of the types
   for (SymbolTable::type_const_iterator TI = MST.type_begin(),
        TE = MST.type_end(); TI != TE; ++TI ) {
-    //Symtab entry:[def slot #][name]
+    // Symtab entry:[def slot #][name]
     output_typeid((unsigned)Table.getSlot(TI->second));
-    output(TI->first, /*align=*/false); 
+    output(TI->first);
   }
 
   // Now do each of the type planes in order.
-  for (SymbolTable::plane_const_iterator PI = MST.plane_begin(), 
+  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, std::ostream &Out,
+                               bool compress ) {
   assert(M && "You can't write a null module!!");
 
+  // 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.write(compressed_magic,4);
+
+    // Compress everything after the magic number (which we altered)
+    uint64_t zipSize = Compressor::compressToStream(
+      (char*)(FirstByte+4),        // Skip the magic number
+      Buffer.size()-4,             // Skip the magic number
+      Out                          // Where to write compressed data
+    );
+
+  } else {
+
+    // We're not compressing, so just write the entire block.
+    Out.write((char*)FirstByte, Buffer.size());
   }
+
+  // make sure it hits disk now
   Out.flush();
 }
 
-// vim: sw=2 ai