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