switch statistics over to not use static ctors.
[oota-llvm.git] / lib / Bytecode / Writer / Writer.cpp
1 //===-- Writer.cpp - Library for writing LLVM bytecode files --------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This library implements the functionality defined in llvm/Bytecode/Writer.h
11 //
12 // Note that this file uses an unusual technique of outputting all the bytecode
13 // to a vector of unsigned char, then copies the vector to an ostream.  The
14 // reason for this is that we must do "seeking" in the stream to do back-
15 // patching, and some very important ostreams that we want to support (like
16 // pipes) do not support seeking.  :( :( :(
17 //
18 //===----------------------------------------------------------------------===//
19
20 #define DEBUG_TYPE "bytecodewriter"
21 #include "WriterInternals.h"
22 #include "llvm/Bytecode/WriteBytecodePass.h"
23 #include "llvm/CallingConv.h"
24 #include "llvm/Constants.h"
25 #include "llvm/DerivedTypes.h"
26 #include "llvm/InlineAsm.h"
27 #include "llvm/Instructions.h"
28 #include "llvm/Module.h"
29 #include "llvm/SymbolTable.h"
30 #include "llvm/Support/GetElementPtrTypeIterator.h"
31 #include "llvm/Support/Compressor.h"
32 #include "llvm/Support/MathExtras.h"
33 #include "llvm/Support/Streams.h"
34 #include "llvm/System/Program.h"
35 #include "llvm/ADT/STLExtras.h"
36 #include "llvm/ADT/Statistic.h"
37 #include <cstring>
38 #include <algorithm>
39 using namespace llvm;
40
41 /// This value needs to be incremented every time the bytecode format changes
42 /// so that the reader can distinguish which format of the bytecode file has
43 /// been written.
44 /// @brief The bytecode version number
45 const unsigned BCVersionNum = 7;
46
47 static RegisterPass<WriteBytecodePass> X("emitbytecode", "Bytecode Writer");
48
49 STATISTIC(BytesWritten, "Number of bytecode bytes written");
50
51 //===----------------------------------------------------------------------===//
52 //===                           Output Primitives                          ===//
53 //===----------------------------------------------------------------------===//
54
55 // output - If a position is specified, it must be in the valid portion of the
56 // string... note that this should be inlined always so only the relevant IF
57 // body should be included.
58 inline void BytecodeWriter::output(unsigned i, int pos) {
59   if (pos == -1) { // Be endian clean, little endian is our friend
60     Out.push_back((unsigned char)i);
61     Out.push_back((unsigned char)(i >> 8));
62     Out.push_back((unsigned char)(i >> 16));
63     Out.push_back((unsigned char)(i >> 24));
64   } else {
65     Out[pos  ] = (unsigned char)i;
66     Out[pos+1] = (unsigned char)(i >> 8);
67     Out[pos+2] = (unsigned char)(i >> 16);
68     Out[pos+3] = (unsigned char)(i >> 24);
69   }
70 }
71
72 inline void BytecodeWriter::output(int i) {
73   output((unsigned)i);
74 }
75
76 /// output_vbr - Output an unsigned value, by using the least number of bytes
77 /// possible.  This is useful because many of our "infinite" values are really
78 /// very small most of the time; but can be large a few times.
79 /// Data format used:  If you read a byte with the high bit set, use the low
80 /// seven bits as data and then read another byte.
81 inline void BytecodeWriter::output_vbr(uint64_t i) {
82   while (1) {
83     if (i < 0x80) { // done?
84       Out.push_back((unsigned char)i);   // We know the high bit is clear...
85       return;
86     }
87
88     // Nope, we are bigger than a character, output the next 7 bits and set the
89     // high bit to say that there is more coming...
90     Out.push_back(0x80 | ((unsigned char)i & 0x7F));
91     i >>= 7;  // Shift out 7 bits now...
92   }
93 }
94
95 inline void BytecodeWriter::output_vbr(unsigned i) {
96   while (1) {
97     if (i < 0x80) { // done?
98       Out.push_back((unsigned char)i);   // We know the high bit is clear...
99       return;
100     }
101
102     // Nope, we are bigger than a character, output the next 7 bits and set the
103     // high bit to say that there is more coming...
104     Out.push_back(0x80 | ((unsigned char)i & 0x7F));
105     i >>= 7;  // Shift out 7 bits now...
106   }
107 }
108
109 inline void BytecodeWriter::output_typeid(unsigned i) {
110   if (i <= 0x00FFFFFF)
111     this->output_vbr(i);
112   else {
113     this->output_vbr(0x00FFFFFF);
114     this->output_vbr(i);
115   }
116 }
117
118 inline void BytecodeWriter::output_vbr(int64_t i) {
119   if (i < 0)
120     output_vbr(((uint64_t)(-i) << 1) | 1); // Set low order sign bit...
121   else
122     output_vbr((uint64_t)i << 1);          // Low order bit is clear.
123 }
124
125
126 inline void BytecodeWriter::output_vbr(int i) {
127   if (i < 0)
128     output_vbr(((unsigned)(-i) << 1) | 1); // Set low order sign bit...
129   else
130     output_vbr((unsigned)i << 1);          // Low order bit is clear.
131 }
132
133 inline void BytecodeWriter::output(const std::string &s) {
134   unsigned Len = s.length();
135   output_vbr(Len);             // Strings may have an arbitrary length.
136   Out.insert(Out.end(), s.begin(), s.end());
137 }
138
139 inline void BytecodeWriter::output_data(const void *Ptr, const void *End) {
140   Out.insert(Out.end(), (const unsigned char*)Ptr, (const unsigned char*)End);
141 }
142
143 inline void BytecodeWriter::output_float(float& FloatVal) {
144   /// FIXME: This isn't optimal, it has size problems on some platforms
145   /// where FP is not IEEE.
146   uint32_t i = FloatToBits(FloatVal);
147   Out.push_back( static_cast<unsigned char>( (i      ) & 0xFF));
148   Out.push_back( static_cast<unsigned char>( (i >> 8 ) & 0xFF));
149   Out.push_back( static_cast<unsigned char>( (i >> 16) & 0xFF));
150   Out.push_back( static_cast<unsigned char>( (i >> 24) & 0xFF));
151 }
152
153 inline void BytecodeWriter::output_double(double& DoubleVal) {
154   /// FIXME: This isn't optimal, it has size problems on some platforms
155   /// where FP is not IEEE.
156   uint64_t i = DoubleToBits(DoubleVal);
157   Out.push_back( static_cast<unsigned char>( (i      ) & 0xFF));
158   Out.push_back( static_cast<unsigned char>( (i >> 8 ) & 0xFF));
159   Out.push_back( static_cast<unsigned char>( (i >> 16) & 0xFF));
160   Out.push_back( static_cast<unsigned char>( (i >> 24) & 0xFF));
161   Out.push_back( static_cast<unsigned char>( (i >> 32) & 0xFF));
162   Out.push_back( static_cast<unsigned char>( (i >> 40) & 0xFF));
163   Out.push_back( static_cast<unsigned char>( (i >> 48) & 0xFF));
164   Out.push_back( static_cast<unsigned char>( (i >> 56) & 0xFF));
165 }
166
167 inline BytecodeBlock::BytecodeBlock(unsigned ID, BytecodeWriter &w,
168                                     bool elideIfEmpty, bool hasLongFormat)
169   : Id(ID), Writer(w), ElideIfEmpty(elideIfEmpty), HasLongFormat(hasLongFormat){
170
171   if (HasLongFormat) {
172     w.output(ID);
173     w.output(0U); // For length in long format
174   } else {
175     w.output(0U); /// Place holder for ID and length for this block
176   }
177   Loc = w.size();
178 }
179
180 inline BytecodeBlock::~BytecodeBlock() { // Do backpatch when block goes out
181                                          // of scope...
182   if (Loc == Writer.size() && ElideIfEmpty) {
183     // If the block is empty, and we are allowed to, do not emit the block at
184     // all!
185     Writer.resize(Writer.size()-(HasLongFormat?8:4));
186     return;
187   }
188
189   if (HasLongFormat)
190     Writer.output(unsigned(Writer.size()-Loc), int(Loc-4));
191   else
192     Writer.output(unsigned(Writer.size()-Loc) << 5 | (Id & 0x1F), int(Loc-4));
193 }
194
195 //===----------------------------------------------------------------------===//
196 //===                           Constant Output                            ===//
197 //===----------------------------------------------------------------------===//
198
199 void BytecodeWriter::outputType(const Type *T) {
200   const StructType* STy = dyn_cast<StructType>(T);
201   if(STy && STy->isPacked())
202     output_vbr((unsigned)Type::BC_ONLY_PackedStructTyID);
203   else
204     output_vbr((unsigned)T->getTypeID());
205
206   // That's all there is to handling primitive types...
207   if (T->isPrimitiveType()) {
208     return;     // We might do this if we alias a prim type: %x = type int
209   }
210
211   switch (T->getTypeID()) {   // Handle derived types now.
212   case Type::FunctionTyID: {
213     const FunctionType *MT = cast<FunctionType>(T);
214     int Slot = Table.getSlot(MT->getReturnType());
215     assert(Slot != -1 && "Type used but not available!!");
216     output_typeid((unsigned)Slot);
217
218     // Output the number of arguments to function (+1 if varargs):
219     output_vbr((unsigned)MT->getNumParams()+MT->isVarArg());
220
221     // Output all of the arguments...
222     FunctionType::param_iterator I = MT->param_begin();
223     for (; I != MT->param_end(); ++I) {
224       Slot = Table.getSlot(*I);
225       assert(Slot != -1 && "Type used but not available!!");
226       output_typeid((unsigned)Slot);
227     }
228
229     // Terminate list with VoidTy if we are a varargs function...
230     if (MT->isVarArg())
231       output_typeid((unsigned)Type::VoidTyID);
232     break;
233   }
234
235   case Type::ArrayTyID: {
236     const ArrayType *AT = cast<ArrayType>(T);
237     int Slot = Table.getSlot(AT->getElementType());
238     assert(Slot != -1 && "Type used but not available!!");
239     output_typeid((unsigned)Slot);
240     output_vbr(AT->getNumElements());
241     break;
242   }
243
244  case Type::PackedTyID: {
245     const PackedType *PT = cast<PackedType>(T);
246     int Slot = Table.getSlot(PT->getElementType());
247     assert(Slot != -1 && "Type used but not available!!");
248     output_typeid((unsigned)Slot);
249     output_vbr(PT->getNumElements());
250     break;
251   }
252
253   case Type::StructTyID: {
254     const StructType *ST = cast<StructType>(T);
255     // Output all of the element types...
256     for (StructType::element_iterator I = ST->element_begin(),
257            E = ST->element_end(); I != E; ++I) {
258       int Slot = Table.getSlot(*I);
259       assert(Slot != -1 && "Type used but not available!!");
260       output_typeid((unsigned)Slot);
261     }
262
263     // Terminate list with VoidTy
264     output_typeid((unsigned)Type::VoidTyID);
265     break;
266   }
267
268   case Type::PointerTyID: {
269     const PointerType *PT = cast<PointerType>(T);
270     int Slot = Table.getSlot(PT->getElementType());
271     assert(Slot != -1 && "Type used but not available!!");
272     output_typeid((unsigned)Slot);
273     break;
274   }
275
276   case Type::OpaqueTyID:
277     // No need to emit anything, just the count of opaque types is enough.
278     break;
279
280   default:
281     cerr << __FILE__ << ":" << __LINE__ << ": Don't know how to serialize"
282          << " Type '" << T->getDescription() << "'\n";
283     break;
284   }
285 }
286
287 void BytecodeWriter::outputConstant(const Constant *CPV) {
288   assert((CPV->getType()->isPrimitiveType() || !CPV->isNullValue()) &&
289          "Shouldn't output null constants!");
290
291   // We must check for a ConstantExpr before switching by type because
292   // a ConstantExpr can be of any type, and has no explicit value.
293   //
294   if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CPV)) {
295     // FIXME: Encoding of constant exprs could be much more compact!
296     assert(CE->getNumOperands() > 0 && "ConstantExpr with 0 operands");
297     assert(CE->getNumOperands() != 1 || CE->isCast());
298     output_vbr(1+CE->getNumOperands());   // flags as an expr
299     output_vbr(CE->getOpcode());          // Put out the CE op code
300
301     for (User::const_op_iterator OI = CE->op_begin(); OI != CE->op_end(); ++OI){
302       int Slot = Table.getSlot(*OI);
303       assert(Slot != -1 && "Unknown constant used in ConstantExpr!!");
304       output_vbr((unsigned)Slot);
305       Slot = Table.getSlot((*OI)->getType());
306       output_typeid((unsigned)Slot);
307     }
308     if (CE->isCompare())
309       output_vbr((unsigned)CE->getPredicate());
310     return;
311   } else if (isa<UndefValue>(CPV)) {
312     output_vbr(1U);       // 1 -> UndefValue constant.
313     return;
314   } else {
315     output_vbr(0U);       // flag as not a ConstantExpr (i.e. 0 operands)
316   }
317
318   switch (CPV->getType()->getTypeID()) {
319   case Type::BoolTyID:    // Boolean Types
320     if (cast<ConstantBool>(CPV)->getValue())
321       output_vbr(1U);
322     else
323       output_vbr(0U);
324     break;
325
326   case Type::UByteTyID:   // Unsigned integer types...
327   case Type::UShortTyID:
328   case Type::UIntTyID:
329   case Type::ULongTyID:
330     output_vbr(cast<ConstantInt>(CPV)->getZExtValue());
331     break;
332
333   case Type::SByteTyID:   // Signed integer types...
334   case Type::ShortTyID:
335   case Type::IntTyID:
336   case Type::LongTyID:
337     output_vbr(cast<ConstantInt>(CPV)->getSExtValue());
338     break;
339
340   case Type::ArrayTyID: {
341     const ConstantArray *CPA = cast<ConstantArray>(CPV);
342     assert(!CPA->isString() && "Constant strings should be handled specially!");
343
344     for (unsigned i = 0, e = CPA->getNumOperands(); i != e; ++i) {
345       int Slot = Table.getSlot(CPA->getOperand(i));
346       assert(Slot != -1 && "Constant used but not available!!");
347       output_vbr((unsigned)Slot);
348     }
349     break;
350   }
351
352   case Type::PackedTyID: {
353     const ConstantPacked *CP = cast<ConstantPacked>(CPV);
354
355     for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i) {
356       int Slot = Table.getSlot(CP->getOperand(i));
357       assert(Slot != -1 && "Constant used but not available!!");
358       output_vbr((unsigned)Slot);
359     }
360     break;
361   }
362
363   case Type::StructTyID: {
364     const ConstantStruct *CPS = cast<ConstantStruct>(CPV);
365
366     for (unsigned i = 0, e = CPS->getNumOperands(); i != e; ++i) {
367       int Slot = Table.getSlot(CPS->getOperand(i));
368       assert(Slot != -1 && "Constant used but not available!!");
369       output_vbr((unsigned)Slot);
370     }
371     break;
372   }
373
374   case Type::PointerTyID:
375     assert(0 && "No non-null, non-constant-expr constants allowed!");
376     abort();
377
378   case Type::FloatTyID: {   // Floating point types...
379     float Tmp = (float)cast<ConstantFP>(CPV)->getValue();
380     output_float(Tmp);
381     break;
382   }
383   case Type::DoubleTyID: {
384     double Tmp = cast<ConstantFP>(CPV)->getValue();
385     output_double(Tmp);
386     break;
387   }
388
389   case Type::VoidTyID:
390   case Type::LabelTyID:
391   default:
392     cerr << __FILE__ << ":" << __LINE__ << ": Don't know how to serialize"
393          << " type '" << *CPV->getType() << "'\n";
394     break;
395   }
396   return;
397 }
398
399 /// outputInlineAsm - InlineAsm's get emitted to the constant pool, so they can
400 /// be shared by multiple uses.
401 void BytecodeWriter::outputInlineAsm(const InlineAsm *IA) {
402   // Output a marker, so we know when we have one one parsing the constant pool.
403   // Note that this encoding is 5 bytes: not very efficient for a marker.  Since
404   // unique inline asms are rare, this should hardly matter.
405   output_vbr(~0U);
406   
407   output(IA->getAsmString());
408   output(IA->getConstraintString());
409   output_vbr(unsigned(IA->hasSideEffects()));
410 }
411
412 void BytecodeWriter::outputConstantStrings() {
413   SlotCalculator::string_iterator I = Table.string_begin();
414   SlotCalculator::string_iterator E = Table.string_end();
415   if (I == E) return;  // No strings to emit
416
417   // If we have != 0 strings to emit, output them now.  Strings are emitted into
418   // the 'void' type plane.
419   output_vbr(unsigned(E-I));
420   output_typeid(Type::VoidTyID);
421
422   // Emit all of the strings.
423   for (I = Table.string_begin(); I != E; ++I) {
424     const ConstantArray *Str = *I;
425     int Slot = Table.getSlot(Str->getType());
426     assert(Slot != -1 && "Constant string of unknown type?");
427     output_typeid((unsigned)Slot);
428
429     // Now that we emitted the type (which indicates the size of the string),
430     // emit all of the characters.
431     std::string Val = Str->getAsString();
432     output_data(Val.c_str(), Val.c_str()+Val.size());
433   }
434 }
435
436 //===----------------------------------------------------------------------===//
437 //===                           Instruction Output                         ===//
438 //===----------------------------------------------------------------------===//
439
440 // outputInstructionFormat0 - Output those weird instructions that have a large
441 // number of operands or have large operands themselves.
442 //
443 // Format: [opcode] [type] [numargs] [arg0] [arg1] ... [arg<numargs-1>]
444 //
445 void BytecodeWriter::outputInstructionFormat0(const Instruction *I,
446                                               unsigned Opcode,
447                                               const SlotCalculator &Table,
448                                               unsigned Type) {
449   // Opcode must have top two bits clear...
450   output_vbr(Opcode << 2);                  // Instruction Opcode ID
451   output_typeid(Type);                      // Result type
452
453   unsigned NumArgs = I->getNumOperands();
454   output_vbr(NumArgs + (isa<CastInst>(I)  || isa<InvokeInst>(I) || 
455                         isa<CmpInst>(I) || isa<VAArgInst>(I) || Opcode == 58));
456
457   if (!isa<GetElementPtrInst>(&I)) {
458     for (unsigned i = 0; i < NumArgs; ++i) {
459       int Slot = Table.getSlot(I->getOperand(i));
460       assert(Slot >= 0 && "No slot number for value!?!?");
461       output_vbr((unsigned)Slot);
462     }
463
464     if (isa<CastInst>(I) || isa<VAArgInst>(I)) {
465       int Slot = Table.getSlot(I->getType());
466       assert(Slot != -1 && "Cast return type unknown?");
467       output_typeid((unsigned)Slot);
468     } else if (isa<CmpInst>(I)) {
469       output_vbr(unsigned(cast<CmpInst>(I)->getPredicate()));
470     } else if (isa<InvokeInst>(I)) {  
471       output_vbr(cast<InvokeInst>(I)->getCallingConv());
472     } else if (Opcode == 58) {  // Call escape sequence
473       output_vbr((cast<CallInst>(I)->getCallingConv() << 1) |
474                  unsigned(cast<CallInst>(I)->isTailCall()));
475     }
476   } else {
477     int Slot = Table.getSlot(I->getOperand(0));
478     assert(Slot >= 0 && "No slot number for value!?!?");
479     output_vbr(unsigned(Slot));
480
481     // We need to encode the type of sequential type indices into their slot #
482     unsigned Idx = 1;
483     for (gep_type_iterator TI = gep_type_begin(I), E = gep_type_end(I);
484          Idx != NumArgs; ++TI, ++Idx) {
485       Slot = Table.getSlot(I->getOperand(Idx));
486       assert(Slot >= 0 && "No slot number for value!?!?");
487
488       if (isa<SequentialType>(*TI)) {
489         unsigned IdxId;
490         switch (I->getOperand(Idx)->getType()->getTypeID()) {
491         default: assert(0 && "Unknown index type!");
492         case Type::UIntTyID:  IdxId = 0; break;
493         case Type::IntTyID:   IdxId = 1; break;
494         case Type::ULongTyID: IdxId = 2; break;
495         case Type::LongTyID:  IdxId = 3; break;
496         }
497         Slot = (Slot << 2) | IdxId;
498       }
499       output_vbr(unsigned(Slot));
500     }
501   }
502 }
503
504
505 // outputInstrVarArgsCall - Output the absurdly annoying varargs function calls.
506 // This are more annoying than most because the signature of the call does not
507 // tell us anything about the types of the arguments in the varargs portion.
508 // Because of this, we encode (as type 0) all of the argument types explicitly
509 // before the argument value.  This really sucks, but you shouldn't be using
510 // varargs functions in your code! *death to printf*!
511 //
512 // Format: [opcode] [type] [numargs] [arg0] [arg1] ... [arg<numargs-1>]
513 //
514 void BytecodeWriter::outputInstrVarArgsCall(const Instruction *I,
515                                             unsigned Opcode,
516                                             const SlotCalculator &Table,
517                                             unsigned Type) {
518   assert(isa<CallInst>(I) || isa<InvokeInst>(I));
519   // Opcode must have top two bits clear...
520   output_vbr(Opcode << 2);                  // Instruction Opcode ID
521   output_typeid(Type);                      // Result type (varargs type)
522
523   const PointerType *PTy = cast<PointerType>(I->getOperand(0)->getType());
524   const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
525   unsigned NumParams = FTy->getNumParams();
526
527   unsigned NumFixedOperands;
528   if (isa<CallInst>(I)) {
529     // Output an operand for the callee and each fixed argument, then two for
530     // each variable argument.
531     NumFixedOperands = 1+NumParams;
532   } else {
533     assert(isa<InvokeInst>(I) && "Not call or invoke??");
534     // Output an operand for the callee and destinations, then two for each
535     // variable argument.
536     NumFixedOperands = 3+NumParams;
537   }
538   output_vbr(2 * I->getNumOperands()-NumFixedOperands + 
539       unsigned(Opcode == 58 || isa<InvokeInst>(I)));
540
541   // The type for the function has already been emitted in the type field of the
542   // instruction.  Just emit the slot # now.
543   for (unsigned i = 0; i != NumFixedOperands; ++i) {
544     int Slot = Table.getSlot(I->getOperand(i));
545     assert(Slot >= 0 && "No slot number for value!?!?");
546     output_vbr((unsigned)Slot);
547   }
548
549   for (unsigned i = NumFixedOperands, e = I->getNumOperands(); i != e; ++i) {
550     // Output Arg Type ID
551     int Slot = Table.getSlot(I->getOperand(i)->getType());
552     assert(Slot >= 0 && "No slot number for value!?!?");
553     output_typeid((unsigned)Slot);
554
555     // Output arg ID itself
556     Slot = Table.getSlot(I->getOperand(i));
557     assert(Slot >= 0 && "No slot number for value!?!?");
558     output_vbr((unsigned)Slot);
559   }
560   
561   if (isa<InvokeInst>(I)) {
562     // Emit the tail call/calling conv for invoke instructions
563     output_vbr(cast<InvokeInst>(I)->getCallingConv());
564   } else if (Opcode == 58) {
565     const CallInst *CI = cast<CallInst>(I);
566     output_vbr((CI->getCallingConv() << 1) | unsigned(CI->isTailCall()));
567   }
568 }
569
570
571 // outputInstructionFormat1 - Output one operand instructions, knowing that no
572 // operand index is >= 2^12.
573 //
574 inline void BytecodeWriter::outputInstructionFormat1(const Instruction *I,
575                                                      unsigned Opcode,
576                                                      unsigned *Slots,
577                                                      unsigned Type) {
578   // bits   Instruction format:
579   // --------------------------
580   // 01-00: Opcode type, fixed to 1.
581   // 07-02: Opcode
582   // 19-08: Resulting type plane
583   // 31-20: Operand #1 (if set to (2^12-1), then zero operands)
584   //
585   output(1 | (Opcode << 2) | (Type << 8) | (Slots[0] << 20));
586 }
587
588
589 // outputInstructionFormat2 - Output two operand instructions, knowing that no
590 // operand index is >= 2^8.
591 //
592 inline void BytecodeWriter::outputInstructionFormat2(const Instruction *I,
593                                                      unsigned Opcode,
594                                                      unsigned *Slots,
595                                                      unsigned Type) {
596   // bits   Instruction format:
597   // --------------------------
598   // 01-00: Opcode type, fixed to 2.
599   // 07-02: Opcode
600   // 15-08: Resulting type plane
601   // 23-16: Operand #1
602   // 31-24: Operand #2
603   //
604   output(2 | (Opcode << 2) | (Type << 8) | (Slots[0] << 16) | (Slots[1] << 24));
605 }
606
607
608 // outputInstructionFormat3 - Output three operand instructions, knowing that no
609 // operand index is >= 2^6.
610 //
611 inline void BytecodeWriter::outputInstructionFormat3(const Instruction *I,
612                                                      unsigned Opcode,
613                                                      unsigned *Slots,
614                                                      unsigned Type) {
615   // bits   Instruction format:
616   // --------------------------
617   // 01-00: Opcode type, fixed to 3.
618   // 07-02: Opcode
619   // 13-08: Resulting type plane
620   // 19-14: Operand #1
621   // 25-20: Operand #2
622   // 31-26: Operand #3
623   //
624   output(3 | (Opcode << 2) | (Type << 8) |
625           (Slots[0] << 14) | (Slots[1] << 20) | (Slots[2] << 26));
626 }
627
628 void BytecodeWriter::outputInstruction(const Instruction &I) {
629   assert(I.getOpcode() < 57 && "Opcode too big???");
630   unsigned Opcode = I.getOpcode();
631   unsigned NumOperands = I.getNumOperands();
632
633   // Encode 'tail call' as 61, 'volatile load' as 62, and 'volatile store' as
634   // 63.
635   if (const CallInst *CI = dyn_cast<CallInst>(&I)) {
636     if (CI->getCallingConv() == CallingConv::C) {
637       if (CI->isTailCall())
638         Opcode = 61;   // CCC + Tail Call
639       else
640         ;     // Opcode = Instruction::Call
641     } else if (CI->getCallingConv() == CallingConv::Fast) {
642       if (CI->isTailCall())
643         Opcode = 59;    // FastCC + TailCall
644       else
645         Opcode = 60;    // FastCC + Not Tail Call
646     } else {
647       Opcode = 58;      // Call escape sequence.
648     }
649   } else if (isa<LoadInst>(I) && cast<LoadInst>(I).isVolatile()) {
650     Opcode = 62;
651   } else if (isa<StoreInst>(I) && cast<StoreInst>(I).isVolatile()) {
652     Opcode = 63;
653   }
654
655   // Figure out which type to encode with the instruction.  Typically we want
656   // the type of the first parameter, as opposed to the type of the instruction
657   // (for example, with setcc, we always know it returns bool, but the type of
658   // the first param is actually interesting).  But if we have no arguments
659   // we take the type of the instruction itself.
660   //
661   const Type *Ty;
662   switch (I.getOpcode()) {
663   case Instruction::Select:
664   case Instruction::Malloc:
665   case Instruction::Alloca:
666     Ty = I.getType();  // These ALWAYS want to encode the return type
667     break;
668   case Instruction::Store:
669     Ty = I.getOperand(1)->getType();  // Encode the pointer type...
670     assert(isa<PointerType>(Ty) && "Store to nonpointer type!?!?");
671     break;
672   default:              // Otherwise use the default behavior...
673     Ty = NumOperands ? I.getOperand(0)->getType() : I.getType();
674     break;
675   }
676
677   unsigned Type;
678   int Slot = Table.getSlot(Ty);
679   assert(Slot != -1 && "Type not available!!?!");
680   Type = (unsigned)Slot;
681
682   // Varargs calls and invokes are encoded entirely different from any other
683   // instructions.
684   if (const CallInst *CI = dyn_cast<CallInst>(&I)){
685     const PointerType *Ty =cast<PointerType>(CI->getCalledValue()->getType());
686     if (cast<FunctionType>(Ty->getElementType())->isVarArg()) {
687       outputInstrVarArgsCall(CI, Opcode, Table, Type);
688       return;
689     }
690   } else if (const InvokeInst *II = dyn_cast<InvokeInst>(&I)) {
691     const PointerType *Ty =cast<PointerType>(II->getCalledValue()->getType());
692     if (cast<FunctionType>(Ty->getElementType())->isVarArg()) {
693       outputInstrVarArgsCall(II, Opcode, Table, Type);
694       return;
695     }
696   }
697
698   if (NumOperands <= 3) {
699     // Make sure that we take the type number into consideration.  We don't want
700     // to overflow the field size for the instruction format we select.
701     //
702     unsigned MaxOpSlot = Type;
703     unsigned Slots[3]; Slots[0] = (1 << 12)-1;   // Marker to signify 0 operands
704
705     for (unsigned i = 0; i != NumOperands; ++i) {
706       int slot = Table.getSlot(I.getOperand(i));
707       assert(slot != -1 && "Broken bytecode!");
708       if (unsigned(slot) > MaxOpSlot) MaxOpSlot = unsigned(slot);
709       Slots[i] = unsigned(slot);
710     }
711
712     // Handle the special cases for various instructions...
713     if (isa<CastInst>(I) || isa<VAArgInst>(I)) {
714       // Cast has to encode the destination type as the second argument in the
715       // packet, or else we won't know what type to cast to!
716       Slots[1] = Table.getSlot(I.getType());
717       assert(Slots[1] != ~0U && "Cast return type unknown?");
718       if (Slots[1] > MaxOpSlot) MaxOpSlot = Slots[1];
719       NumOperands++;
720     } else if (const AllocationInst *AI = dyn_cast<AllocationInst>(&I)) {
721       assert(NumOperands == 1 && "Bogus allocation!");
722       if (AI->getAlignment()) {
723         Slots[1] = Log2_32(AI->getAlignment())+1;
724         if (Slots[1] > MaxOpSlot) MaxOpSlot = Slots[1];
725         NumOperands = 2;
726       }
727     } else if (isa<ICmpInst>(I) || isa<FCmpInst>(I)) {
728       // We need to encode the compare instruction's predicate as the third
729       // operand. Its not really a slot, but we don't want to break the 
730       // instruction format for these instructions.
731       NumOperands++;
732       assert(NumOperands == 3 && "CmpInst with wrong number of operands?");
733       Slots[2] = unsigned(cast<CmpInst>(&I)->getPredicate());
734       if (Slots[2] > MaxOpSlot)
735         MaxOpSlot = Slots[2];
736     } else if (const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(&I)) {
737       // We need to encode the type of sequential type indices into their slot #
738       unsigned Idx = 1;
739       for (gep_type_iterator I = gep_type_begin(GEP), E = gep_type_end(GEP);
740            I != E; ++I, ++Idx)
741         if (isa<SequentialType>(*I)) {
742           unsigned IdxId;
743           switch (GEP->getOperand(Idx)->getType()->getTypeID()) {
744           default: assert(0 && "Unknown index type!");
745           case Type::UIntTyID:  IdxId = 0; break;
746           case Type::IntTyID:   IdxId = 1; break;
747           case Type::ULongTyID: IdxId = 2; break;
748           case Type::LongTyID:  IdxId = 3; break;
749           }
750           Slots[Idx] = (Slots[Idx] << 2) | IdxId;
751           if (Slots[Idx] > MaxOpSlot) MaxOpSlot = Slots[Idx];
752         }
753     } else if (Opcode == 58) {
754       // If this is the escape sequence for call, emit the tailcall/cc info.
755       const CallInst &CI = cast<CallInst>(I);
756       ++NumOperands;
757       if (NumOperands <= 3) {
758         Slots[NumOperands-1] =
759           (CI.getCallingConv() << 1)|unsigned(CI.isTailCall());
760         if (Slots[NumOperands-1] > MaxOpSlot)
761           MaxOpSlot = Slots[NumOperands-1];
762       }
763     } else if (isa<InvokeInst>(I)) {
764       // Invoke escape seq has at least 4 operands to encode.
765       ++NumOperands;
766     }
767
768     // Decide which instruction encoding to use.  This is determined primarily
769     // by the number of operands, and secondarily by whether or not the max
770     // operand will fit into the instruction encoding.  More operands == fewer
771     // bits per operand.
772     //
773     switch (NumOperands) {
774     case 0:
775     case 1:
776       if (MaxOpSlot < (1 << 12)-1) { // -1 because we use 4095 to indicate 0 ops
777         outputInstructionFormat1(&I, Opcode, Slots, Type);
778         return;
779       }
780       break;
781
782     case 2:
783       if (MaxOpSlot < (1 << 8)) {
784         outputInstructionFormat2(&I, Opcode, Slots, Type);
785         return;
786       }
787       break;
788
789     case 3:
790       if (MaxOpSlot < (1 << 6)) {
791         outputInstructionFormat3(&I, Opcode, Slots, Type);
792         return;
793       }
794       break;
795     default:
796       break;
797     }
798   }
799
800   // If we weren't handled before here, we either have a large number of
801   // operands or a large operand index that we are referring to.
802   outputInstructionFormat0(&I, Opcode, Table, Type);
803 }
804
805 //===----------------------------------------------------------------------===//
806 //===                              Block Output                            ===//
807 //===----------------------------------------------------------------------===//
808
809 BytecodeWriter::BytecodeWriter(std::vector<unsigned char> &o, const Module *M)
810   : Out(o), Table(M) {
811
812   // Emit the signature...
813   static const unsigned char *Sig = (const unsigned char*)"llvm";
814   output_data(Sig, Sig+4);
815
816   // Emit the top level CLASS block.
817   BytecodeBlock ModuleBlock(BytecodeFormat::ModuleBlockID, *this, false, true);
818
819   bool isBigEndian      = M->getEndianness() == Module::BigEndian;
820   bool hasLongPointers  = M->getPointerSize() == Module::Pointer64;
821   bool hasNoEndianness  = M->getEndianness() == Module::AnyEndianness;
822   bool hasNoPointerSize = M->getPointerSize() == Module::AnyPointerSize;
823
824   // Output the version identifier and other information.
825   unsigned Version = (BCVersionNum << 4) |
826                      (unsigned)isBigEndian | (hasLongPointers << 1) |
827                      (hasNoEndianness << 2) |
828                      (hasNoPointerSize << 3);
829   output_vbr(Version);
830
831   // The Global type plane comes first
832   {
833     BytecodeBlock CPool(BytecodeFormat::GlobalTypePlaneBlockID, *this);
834     outputTypes(Type::FirstDerivedTyID);
835   }
836
837   // The ModuleInfoBlock follows directly after the type information
838   outputModuleInfoBlock(M);
839
840   // Output module level constants, used for global variable initializers
841   outputConstants(false);
842
843   // Do the whole module now! Process each function at a time...
844   for (Module::const_iterator I = M->begin(), E = M->end(); I != E; ++I)
845     outputFunction(I);
846
847   // If needed, output the symbol table for the module...
848   outputSymbolTable(M->getSymbolTable());
849 }
850
851 void BytecodeWriter::outputTypes(unsigned TypeNum) {
852   // Write the type plane for types first because earlier planes (e.g. for a
853   // primitive type like float) may have constants constructed using types
854   // coming later (e.g., via getelementptr from a pointer type).  The type
855   // plane is needed before types can be fwd or bkwd referenced.
856   const std::vector<const Type*>& Types = Table.getTypes();
857   assert(!Types.empty() && "No types at all?");
858   assert(TypeNum <= Types.size() && "Invalid TypeNo index");
859
860   unsigned NumEntries = Types.size() - TypeNum;
861
862   // Output type header: [num entries]
863   output_vbr(NumEntries);
864
865   for (unsigned i = TypeNum; i < TypeNum+NumEntries; ++i)
866     outputType(Types[i]);
867 }
868
869 // Helper function for outputConstants().
870 // Writes out all the constants in the plane Plane starting at entry StartNo.
871 //
872 void BytecodeWriter::outputConstantsInPlane(const std::vector<const Value*>
873                                             &Plane, unsigned StartNo) {
874   unsigned ValNo = StartNo;
875
876   // Scan through and ignore function arguments, global values, and constant
877   // strings.
878   for (; ValNo < Plane.size() &&
879          (isa<Argument>(Plane[ValNo]) || isa<GlobalValue>(Plane[ValNo]) ||
880           (isa<ConstantArray>(Plane[ValNo]) &&
881            cast<ConstantArray>(Plane[ValNo])->isString())); ValNo++)
882     /*empty*/;
883
884   unsigned NC = ValNo;              // Number of constants
885   for (; NC < Plane.size() && (isa<Constant>(Plane[NC]) || 
886                                isa<InlineAsm>(Plane[NC])); NC++)
887     /*empty*/;
888   NC -= ValNo;                      // Convert from index into count
889   if (NC == 0) return;              // Skip empty type planes...
890
891   // FIXME: Most slabs only have 1 or 2 entries!  We should encode this much
892   // more compactly.
893
894   // Put out type header: [num entries][type id number]
895   //
896   output_vbr(NC);
897
898   // Put out the Type ID Number...
899   int Slot = Table.getSlot(Plane.front()->getType());
900   assert (Slot != -1 && "Type in constant pool but not in function!!");
901   output_typeid((unsigned)Slot);
902
903   for (unsigned i = ValNo; i < ValNo+NC; ++i) {
904     const Value *V = Plane[i];
905     if (const Constant *C = dyn_cast<Constant>(V))
906       outputConstant(C);
907     else
908       outputInlineAsm(cast<InlineAsm>(V));
909   }
910 }
911
912 static inline bool hasNullValue(const Type *Ty) {
913   return Ty != Type::LabelTy && Ty != Type::VoidTy && !isa<OpaqueType>(Ty);
914 }
915
916 void BytecodeWriter::outputConstants(bool isFunction) {
917   BytecodeBlock CPool(BytecodeFormat::ConstantPoolBlockID, *this,
918                       true  /* Elide block if empty */);
919
920   unsigned NumPlanes = Table.getNumPlanes();
921
922   if (isFunction)
923     // Output the type plane before any constants!
924     outputTypes(Table.getModuleTypeLevel());
925   else
926     // Output module-level string constants before any other constants.
927     outputConstantStrings();
928
929   for (unsigned pno = 0; pno != NumPlanes; pno++) {
930     const std::vector<const Value*> &Plane = Table.getPlane(pno);
931     if (!Plane.empty()) {              // Skip empty type planes...
932       unsigned ValNo = 0;
933       if (isFunction)                  // Don't re-emit module constants
934         ValNo += Table.getModuleLevel(pno);
935
936       if (hasNullValue(Plane[0]->getType())) {
937         // Skip zero initializer
938         if (ValNo == 0)
939           ValNo = 1;
940       }
941
942       // Write out constants in the plane
943       outputConstantsInPlane(Plane, ValNo);
944     }
945   }
946 }
947
948 static unsigned getEncodedLinkage(const GlobalValue *GV) {
949   switch (GV->getLinkage()) {
950   default: assert(0 && "Invalid linkage!");
951   case GlobalValue::ExternalLinkage:     return 0;
952   case GlobalValue::WeakLinkage:         return 1;
953   case GlobalValue::AppendingLinkage:    return 2;
954   case GlobalValue::InternalLinkage:     return 3;
955   case GlobalValue::LinkOnceLinkage:     return 4;
956   case GlobalValue::DLLImportLinkage:    return 5;
957   case GlobalValue::DLLExportLinkage:    return 6;
958   case GlobalValue::ExternalWeakLinkage: return 7;
959   }
960 }
961
962 void BytecodeWriter::outputModuleInfoBlock(const Module *M) {
963   BytecodeBlock ModuleInfoBlock(BytecodeFormat::ModuleGlobalInfoBlockID, *this);
964
965   // Give numbers to sections as we encounter them.
966   unsigned SectionIDCounter = 0;
967   std::vector<std::string> SectionNames;
968   std::map<std::string, unsigned> SectionID;
969   
970   // Output the types for the global variables in the module...
971   for (Module::const_global_iterator I = M->global_begin(),
972          End = M->global_end(); I != End; ++I) {
973     int Slot = Table.getSlot(I->getType());
974     assert(Slot != -1 && "Module global vars is broken!");
975
976     assert((I->hasInitializer() || !I->hasInternalLinkage()) &&
977            "Global must have an initializer or have external linkage!");
978     
979     // Fields: bit0 = isConstant, bit1 = hasInitializer, bit2-4=Linkage,
980     // bit5+ = Slot # for type.
981     bool HasExtensionWord = (I->getAlignment() != 0) || I->hasSection();
982     
983     // If we need to use the extension byte, set linkage=3(internal) and
984     // initializer = 0 (impossible!).
985     if (!HasExtensionWord) {
986       unsigned oSlot = ((unsigned)Slot << 5) | (getEncodedLinkage(I) << 2) |
987                         (I->hasInitializer() << 1) | (unsigned)I->isConstant();
988       output_vbr(oSlot);
989     } else {  
990       unsigned oSlot = ((unsigned)Slot << 5) | (3 << 2) |
991                         (0 << 1) | (unsigned)I->isConstant();
992       output_vbr(oSlot);
993       
994       // The extension word has this format: bit 0 = has initializer, bit 1-3 =
995       // linkage, bit 4-8 = alignment (log2), bit 9 = has SectionID, 
996       // bits 10+ = future use.
997       unsigned ExtWord = (unsigned)I->hasInitializer() |
998                          (getEncodedLinkage(I) << 1) |
999                          ((Log2_32(I->getAlignment())+1) << 4) |
1000                          ((unsigned)I->hasSection() << 9);
1001       output_vbr(ExtWord);
1002       if (I->hasSection()) {
1003         // Give section names unique ID's.
1004         unsigned &Entry = SectionID[I->getSection()];
1005         if (Entry == 0) {
1006           Entry = ++SectionIDCounter;
1007           SectionNames.push_back(I->getSection());
1008         }
1009         output_vbr(Entry);
1010       }
1011     }
1012
1013     // If we have an initializer, output it now.
1014     if (I->hasInitializer()) {
1015       Slot = Table.getSlot((Value*)I->getInitializer());
1016       assert(Slot != -1 && "No slot for global var initializer!");
1017       output_vbr((unsigned)Slot);
1018     }
1019   }
1020   output_typeid((unsigned)Table.getSlot(Type::VoidTy));
1021
1022   // Output the types of the functions in this module.
1023   for (Module::const_iterator I = M->begin(), End = M->end(); I != End; ++I) {
1024     int Slot = Table.getSlot(I->getType());
1025     assert(Slot != -1 && "Module slot calculator is broken!");
1026     assert(Slot >= Type::FirstDerivedTyID && "Derived type not in range!");
1027     assert(((Slot << 6) >> 6) == Slot && "Slot # too big!");
1028     unsigned CC = I->getCallingConv()+1;
1029     unsigned ID = (Slot << 5) | (CC & 15);
1030
1031     if (I->isExternal())   // If external, we don't have an FunctionInfo block.
1032       ID |= 1 << 4;
1033     
1034     if (I->getAlignment() || I->hasSection() || (CC & ~15) != 0 ||
1035         (I->isExternal() && I->hasDLLImportLinkage()) ||
1036         (I->isExternal() && I->hasExternalWeakLinkage())
1037        )
1038       ID |= 1 << 31;       // Do we need an extension word?
1039     
1040     output_vbr(ID);
1041     
1042     if (ID & (1 << 31)) {
1043       // Extension byte: bits 0-4 = alignment, bits 5-9 = top nibble of calling
1044       // convention, bit 10 = hasSectionID., bits 11-12 = external linkage type
1045       unsigned extLinkage = 0;
1046
1047       if (I->isExternal()) {
1048         if (I->hasDLLImportLinkage()) {
1049           extLinkage = 1;
1050         } else if (I->hasExternalWeakLinkage()) {
1051           extLinkage = 2;
1052         }
1053       }
1054
1055       ID = (Log2_32(I->getAlignment())+1) | ((CC >> 4) << 5) | 
1056         (I->hasSection() << 10) |
1057         ((extLinkage & 3) << 11);
1058       output_vbr(ID);
1059       
1060       // Give section names unique ID's.
1061       if (I->hasSection()) {
1062         unsigned &Entry = SectionID[I->getSection()];
1063         if (Entry == 0) {
1064           Entry = ++SectionIDCounter;
1065           SectionNames.push_back(I->getSection());
1066         }
1067         output_vbr(Entry);
1068       }
1069     }
1070   }
1071   output_vbr((unsigned)Table.getSlot(Type::VoidTy) << 5);
1072
1073   // Emit the list of dependent libraries for the Module.
1074   Module::lib_iterator LI = M->lib_begin();
1075   Module::lib_iterator LE = M->lib_end();
1076   output_vbr(unsigned(LE - LI));   // Emit the number of dependent libraries.
1077   for (; LI != LE; ++LI)
1078     output(*LI);
1079
1080   // Output the target triple from the module
1081   output(M->getTargetTriple());
1082   
1083   // Emit the table of section names.
1084   output_vbr((unsigned)SectionNames.size());
1085   for (unsigned i = 0, e = SectionNames.size(); i != e; ++i)
1086     output(SectionNames[i]);
1087   
1088   // Output the inline asm string.
1089   output(M->getModuleInlineAsm());
1090 }
1091
1092 void BytecodeWriter::outputInstructions(const Function *F) {
1093   BytecodeBlock ILBlock(BytecodeFormat::InstructionListBlockID, *this);
1094   for (Function::const_iterator BB = F->begin(), E = F->end(); BB != E; ++BB)
1095     for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I!=E; ++I)
1096       outputInstruction(*I);
1097 }
1098
1099 void BytecodeWriter::outputFunction(const Function *F) {
1100   // If this is an external function, there is nothing else to emit!
1101   if (F->isExternal()) return;
1102
1103   BytecodeBlock FunctionBlock(BytecodeFormat::FunctionBlockID, *this);
1104   output_vbr(getEncodedLinkage(F));
1105
1106   // Get slot information about the function...
1107   Table.incorporateFunction(F);
1108
1109   if (Table.getCompactionTable().empty()) {
1110     // Output information about the constants in the function if the compaction
1111     // table is not being used.
1112     outputConstants(true);
1113   } else {
1114     // Otherwise, emit the compaction table.
1115     outputCompactionTable();
1116   }
1117
1118   // Output all of the instructions in the body of the function
1119   outputInstructions(F);
1120
1121   // If needed, output the symbol table for the function...
1122   outputSymbolTable(F->getSymbolTable());
1123
1124   Table.purgeFunction();
1125 }
1126
1127 void BytecodeWriter::outputCompactionTablePlane(unsigned PlaneNo,
1128                                          const std::vector<const Value*> &Plane,
1129                                                 unsigned StartNo) {
1130   unsigned End = Table.getModuleLevel(PlaneNo);
1131   if (Plane.empty() || StartNo == End || End == 0) return;   // Nothing to emit
1132   assert(StartNo < End && "Cannot emit negative range!");
1133   assert(StartNo < Plane.size() && End <= Plane.size());
1134
1135   // Do not emit the null initializer!
1136   ++StartNo;
1137
1138   // Figure out which encoding to use.  By far the most common case we have is
1139   // to emit 0-2 entries in a compaction table plane.
1140   switch (End-StartNo) {
1141   case 0:         // Avoid emitting two vbr's if possible.
1142   case 1:
1143   case 2:
1144     output_vbr((PlaneNo << 2) | End-StartNo);
1145     break;
1146   default:
1147     // Output the number of things.
1148     output_vbr((unsigned(End-StartNo) << 2) | 3);
1149     output_typeid(PlaneNo);                 // Emit the type plane this is
1150     break;
1151   }
1152
1153   for (unsigned i = StartNo; i != End; ++i)
1154     output_vbr(Table.getGlobalSlot(Plane[i]));
1155 }
1156
1157 void BytecodeWriter::outputCompactionTypes(unsigned StartNo) {
1158   // Get the compaction type table from the slot calculator
1159   const std::vector<const Type*> &CTypes = Table.getCompactionTypes();
1160
1161   // The compaction types may have been uncompactified back to the
1162   // global types. If so, we just write an empty table
1163   if (CTypes.size() == 0) {
1164     output_vbr(0U);
1165     return;
1166   }
1167
1168   assert(CTypes.size() >= StartNo && "Invalid compaction types start index");
1169
1170   // Determine how many types to write
1171   unsigned NumTypes = CTypes.size() - StartNo;
1172
1173   // Output the number of types.
1174   output_vbr(NumTypes);
1175
1176   for (unsigned i = StartNo; i < StartNo+NumTypes; ++i)
1177     output_typeid(Table.getGlobalSlot(CTypes[i]));
1178 }
1179
1180 void BytecodeWriter::outputCompactionTable() {
1181   // Avoid writing the compaction table at all if there is no content.
1182   if (Table.getCompactionTypes().size() >= Type::FirstDerivedTyID ||
1183       (!Table.CompactionTableIsEmpty())) {
1184     BytecodeBlock CTB(BytecodeFormat::CompactionTableBlockID, *this,
1185                       true/*ElideIfEmpty*/);
1186     const std::vector<std::vector<const Value*> > &CT =
1187       Table.getCompactionTable();
1188
1189     // First things first, emit the type compaction table if there is one.
1190     outputCompactionTypes(Type::FirstDerivedTyID);
1191
1192     for (unsigned i = 0, e = CT.size(); i != e; ++i)
1193       outputCompactionTablePlane(i, CT[i], 0);
1194   }
1195 }
1196
1197 void BytecodeWriter::outputSymbolTable(const SymbolTable &MST) {
1198   // Do not output the Bytecode block for an empty symbol table, it just wastes
1199   // space!
1200   if (MST.isEmpty()) return;
1201
1202   BytecodeBlock SymTabBlock(BytecodeFormat::SymbolTableBlockID, *this,
1203                             true/*ElideIfEmpty*/);
1204
1205   // Write the number of types
1206   output_vbr(MST.num_types());
1207
1208   // Write each of the types
1209   for (SymbolTable::type_const_iterator TI = MST.type_begin(),
1210        TE = MST.type_end(); TI != TE; ++TI) {
1211     // Symtab entry:[def slot #][name]
1212     output_typeid((unsigned)Table.getSlot(TI->second));
1213     output(TI->first);
1214   }
1215
1216   // Now do each of the type planes in order.
1217   for (SymbolTable::plane_const_iterator PI = MST.plane_begin(),
1218        PE = MST.plane_end(); PI != PE;  ++PI) {
1219     SymbolTable::value_const_iterator I = MST.value_begin(PI->first);
1220     SymbolTable::value_const_iterator End = MST.value_end(PI->first);
1221     int Slot;
1222
1223     if (I == End) continue;  // Don't mess with an absent type...
1224
1225     // Write the number of values in this plane
1226     output_vbr((unsigned)PI->second.size());
1227
1228     // Write the slot number of the type for this plane
1229     Slot = Table.getSlot(PI->first);
1230     assert(Slot != -1 && "Type in symtab, but not in table!");
1231     output_typeid((unsigned)Slot);
1232
1233     // Write each of the values in this plane
1234     for (; I != End; ++I) {
1235       // Symtab entry: [def slot #][name]
1236       Slot = Table.getSlot(I->second);
1237       assert(Slot != -1 && "Value in symtab but has no slot number!!");
1238       output_vbr((unsigned)Slot);
1239       output(I->first);
1240     }
1241   }
1242 }
1243
1244 void llvm::WriteBytecodeToFile(const Module *M, OStream &Out,
1245                                bool compress) {
1246   assert(M && "You can't write a null module!!");
1247
1248   // Make sure that std::cout is put into binary mode for systems
1249   // that care.
1250   if (Out == cout)
1251     sys::Program::ChangeStdoutToBinary();
1252
1253   // Create a vector of unsigned char for the bytecode output. We
1254   // reserve 256KBytes of space in the vector so that we avoid doing
1255   // lots of little allocations. 256KBytes is sufficient for a large
1256   // proportion of the bytecode files we will encounter. Larger files
1257   // will be automatically doubled in size as needed (std::vector
1258   // behavior).
1259   std::vector<unsigned char> Buffer;
1260   Buffer.reserve(256 * 1024);
1261
1262   // The BytecodeWriter populates Buffer for us.
1263   BytecodeWriter BCW(Buffer, M);
1264
1265   // Keep track of how much we've written
1266   BytesWritten += Buffer.size();
1267
1268   // Determine start and end points of the Buffer
1269   const unsigned char *FirstByte = &Buffer.front();
1270
1271   // If we're supposed to compress this mess ...
1272   if (compress) {
1273
1274     // We signal compression by using an alternate magic number for the
1275     // file. The compressed bytecode file's magic number is "llvc" instead
1276     // of "llvm".
1277     char compressed_magic[4];
1278     compressed_magic[0] = 'l';
1279     compressed_magic[1] = 'l';
1280     compressed_magic[2] = 'v';
1281     compressed_magic[3] = 'c';
1282
1283     Out.stream()->write(compressed_magic,4);
1284
1285     // Compress everything after the magic number (which we altered)
1286     Compressor::compressToStream(
1287       (char*)(FirstByte+4),        // Skip the magic number
1288       Buffer.size()-4,             // Skip the magic number
1289       *Out.stream()                // Where to write compressed data
1290     );
1291
1292   } else {
1293
1294     // We're not compressing, so just write the entire block.
1295     Out.stream()->write((char*)FirstByte, Buffer.size());
1296   }
1297
1298   // make sure it hits disk now
1299   Out.stream()->flush();
1300 }