blob: c82665e9478ff6e545384280a0da752ba6160d78 [file] [log] [blame]
Chris Lattner14999342004-01-10 19:07:06 +00001//===-- Writer.cpp - Library for writing LLVM bytecode files --------------===//
Misha Brukman23c6d2c2005-04-21 21:48:46 +00002//
John Criswellb576c942003-10-20 19:43:21 +00003// 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.
Misha Brukman23c6d2c2005-04-21 21:48:46 +00007//
John Criswellb576c942003-10-20 19:43:21 +00008//===----------------------------------------------------------------------===//
Chris Lattner00950542001-06-06 20:29:01 +00009//
10// This library implements the functionality defined in llvm/Bytecode/Writer.h
11//
Chris Lattner00950542001-06-06 20:29:01 +000012// Note that this file uses an unusual technique of outputting all the bytecode
Reid Spencerad89bd62004-07-25 18:07:36 +000013// to a vector of unsigned char, then copies the vector to an ostream. The
Chris Lattner00950542001-06-06 20:29:01 +000014// 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//
Chris Lattner00950542001-06-06 20:29:01 +000018//===----------------------------------------------------------------------===//
19
20#include "WriterInternals.h"
Chris Lattner635cd932002-07-23 19:56:44 +000021#include "llvm/Bytecode/WriteBytecodePass.h"
Chris Lattnerdee199f2005-05-06 22:34:01 +000022#include "llvm/CallingConv.h"
Chris Lattner83bb3d22004-01-14 23:36:54 +000023#include "llvm/Constants.h"
24#include "llvm/DerivedTypes.h"
Reid Spencerad89bd62004-07-25 18:07:36 +000025#include "llvm/Instructions.h"
Chris Lattner00950542001-06-06 20:29:01 +000026#include "llvm/Module.h"
Chris Lattner00950542001-06-06 20:29:01 +000027#include "llvm/SymbolTable.h"
Reid Spencerad89bd62004-07-25 18:07:36 +000028#include "llvm/Support/GetElementPtrTypeIterator.h"
Reid Spencer17f52c52004-11-06 23:17:23 +000029#include "llvm/Support/Compressor.h"
Jim Laskeycb6682f2005-08-17 19:34:49 +000030#include "llvm/Support/MathExtras.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000031#include "llvm/ADT/STLExtras.h"
32#include "llvm/ADT/Statistic.h"
Chris Lattner32abce62004-01-10 19:10:01 +000033#include <cstring>
Chris Lattner00950542001-06-06 20:29:01 +000034#include <algorithm>
Chris Lattner44f549b2004-01-10 18:49:43 +000035using namespace llvm;
Brian Gaeked0fde302003-11-11 22:41:34 +000036
Reid Spencer38d54be2004-08-17 07:45:14 +000037/// This value needs to be incremented every time the bytecode format changes
38/// so that the reader can distinguish which format of the bytecode file has
39/// been written.
40/// @brief The bytecode version number
Chris Lattnera79e7cc2004-10-16 18:18:16 +000041const unsigned BCVersionNum = 5;
Reid Spencer38d54be2004-08-17 07:45:14 +000042
Chris Lattner635cd932002-07-23 19:56:44 +000043static RegisterPass<WriteBytecodePass> X("emitbytecode", "Bytecode Writer");
44
Misha Brukman23c6d2c2005-04-21 21:48:46 +000045static Statistic<>
Chris Lattnera92f6962002-10-01 22:38:41 +000046BytesWritten("bytecodewriter", "Number of bytecode bytes written");
Chris Lattner635cd932002-07-23 19:56:44 +000047
Reid Spencerad89bd62004-07-25 18:07:36 +000048//===----------------------------------------------------------------------===//
49//=== Output Primitives ===//
50//===----------------------------------------------------------------------===//
51
52// output - If a position is specified, it must be in the valid portion of the
Misha Brukman23c6d2c2005-04-21 21:48:46 +000053// string... note that this should be inlined always so only the relevant IF
Reid Spencerad89bd62004-07-25 18:07:36 +000054// body should be included.
55inline void BytecodeWriter::output(unsigned i, int pos) {
56 if (pos == -1) { // Be endian clean, little endian is our friend
Misha Brukman23c6d2c2005-04-21 21:48:46 +000057 Out.push_back((unsigned char)i);
Reid Spencerad89bd62004-07-25 18:07:36 +000058 Out.push_back((unsigned char)(i >> 8));
59 Out.push_back((unsigned char)(i >> 16));
60 Out.push_back((unsigned char)(i >> 24));
61 } else {
62 Out[pos ] = (unsigned char)i;
63 Out[pos+1] = (unsigned char)(i >> 8);
64 Out[pos+2] = (unsigned char)(i >> 16);
65 Out[pos+3] = (unsigned char)(i >> 24);
66 }
67}
68
69inline void BytecodeWriter::output(int i) {
70 output((unsigned)i);
71}
72
73/// output_vbr - Output an unsigned value, by using the least number of bytes
74/// possible. This is useful because many of our "infinite" values are really
75/// very small most of the time; but can be large a few times.
Misha Brukman23c6d2c2005-04-21 21:48:46 +000076/// Data format used: If you read a byte with the high bit set, use the low
77/// seven bits as data and then read another byte.
Reid Spencerad89bd62004-07-25 18:07:36 +000078inline void BytecodeWriter::output_vbr(uint64_t i) {
79 while (1) {
80 if (i < 0x80) { // done?
81 Out.push_back((unsigned char)i); // We know the high bit is clear...
82 return;
83 }
Misha Brukman23c6d2c2005-04-21 21:48:46 +000084
Reid Spencerad89bd62004-07-25 18:07:36 +000085 // Nope, we are bigger than a character, output the next 7 bits and set the
86 // high bit to say that there is more coming...
87 Out.push_back(0x80 | ((unsigned char)i & 0x7F));
88 i >>= 7; // Shift out 7 bits now...
89 }
90}
91
92inline void BytecodeWriter::output_vbr(unsigned i) {
93 while (1) {
94 if (i < 0x80) { // done?
95 Out.push_back((unsigned char)i); // We know the high bit is clear...
96 return;
97 }
Misha Brukman23c6d2c2005-04-21 21:48:46 +000098
Reid Spencerad89bd62004-07-25 18:07:36 +000099 // Nope, we are bigger than a character, output the next 7 bits and set the
100 // high bit to say that there is more coming...
101 Out.push_back(0x80 | ((unsigned char)i & 0x7F));
102 i >>= 7; // Shift out 7 bits now...
103 }
104}
105
106inline void BytecodeWriter::output_typeid(unsigned i) {
107 if (i <= 0x00FFFFFF)
108 this->output_vbr(i);
109 else {
110 this->output_vbr(0x00FFFFFF);
111 this->output_vbr(i);
112 }
113}
114
115inline void BytecodeWriter::output_vbr(int64_t i) {
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000116 if (i < 0)
Reid Spencerad89bd62004-07-25 18:07:36 +0000117 output_vbr(((uint64_t)(-i) << 1) | 1); // Set low order sign bit...
118 else
119 output_vbr((uint64_t)i << 1); // Low order bit is clear.
120}
121
122
123inline void BytecodeWriter::output_vbr(int i) {
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000124 if (i < 0)
Reid Spencerad89bd62004-07-25 18:07:36 +0000125 output_vbr(((unsigned)(-i) << 1) | 1); // Set low order sign bit...
126 else
127 output_vbr((unsigned)i << 1); // Low order bit is clear.
128}
129
Reid Spencer38d54be2004-08-17 07:45:14 +0000130inline void BytecodeWriter::output(const std::string &s) {
Reid Spencerad89bd62004-07-25 18:07:36 +0000131 unsigned Len = s.length();
132 output_vbr(Len ); // Strings may have an arbitrary length...
133 Out.insert(Out.end(), s.begin(), s.end());
Reid Spencerad89bd62004-07-25 18:07:36 +0000134}
135
136inline void BytecodeWriter::output_data(const void *Ptr, const void *End) {
137 Out.insert(Out.end(), (const unsigned char*)Ptr, (const unsigned char*)End);
138}
139
140inline void BytecodeWriter::output_float(float& FloatVal) {
141 /// FIXME: This isn't optimal, it has size problems on some platforms
142 /// where FP is not IEEE.
Jim Laskeycb6682f2005-08-17 19:34:49 +0000143 uint32_t i = FloatToBits(FloatVal);
144 Out.push_back( static_cast<unsigned char>( (i & 0xFF )));
145 Out.push_back( static_cast<unsigned char>( (i >> 8) & 0xFF));
146 Out.push_back( static_cast<unsigned char>( (i >> 16) & 0xFF));
147 Out.push_back( static_cast<unsigned char>( (i >> 24) & 0xFF));
Reid Spencerad89bd62004-07-25 18:07:36 +0000148}
149
150inline void BytecodeWriter::output_double(double& DoubleVal) {
151 /// FIXME: This isn't optimal, it has size problems on some platforms
152 /// where FP is not IEEE.
Jim Laskeycb6682f2005-08-17 19:34:49 +0000153 uint64_t i = DoubleToBits(DoubleVal);
154 Out.push_back( static_cast<unsigned char>( (i & 0xFF )));
155 Out.push_back( static_cast<unsigned char>( (i >> 8) & 0xFF));
156 Out.push_back( static_cast<unsigned char>( (i >> 16) & 0xFF));
157 Out.push_back( static_cast<unsigned char>( (i >> 24) & 0xFF));
158 Out.push_back( static_cast<unsigned char>( (i >> 32) & 0xFF));
159 Out.push_back( static_cast<unsigned char>( (i >> 40) & 0xFF));
160 Out.push_back( static_cast<unsigned char>( (i >> 48) & 0xFF));
161 Out.push_back( static_cast<unsigned char>( (i >> 56) & 0xFF));
Reid Spencerad89bd62004-07-25 18:07:36 +0000162}
163
Chris Lattnerc76ea432005-11-12 18:34:09 +0000164inline BytecodeBlock::BytecodeBlock(unsigned ID, BytecodeWriter &w,
165 bool elideIfEmpty, bool hasLongFormat)
Reid Spencerad89bd62004-07-25 18:07:36 +0000166 : Id(ID), Writer(w), ElideIfEmpty(elideIfEmpty), HasLongFormat(hasLongFormat){
167
168 if (HasLongFormat) {
169 w.output(ID);
170 w.output(0U); // For length in long format
171 } else {
172 w.output(0U); /// Place holder for ID and length for this block
173 }
174 Loc = w.size();
175}
176
Chris Lattnerb0bf6642004-10-14 01:35:17 +0000177inline BytecodeBlock::~BytecodeBlock() { // Do backpatch when block goes out
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000178 // of scope...
Reid Spencerad89bd62004-07-25 18:07:36 +0000179 if (Loc == Writer.size() && ElideIfEmpty) {
180 // If the block is empty, and we are allowed to, do not emit the block at
181 // all!
182 Writer.resize(Writer.size()-(HasLongFormat?8:4));
183 return;
184 }
185
Reid Spencerad89bd62004-07-25 18:07:36 +0000186 if (HasLongFormat)
187 Writer.output(unsigned(Writer.size()-Loc), int(Loc-4));
188 else
189 Writer.output(unsigned(Writer.size()-Loc) << 5 | (Id & 0x1F), int(Loc-4));
Reid Spencerad89bd62004-07-25 18:07:36 +0000190}
191
192//===----------------------------------------------------------------------===//
193//=== Constant Output ===//
194//===----------------------------------------------------------------------===//
195
196void BytecodeWriter::outputType(const Type *T) {
197 output_vbr((unsigned)T->getTypeID());
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000198
Reid Spencerad89bd62004-07-25 18:07:36 +0000199 // That's all there is to handling primitive types...
200 if (T->isPrimitiveType()) {
201 return; // We might do this if we alias a prim type: %x = type int
202 }
203
204 switch (T->getTypeID()) { // Handle derived types now.
205 case Type::FunctionTyID: {
206 const FunctionType *MT = cast<FunctionType>(T);
207 int Slot = Table.getSlot(MT->getReturnType());
208 assert(Slot != -1 && "Type used but not available!!");
209 output_typeid((unsigned)Slot);
210
211 // Output the number of arguments to function (+1 if varargs):
212 output_vbr((unsigned)MT->getNumParams()+MT->isVarArg());
213
214 // Output all of the arguments...
215 FunctionType::param_iterator I = MT->param_begin();
216 for (; I != MT->param_end(); ++I) {
217 Slot = Table.getSlot(*I);
218 assert(Slot != -1 && "Type used but not available!!");
219 output_typeid((unsigned)Slot);
220 }
221
222 // Terminate list with VoidTy if we are a varargs function...
223 if (MT->isVarArg())
224 output_typeid((unsigned)Type::VoidTyID);
225 break;
226 }
227
228 case Type::ArrayTyID: {
229 const ArrayType *AT = cast<ArrayType>(T);
230 int Slot = Table.getSlot(AT->getElementType());
231 assert(Slot != -1 && "Type used but not available!!");
232 output_typeid((unsigned)Slot);
Reid Spencerad89bd62004-07-25 18:07:36 +0000233 output_vbr(AT->getNumElements());
234 break;
235 }
236
Brian Gaeke715c90b2004-08-20 06:00:58 +0000237 case Type::PackedTyID: {
238 const PackedType *PT = cast<PackedType>(T);
239 int Slot = Table.getSlot(PT->getElementType());
240 assert(Slot != -1 && "Type used but not available!!");
241 output_typeid((unsigned)Slot);
242 output_vbr(PT->getNumElements());
243 break;
244 }
245
246
Reid Spencerad89bd62004-07-25 18:07:36 +0000247 case Type::StructTyID: {
248 const StructType *ST = cast<StructType>(T);
249
250 // Output all of the element types...
251 for (StructType::element_iterator I = ST->element_begin(),
252 E = ST->element_end(); I != E; ++I) {
253 int Slot = Table.getSlot(*I);
254 assert(Slot != -1 && "Type used but not available!!");
255 output_typeid((unsigned)Slot);
256 }
257
258 // Terminate list with VoidTy
259 output_typeid((unsigned)Type::VoidTyID);
260 break;
261 }
262
263 case Type::PointerTyID: {
264 const PointerType *PT = cast<PointerType>(T);
265 int Slot = Table.getSlot(PT->getElementType());
266 assert(Slot != -1 && "Type used but not available!!");
267 output_typeid((unsigned)Slot);
268 break;
269 }
270
Chris Lattnerb0bf6642004-10-14 01:35:17 +0000271 case Type::OpaqueTyID:
Reid Spencerad89bd62004-07-25 18:07:36 +0000272 // No need to emit anything, just the count of opaque types is enough.
273 break;
Reid Spencerad89bd62004-07-25 18:07:36 +0000274
Reid Spencerad89bd62004-07-25 18:07:36 +0000275 default:
276 std::cerr << __FILE__ << ":" << __LINE__ << ": Don't know how to serialize"
277 << " Type '" << T->getDescription() << "'\n";
278 break;
279 }
280}
281
282void BytecodeWriter::outputConstant(const Constant *CPV) {
283 assert((CPV->getType()->isPrimitiveType() || !CPV->isNullValue()) &&
284 "Shouldn't output null constants!");
285
286 // We must check for a ConstantExpr before switching by type because
287 // a ConstantExpr can be of any type, and has no explicit value.
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000288 //
Reid Spencerad89bd62004-07-25 18:07:36 +0000289 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CPV)) {
290 // FIXME: Encoding of constant exprs could be much more compact!
291 assert(CE->getNumOperands() > 0 && "ConstantExpr with 0 operands");
Chris Lattner129baf62004-12-04 21:28:47 +0000292 assert(CE->getNumOperands() != 1 || CE->getOpcode() == Instruction::Cast);
Chris Lattnera79e7cc2004-10-16 18:18:16 +0000293 output_vbr(1+CE->getNumOperands()); // flags as an expr
Reid Spencerad89bd62004-07-25 18:07:36 +0000294 output_vbr(CE->getOpcode()); // flags as an expr
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000295
Reid Spencerad89bd62004-07-25 18:07:36 +0000296 for (User::const_op_iterator OI = CE->op_begin(); OI != CE->op_end(); ++OI){
297 int Slot = Table.getSlot(*OI);
298 assert(Slot != -1 && "Unknown constant used in ConstantExpr!!");
299 output_vbr((unsigned)Slot);
300 Slot = Table.getSlot((*OI)->getType());
301 output_typeid((unsigned)Slot);
302 }
303 return;
Chris Lattnera79e7cc2004-10-16 18:18:16 +0000304 } else if (isa<UndefValue>(CPV)) {
305 output_vbr(1U); // 1 -> UndefValue constant.
306 return;
Reid Spencerad89bd62004-07-25 18:07:36 +0000307 } else {
308 output_vbr(0U); // flag as not a ConstantExpr
309 }
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000310
Reid Spencerad89bd62004-07-25 18:07:36 +0000311 switch (CPV->getType()->getTypeID()) {
312 case Type::BoolTyID: // Boolean Types
313 if (cast<ConstantBool>(CPV)->getValue())
314 output_vbr(1U);
315 else
316 output_vbr(0U);
317 break;
318
319 case Type::UByteTyID: // Unsigned integer types...
320 case Type::UShortTyID:
321 case Type::UIntTyID:
322 case Type::ULongTyID:
323 output_vbr(cast<ConstantUInt>(CPV)->getValue());
324 break;
325
326 case Type::SByteTyID: // Signed integer types...
327 case Type::ShortTyID:
328 case Type::IntTyID:
329 case Type::LongTyID:
330 output_vbr(cast<ConstantSInt>(CPV)->getValue());
331 break;
332
333 case Type::ArrayTyID: {
334 const ConstantArray *CPA = cast<ConstantArray>(CPV);
335 assert(!CPA->isString() && "Constant strings should be handled specially!");
336
Alkis Evlogimenos15876bb2004-08-04 08:44:43 +0000337 for (unsigned i = 0, e = CPA->getNumOperands(); i != e; ++i) {
Reid Spencerad89bd62004-07-25 18:07:36 +0000338 int Slot = Table.getSlot(CPA->getOperand(i));
339 assert(Slot != -1 && "Constant used but not available!!");
340 output_vbr((unsigned)Slot);
341 }
342 break;
343 }
344
Brian Gaeke715c90b2004-08-20 06:00:58 +0000345 case Type::PackedTyID: {
346 const ConstantPacked *CP = cast<ConstantPacked>(CPV);
347
348 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i) {
349 int Slot = Table.getSlot(CP->getOperand(i));
350 assert(Slot != -1 && "Constant used but not available!!");
351 output_vbr((unsigned)Slot);
352 }
353 break;
354 }
355
Reid Spencerad89bd62004-07-25 18:07:36 +0000356 case Type::StructTyID: {
357 const ConstantStruct *CPS = cast<ConstantStruct>(CPV);
Reid Spencerad89bd62004-07-25 18:07:36 +0000358
Alkis Evlogimenos15876bb2004-08-04 08:44:43 +0000359 for (unsigned i = 0, e = CPS->getNumOperands(); i != e; ++i) {
360 int Slot = Table.getSlot(CPS->getOperand(i));
Reid Spencerad89bd62004-07-25 18:07:36 +0000361 assert(Slot != -1 && "Constant used but not available!!");
362 output_vbr((unsigned)Slot);
363 }
364 break;
365 }
366
367 case Type::PointerTyID:
368 assert(0 && "No non-null, non-constant-expr constants allowed!");
369 abort();
370
371 case Type::FloatTyID: { // Floating point types...
372 float Tmp = (float)cast<ConstantFP>(CPV)->getValue();
373 output_float(Tmp);
374 break;
375 }
376 case Type::DoubleTyID: {
377 double Tmp = cast<ConstantFP>(CPV)->getValue();
378 output_double(Tmp);
379 break;
380 }
381
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000382 case Type::VoidTyID:
Reid Spencerad89bd62004-07-25 18:07:36 +0000383 case Type::LabelTyID:
384 default:
385 std::cerr << __FILE__ << ":" << __LINE__ << ": Don't know how to serialize"
386 << " type '" << *CPV->getType() << "'\n";
387 break;
388 }
389 return;
390}
391
392void BytecodeWriter::outputConstantStrings() {
393 SlotCalculator::string_iterator I = Table.string_begin();
394 SlotCalculator::string_iterator E = Table.string_end();
395 if (I == E) return; // No strings to emit
396
397 // If we have != 0 strings to emit, output them now. Strings are emitted into
398 // the 'void' type plane.
399 output_vbr(unsigned(E-I));
400 output_typeid(Type::VoidTyID);
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000401
Reid Spencerad89bd62004-07-25 18:07:36 +0000402 // Emit all of the strings.
403 for (I = Table.string_begin(); I != E; ++I) {
404 const ConstantArray *Str = *I;
405 int Slot = Table.getSlot(Str->getType());
406 assert(Slot != -1 && "Constant string of unknown type?");
407 output_typeid((unsigned)Slot);
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000408
Reid Spencerad89bd62004-07-25 18:07:36 +0000409 // Now that we emitted the type (which indicates the size of the string),
410 // emit all of the characters.
411 std::string Val = Str->getAsString();
412 output_data(Val.c_str(), Val.c_str()+Val.size());
413 }
414}
415
416//===----------------------------------------------------------------------===//
417//=== Instruction Output ===//
418//===----------------------------------------------------------------------===//
Reid Spencerad89bd62004-07-25 18:07:36 +0000419
Chris Lattnerda895d62005-02-27 06:18:25 +0000420// outputInstructionFormat0 - Output those weird instructions that have a large
Chris Lattnerdee199f2005-05-06 22:34:01 +0000421// number of operands or have large operands themselves.
Reid Spencerad89bd62004-07-25 18:07:36 +0000422//
423// Format: [opcode] [type] [numargs] [arg0] [arg1] ... [arg<numargs-1>]
424//
Chris Lattnerf9d71782004-10-14 01:46:07 +0000425void BytecodeWriter::outputInstructionFormat0(const Instruction *I,
426 unsigned Opcode,
427 const SlotCalculator &Table,
428 unsigned Type) {
Reid Spencerad89bd62004-07-25 18:07:36 +0000429 // Opcode must have top two bits clear...
430 output_vbr(Opcode << 2); // Instruction Opcode ID
431 output_typeid(Type); // Result type
432
433 unsigned NumArgs = I->getNumOperands();
Andrew Lenharth558bc882005-06-18 18:34:52 +0000434 output_vbr(NumArgs + (isa<CastInst>(I) ||
Chris Lattnerdee199f2005-05-06 22:34:01 +0000435 isa<VAArgInst>(I) || Opcode == 56 || Opcode == 58));
Reid Spencerad89bd62004-07-25 18:07:36 +0000436
437 if (!isa<GetElementPtrInst>(&I)) {
438 for (unsigned i = 0; i < NumArgs; ++i) {
439 int Slot = Table.getSlot(I->getOperand(i));
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000440 assert(Slot >= 0 && "No slot number for value!?!?");
Reid Spencerad89bd62004-07-25 18:07:36 +0000441 output_vbr((unsigned)Slot);
442 }
443
444 if (isa<CastInst>(I) || isa<VAArgInst>(I)) {
445 int Slot = Table.getSlot(I->getType());
446 assert(Slot != -1 && "Cast return type unknown?");
447 output_typeid((unsigned)Slot);
Chris Lattnerdee199f2005-05-06 22:34:01 +0000448 } else if (Opcode == 56) { // Invoke escape sequence
449 output_vbr(cast<InvokeInst>(I)->getCallingConv());
450 } else if (Opcode == 58) { // Call escape sequence
451 output_vbr((cast<CallInst>(I)->getCallingConv() << 1) |
Jeff Cohen39cef602005-05-07 02:44:04 +0000452 unsigned(cast<CallInst>(I)->isTailCall()));
Reid Spencerad89bd62004-07-25 18:07:36 +0000453 }
Reid Spencerad89bd62004-07-25 18:07:36 +0000454 } else {
455 int Slot = Table.getSlot(I->getOperand(0));
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000456 assert(Slot >= 0 && "No slot number for value!?!?");
Reid Spencerad89bd62004-07-25 18:07:36 +0000457 output_vbr(unsigned(Slot));
458
459 // We need to encode the type of sequential type indices into their slot #
460 unsigned Idx = 1;
461 for (gep_type_iterator TI = gep_type_begin(I), E = gep_type_end(I);
462 Idx != NumArgs; ++TI, ++Idx) {
463 Slot = Table.getSlot(I->getOperand(Idx));
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000464 assert(Slot >= 0 && "No slot number for value!?!?");
465
Reid Spencerad89bd62004-07-25 18:07:36 +0000466 if (isa<SequentialType>(*TI)) {
467 unsigned IdxId;
468 switch (I->getOperand(Idx)->getType()->getTypeID()) {
469 default: assert(0 && "Unknown index type!");
470 case Type::UIntTyID: IdxId = 0; break;
471 case Type::IntTyID: IdxId = 1; break;
472 case Type::ULongTyID: IdxId = 2; break;
473 case Type::LongTyID: IdxId = 3; break;
474 }
475 Slot = (Slot << 2) | IdxId;
476 }
477 output_vbr(unsigned(Slot));
478 }
479 }
Reid Spencerad89bd62004-07-25 18:07:36 +0000480}
481
482
483// outputInstrVarArgsCall - Output the absurdly annoying varargs function calls.
484// This are more annoying than most because the signature of the call does not
485// tell us anything about the types of the arguments in the varargs portion.
486// Because of this, we encode (as type 0) all of the argument types explicitly
487// before the argument value. This really sucks, but you shouldn't be using
488// varargs functions in your code! *death to printf*!
489//
490// Format: [opcode] [type] [numargs] [arg0] [arg1] ... [arg<numargs-1>]
491//
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000492void BytecodeWriter::outputInstrVarArgsCall(const Instruction *I,
493 unsigned Opcode,
494 const SlotCalculator &Table,
495 unsigned Type) {
Reid Spencerad89bd62004-07-25 18:07:36 +0000496 assert(isa<CallInst>(I) || isa<InvokeInst>(I));
497 // Opcode must have top two bits clear...
498 output_vbr(Opcode << 2); // Instruction Opcode ID
499 output_typeid(Type); // Result type (varargs type)
500
501 const PointerType *PTy = cast<PointerType>(I->getOperand(0)->getType());
502 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
503 unsigned NumParams = FTy->getNumParams();
504
505 unsigned NumFixedOperands;
506 if (isa<CallInst>(I)) {
507 // Output an operand for the callee and each fixed argument, then two for
508 // each variable argument.
509 NumFixedOperands = 1+NumParams;
510 } else {
511 assert(isa<InvokeInst>(I) && "Not call or invoke??");
512 // Output an operand for the callee and destinations, then two for each
513 // variable argument.
514 NumFixedOperands = 3+NumParams;
515 }
516 output_vbr(2 * I->getNumOperands()-NumFixedOperands);
517
518 // The type for the function has already been emitted in the type field of the
519 // instruction. Just emit the slot # now.
520 for (unsigned i = 0; i != NumFixedOperands; ++i) {
521 int Slot = Table.getSlot(I->getOperand(i));
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000522 assert(Slot >= 0 && "No slot number for value!?!?");
Reid Spencerad89bd62004-07-25 18:07:36 +0000523 output_vbr((unsigned)Slot);
524 }
525
526 for (unsigned i = NumFixedOperands, e = I->getNumOperands(); i != e; ++i) {
527 // Output Arg Type ID
528 int Slot = Table.getSlot(I->getOperand(i)->getType());
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000529 assert(Slot >= 0 && "No slot number for value!?!?");
Reid Spencerad89bd62004-07-25 18:07:36 +0000530 output_typeid((unsigned)Slot);
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000531
Reid Spencerad89bd62004-07-25 18:07:36 +0000532 // Output arg ID itself
533 Slot = Table.getSlot(I->getOperand(i));
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000534 assert(Slot >= 0 && "No slot number for value!?!?");
Reid Spencerad89bd62004-07-25 18:07:36 +0000535 output_vbr((unsigned)Slot);
536 }
Reid Spencerad89bd62004-07-25 18:07:36 +0000537}
538
539
540// outputInstructionFormat1 - Output one operand instructions, knowing that no
541// operand index is >= 2^12.
542//
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000543inline void BytecodeWriter::outputInstructionFormat1(const Instruction *I,
544 unsigned Opcode,
545 unsigned *Slots,
546 unsigned Type) {
Reid Spencerad89bd62004-07-25 18:07:36 +0000547 // bits Instruction format:
548 // --------------------------
549 // 01-00: Opcode type, fixed to 1.
550 // 07-02: Opcode
551 // 19-08: Resulting type plane
552 // 31-20: Operand #1 (if set to (2^12-1), then zero operands)
553 //
Chris Lattnerf9d71782004-10-14 01:46:07 +0000554 output(1 | (Opcode << 2) | (Type << 8) | (Slots[0] << 20));
Reid Spencerad89bd62004-07-25 18:07:36 +0000555}
556
557
558// outputInstructionFormat2 - Output two operand instructions, knowing that no
559// operand index is >= 2^8.
560//
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000561inline void BytecodeWriter::outputInstructionFormat2(const Instruction *I,
562 unsigned Opcode,
563 unsigned *Slots,
564 unsigned Type) {
Reid Spencerad89bd62004-07-25 18:07:36 +0000565 // bits Instruction format:
566 // --------------------------
567 // 01-00: Opcode type, fixed to 2.
568 // 07-02: Opcode
569 // 15-08: Resulting type plane
570 // 23-16: Operand #1
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000571 // 31-24: Operand #2
Reid Spencerad89bd62004-07-25 18:07:36 +0000572 //
Chris Lattnerf9d71782004-10-14 01:46:07 +0000573 output(2 | (Opcode << 2) | (Type << 8) | (Slots[0] << 16) | (Slots[1] << 24));
Reid Spencerad89bd62004-07-25 18:07:36 +0000574}
575
576
577// outputInstructionFormat3 - Output three operand instructions, knowing that no
578// operand index is >= 2^6.
579//
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000580inline void BytecodeWriter::outputInstructionFormat3(const Instruction *I,
Reid Spencerad89bd62004-07-25 18:07:36 +0000581 unsigned Opcode,
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000582 unsigned *Slots,
583 unsigned Type) {
Reid Spencerad89bd62004-07-25 18:07:36 +0000584 // bits Instruction format:
585 // --------------------------
586 // 01-00: Opcode type, fixed to 3.
587 // 07-02: Opcode
588 // 13-08: Resulting type plane
589 // 19-14: Operand #1
590 // 25-20: Operand #2
591 // 31-26: Operand #3
592 //
Chris Lattnerf9d71782004-10-14 01:46:07 +0000593 output(3 | (Opcode << 2) | (Type << 8) |
Chris Lattner84d1ced2004-10-14 01:57:28 +0000594 (Slots[0] << 14) | (Slots[1] << 20) | (Slots[2] << 26));
Reid Spencerad89bd62004-07-25 18:07:36 +0000595}
596
597void BytecodeWriter::outputInstruction(const Instruction &I) {
Chris Lattnerbfed9242005-05-13 23:35:47 +0000598 assert(I.getOpcode() < 56 && "Opcode too big???");
Reid Spencerad89bd62004-07-25 18:07:36 +0000599 unsigned Opcode = I.getOpcode();
600 unsigned NumOperands = I.getNumOperands();
601
Chris Lattner38287bd2005-05-06 06:13:34 +0000602 // Encode 'tail call' as 61, 'volatile load' as 62, and 'volatile store' as
603 // 63.
Chris Lattnerdee199f2005-05-06 22:34:01 +0000604 if (const CallInst *CI = dyn_cast<CallInst>(&I)) {
605 if (CI->getCallingConv() == CallingConv::C) {
606 if (CI->isTailCall())
607 Opcode = 61; // CCC + Tail Call
608 else
609 ; // Opcode = Instruction::Call
610 } else if (CI->getCallingConv() == CallingConv::Fast) {
611 if (CI->isTailCall())
612 Opcode = 59; // FastCC + TailCall
613 else
614 Opcode = 60; // FastCC + Not Tail Call
615 } else {
616 Opcode = 58; // Call escape sequence.
617 }
618 } else if (const InvokeInst *II = dyn_cast<InvokeInst>(&I)) {
619 if (II->getCallingConv() == CallingConv::Fast)
620 Opcode = 57; // FastCC invoke.
621 else if (II->getCallingConv() != CallingConv::C)
622 Opcode = 56; // Invoke escape sequence.
Jeff Cohen00b168892005-07-27 06:12:32 +0000623
Chris Lattnerdee199f2005-05-06 22:34:01 +0000624 } else if (isa<LoadInst>(I) && cast<LoadInst>(I).isVolatile()) {
Reid Spencerad89bd62004-07-25 18:07:36 +0000625 Opcode = 62;
Chris Lattnerdee199f2005-05-06 22:34:01 +0000626 } else if (isa<StoreInst>(I) && cast<StoreInst>(I).isVolatile()) {
Reid Spencerad89bd62004-07-25 18:07:36 +0000627 Opcode = 63;
Chris Lattnerdee199f2005-05-06 22:34:01 +0000628 }
Reid Spencerad89bd62004-07-25 18:07:36 +0000629
630 // Figure out which type to encode with the instruction. Typically we want
631 // the type of the first parameter, as opposed to the type of the instruction
632 // (for example, with setcc, we always know it returns bool, but the type of
633 // the first param is actually interesting). But if we have no arguments
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000634 // we take the type of the instruction itself.
Reid Spencerad89bd62004-07-25 18:07:36 +0000635 //
636 const Type *Ty;
637 switch (I.getOpcode()) {
638 case Instruction::Select:
639 case Instruction::Malloc:
640 case Instruction::Alloca:
641 Ty = I.getType(); // These ALWAYS want to encode the return type
642 break;
643 case Instruction::Store:
644 Ty = I.getOperand(1)->getType(); // Encode the pointer type...
645 assert(isa<PointerType>(Ty) && "Store to nonpointer type!?!?");
646 break;
647 default: // Otherwise use the default behavior...
648 Ty = NumOperands ? I.getOperand(0)->getType() : I.getType();
649 break;
650 }
651
652 unsigned Type;
653 int Slot = Table.getSlot(Ty);
654 assert(Slot != -1 && "Type not available!!?!");
655 Type = (unsigned)Slot;
656
657 // Varargs calls and invokes are encoded entirely different from any other
658 // instructions.
659 if (const CallInst *CI = dyn_cast<CallInst>(&I)){
660 const PointerType *Ty =cast<PointerType>(CI->getCalledValue()->getType());
661 if (cast<FunctionType>(Ty->getElementType())->isVarArg()) {
662 outputInstrVarArgsCall(CI, Opcode, Table, Type);
663 return;
664 }
665 } else if (const InvokeInst *II = dyn_cast<InvokeInst>(&I)) {
666 const PointerType *Ty =cast<PointerType>(II->getCalledValue()->getType());
667 if (cast<FunctionType>(Ty->getElementType())->isVarArg()) {
668 outputInstrVarArgsCall(II, Opcode, Table, Type);
669 return;
670 }
671 }
672
673 if (NumOperands <= 3) {
674 // Make sure that we take the type number into consideration. We don't want
675 // to overflow the field size for the instruction format we select.
676 //
677 unsigned MaxOpSlot = Type;
678 unsigned Slots[3]; Slots[0] = (1 << 12)-1; // Marker to signify 0 operands
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000679
Reid Spencerad89bd62004-07-25 18:07:36 +0000680 for (unsigned i = 0; i != NumOperands; ++i) {
681 int slot = Table.getSlot(I.getOperand(i));
682 assert(slot != -1 && "Broken bytecode!");
683 if (unsigned(slot) > MaxOpSlot) MaxOpSlot = unsigned(slot);
684 Slots[i] = unsigned(slot);
685 }
686
687 // Handle the special cases for various instructions...
688 if (isa<CastInst>(I) || isa<VAArgInst>(I)) {
689 // Cast has to encode the destination type as the second argument in the
690 // packet, or else we won't know what type to cast to!
691 Slots[1] = Table.getSlot(I.getType());
692 assert(Slots[1] != ~0U && "Cast return type unknown?");
693 if (Slots[1] > MaxOpSlot) MaxOpSlot = Slots[1];
694 NumOperands++;
Chris Lattner42ba6b42005-11-05 22:08:14 +0000695 } else if (const AllocationInst *AI = dyn_cast<AllocationInst>(&I)) {
696 assert(NumOperands == 1 && "Bogus allocation!");
697 if (AI->getAlignment()) {
698 Slots[1] = Log2_32(AI->getAlignment())+1;
699 if (Slots[1] > MaxOpSlot) MaxOpSlot = Slots[1];
700 NumOperands = 2;
701 }
Reid Spencerad89bd62004-07-25 18:07:36 +0000702 } else if (const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(&I)) {
703 // We need to encode the type of sequential type indices into their slot #
704 unsigned Idx = 1;
705 for (gep_type_iterator I = gep_type_begin(GEP), E = gep_type_end(GEP);
706 I != E; ++I, ++Idx)
707 if (isa<SequentialType>(*I)) {
708 unsigned IdxId;
709 switch (GEP->getOperand(Idx)->getType()->getTypeID()) {
710 default: assert(0 && "Unknown index type!");
711 case Type::UIntTyID: IdxId = 0; break;
712 case Type::IntTyID: IdxId = 1; break;
713 case Type::ULongTyID: IdxId = 2; break;
714 case Type::LongTyID: IdxId = 3; break;
715 }
716 Slots[Idx] = (Slots[Idx] << 2) | IdxId;
717 if (Slots[Idx] > MaxOpSlot) MaxOpSlot = Slots[Idx];
718 }
Chris Lattnerdee199f2005-05-06 22:34:01 +0000719 } else if (Opcode == 58) {
720 // If this is the escape sequence for call, emit the tailcall/cc info.
721 const CallInst &CI = cast<CallInst>(I);
722 ++NumOperands;
723 if (NumOperands < 3) {
Jeff Cohen39cef602005-05-07 02:44:04 +0000724 Slots[NumOperands-1] = (CI.getCallingConv() << 1)|unsigned(CI.isTailCall());
Chris Lattnerdee199f2005-05-06 22:34:01 +0000725 if (Slots[NumOperands-1] > MaxOpSlot)
726 MaxOpSlot = Slots[NumOperands-1];
727 }
728 } else if (Opcode == 56) {
729 // Invoke escape seq has at least 4 operands to encode.
730 ++NumOperands;
Reid Spencerad89bd62004-07-25 18:07:36 +0000731 }
732
733 // Decide which instruction encoding to use. This is determined primarily
734 // by the number of operands, and secondarily by whether or not the max
735 // operand will fit into the instruction encoding. More operands == fewer
736 // bits per operand.
737 //
738 switch (NumOperands) {
739 case 0:
740 case 1:
741 if (MaxOpSlot < (1 << 12)-1) { // -1 because we use 4095 to indicate 0 ops
742 outputInstructionFormat1(&I, Opcode, Slots, Type);
743 return;
744 }
745 break;
746
747 case 2:
748 if (MaxOpSlot < (1 << 8)) {
749 outputInstructionFormat2(&I, Opcode, Slots, Type);
750 return;
751 }
752 break;
753
754 case 3:
755 if (MaxOpSlot < (1 << 6)) {
756 outputInstructionFormat3(&I, Opcode, Slots, Type);
757 return;
758 }
759 break;
760 default:
761 break;
762 }
763 }
764
765 // If we weren't handled before here, we either have a large number of
766 // operands or a large operand index that we are referring to.
767 outputInstructionFormat0(&I, Opcode, Table, Type);
768}
769
770//===----------------------------------------------------------------------===//
771//=== Block Output ===//
772//===----------------------------------------------------------------------===//
773
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000774BytecodeWriter::BytecodeWriter(std::vector<unsigned char> &o, const Module *M)
Reid Spencer798ff642004-05-26 07:37:11 +0000775 : Out(o), Table(M) {
Chris Lattner00950542001-06-06 20:29:01 +0000776
Chris Lattner83bb3d22004-01-14 23:36:54 +0000777 // Emit the signature...
778 static const unsigned char *Sig = (const unsigned char*)"llvm";
Reid Spencerad89bd62004-07-25 18:07:36 +0000779 output_data(Sig, Sig+4);
Chris Lattner00950542001-06-06 20:29:01 +0000780
781 // Emit the top level CLASS block.
Reid Spencerad89bd62004-07-25 18:07:36 +0000782 BytecodeBlock ModuleBlock(BytecodeFormat::ModuleBlockID, *this, false, true);
Chris Lattner00950542001-06-06 20:29:01 +0000783
Chris Lattnerd445c6b2003-08-24 13:47:36 +0000784 bool isBigEndian = M->getEndianness() == Module::BigEndian;
785 bool hasLongPointers = M->getPointerSize() == Module::Pointer64;
786 bool hasNoEndianness = M->getEndianness() == Module::AnyEndianness;
787 bool hasNoPointerSize = M->getPointerSize() == Module::AnyPointerSize;
Chris Lattner186a1f72003-03-19 20:56:46 +0000788
Chris Lattnera79e7cc2004-10-16 18:18:16 +0000789 // Output the version identifier and other information.
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000790 unsigned Version = (BCVersionNum << 4) |
Reid Spencer38d54be2004-08-17 07:45:14 +0000791 (unsigned)isBigEndian | (hasLongPointers << 1) |
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000792 (hasNoEndianness << 2) |
Reid Spencer38d54be2004-08-17 07:45:14 +0000793 (hasNoPointerSize << 3);
Reid Spencerad89bd62004-07-25 18:07:36 +0000794 output_vbr(Version);
Chris Lattner00950542001-06-06 20:29:01 +0000795
Reid Spencercb3595c2004-07-04 11:45:47 +0000796 // The Global type plane comes first
Chris Lattner186a1f72003-03-19 20:56:46 +0000797 {
Reid Spencerad89bd62004-07-25 18:07:36 +0000798 BytecodeBlock CPool(BytecodeFormat::GlobalTypePlaneBlockID, *this );
Reid Spencercb3595c2004-07-04 11:45:47 +0000799 outputTypes(Type::FirstDerivedTyID);
Chris Lattner186a1f72003-03-19 20:56:46 +0000800 }
Chris Lattner00950542001-06-06 20:29:01 +0000801
Chris Lattner186a1f72003-03-19 20:56:46 +0000802 // The ModuleInfoBlock follows directly after the type information
Chris Lattnere8fdde12001-09-07 16:39:41 +0000803 outputModuleInfoBlock(M);
804
Chris Lattner186a1f72003-03-19 20:56:46 +0000805 // Output module level constants, used for global variable initializers
806 outputConstants(false);
807
Chris Lattnerb5794002002-04-07 22:49:37 +0000808 // Do the whole module now! Process each function at a time...
Chris Lattner0b12b5f2002-06-25 16:13:21 +0000809 for (Module::const_iterator I = M->begin(), E = M->end(); I != E; ++I)
Chris Lattner186a1f72003-03-19 20:56:46 +0000810 outputFunction(I);
Chris Lattnere8fdde12001-09-07 16:39:41 +0000811
812 // If needed, output the symbol table for the module...
Chris Lattner6e6026b2002-11-20 18:36:02 +0000813 outputSymbolTable(M->getSymbolTable());
Chris Lattner00950542001-06-06 20:29:01 +0000814}
815
Chris Lattnerf9d71782004-10-14 01:46:07 +0000816void BytecodeWriter::outputTypes(unsigned TypeNum) {
Reid Spencercb3595c2004-07-04 11:45:47 +0000817 // Write the type plane for types first because earlier planes (e.g. for a
818 // primitive type like float) may have constants constructed using types
819 // coming later (e.g., via getelementptr from a pointer type). The type
820 // plane is needed before types can be fwd or bkwd referenced.
821 const std::vector<const Type*>& Types = Table.getTypes();
822 assert(!Types.empty() && "No types at all?");
823 assert(TypeNum <= Types.size() && "Invalid TypeNo index");
824
825 unsigned NumEntries = Types.size() - TypeNum;
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000826
Reid Spencercb3595c2004-07-04 11:45:47 +0000827 // Output type header: [num entries]
Reid Spencerad89bd62004-07-25 18:07:36 +0000828 output_vbr(NumEntries);
Reid Spencercb3595c2004-07-04 11:45:47 +0000829
830 for (unsigned i = TypeNum; i < TypeNum+NumEntries; ++i)
831 outputType(Types[i]);
832}
833
Vikram S. Advea7dac3d2002-07-14 23:07:51 +0000834// Helper function for outputConstants().
835// Writes out all the constants in the plane Plane starting at entry StartNo.
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000836//
Vikram S. Advea7dac3d2002-07-14 23:07:51 +0000837void BytecodeWriter::outputConstantsInPlane(const std::vector<const Value*>
838 &Plane, unsigned StartNo) {
839 unsigned ValNo = StartNo;
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000840
Chris Lattner83bb3d22004-01-14 23:36:54 +0000841 // Scan through and ignore function arguments, global values, and constant
842 // strings.
843 for (; ValNo < Plane.size() &&
844 (isa<Argument>(Plane[ValNo]) || isa<GlobalValue>(Plane[ValNo]) ||
845 (isa<ConstantArray>(Plane[ValNo]) &&
846 cast<ConstantArray>(Plane[ValNo])->isString())); ValNo++)
Vikram S. Advea7dac3d2002-07-14 23:07:51 +0000847 /*empty*/;
848
849 unsigned NC = ValNo; // Number of constants
Reid Spencercb3595c2004-07-04 11:45:47 +0000850 for (; NC < Plane.size() && (isa<Constant>(Plane[NC])); NC++)
Vikram S. Advea7dac3d2002-07-14 23:07:51 +0000851 /*empty*/;
852 NC -= ValNo; // Convert from index into count
853 if (NC == 0) return; // Skip empty type planes...
854
Chris Lattnerd6942d72004-01-14 16:54:21 +0000855 // FIXME: Most slabs only have 1 or 2 entries! We should encode this much
856 // more compactly.
857
Vikram S. Advea7dac3d2002-07-14 23:07:51 +0000858 // Output type header: [num entries][type id number]
859 //
Reid Spencerad89bd62004-07-25 18:07:36 +0000860 output_vbr(NC);
Vikram S. Advea7dac3d2002-07-14 23:07:51 +0000861
862 // Output the Type ID Number...
Alkis Evlogimenos60596382003-10-17 02:02:40 +0000863 int Slot = Table.getSlot(Plane.front()->getType());
Vikram S. Advea7dac3d2002-07-14 23:07:51 +0000864 assert (Slot != -1 && "Type in constant pool but not in function!!");
Reid Spencerad89bd62004-07-25 18:07:36 +0000865 output_typeid((unsigned)Slot);
Vikram S. Advea7dac3d2002-07-14 23:07:51 +0000866
Vikram S. Advea7dac3d2002-07-14 23:07:51 +0000867 for (unsigned i = ValNo; i < ValNo+NC; ++i) {
868 const Value *V = Plane[i];
Reid Spencere0125b62004-07-18 00:16:21 +0000869 if (const Constant *C = dyn_cast<Constant>(V)) {
870 outputConstant(C);
Vikram S. Advea7dac3d2002-07-14 23:07:51 +0000871 }
872 }
873}
874
Chris Lattner9e60d8d2005-05-05 22:21:19 +0000875static inline bool hasNullValue(const Type *Ty) {
876 return Ty != Type::LabelTy && Ty != Type::VoidTy && !isa<OpaqueType>(Ty);
Chris Lattner80b97342004-01-17 23:25:43 +0000877}
878
Chris Lattner79df7c02002-03-26 18:01:55 +0000879void BytecodeWriter::outputConstants(bool isFunction) {
Reid Spencerad89bd62004-07-25 18:07:36 +0000880 BytecodeBlock CPool(BytecodeFormat::ConstantPoolBlockID, *this,
Chris Lattner0baa0af2004-01-15 21:06:57 +0000881 true /* Elide block if empty */);
Chris Lattner00950542001-06-06 20:29:01 +0000882
883 unsigned NumPlanes = Table.getNumPlanes();
Chris Lattnerf69315b2003-05-22 18:35:38 +0000884
Reid Spencere0125b62004-07-18 00:16:21 +0000885 if (isFunction)
886 // Output the type plane before any constants!
Chris Lattnera79e7cc2004-10-16 18:18:16 +0000887 outputTypes(Table.getModuleTypeLevel());
Reid Spencere0125b62004-07-18 00:16:21 +0000888 else
Chris Lattnerf9d71782004-10-14 01:46:07 +0000889 // Output module-level string constants before any other constants.
Chris Lattner83bb3d22004-01-14 23:36:54 +0000890 outputConstantStrings();
891
Reid Spencercb3595c2004-07-04 11:45:47 +0000892 for (unsigned pno = 0; pno != NumPlanes; pno++) {
893 const std::vector<const Value*> &Plane = Table.getPlane(pno);
894 if (!Plane.empty()) { // Skip empty type planes...
895 unsigned ValNo = 0;
896 if (isFunction) // Don't re-emit module constants
Reid Spencer0852c802004-07-04 11:46:15 +0000897 ValNo += Table.getModuleLevel(pno);
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000898
Chris Lattner9e60d8d2005-05-05 22:21:19 +0000899 if (hasNullValue(Plane[0]->getType())) {
Reid Spencer0852c802004-07-04 11:46:15 +0000900 // Skip zero initializer
901 if (ValNo == 0)
902 ValNo = 1;
Chris Lattnerf69315b2003-05-22 18:35:38 +0000903 }
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000904
Reid Spencercb3595c2004-07-04 11:45:47 +0000905 // Write out constants in the plane
906 outputConstantsInPlane(Plane, ValNo);
Chris Lattnerf69315b2003-05-22 18:35:38 +0000907 }
Reid Spencercb3595c2004-07-04 11:45:47 +0000908 }
Chris Lattner00950542001-06-06 20:29:01 +0000909}
910
Chris Lattner6b252422003-10-16 18:28:50 +0000911static unsigned getEncodedLinkage(const GlobalValue *GV) {
912 switch (GV->getLinkage()) {
913 default: assert(0 && "Invalid linkage!");
914 case GlobalValue::ExternalLinkage: return 0;
Chris Lattner6b252422003-10-16 18:28:50 +0000915 case GlobalValue::WeakLinkage: return 1;
916 case GlobalValue::AppendingLinkage: return 2;
917 case GlobalValue::InternalLinkage: return 3;
Chris Lattner22482a12003-10-18 06:30:21 +0000918 case GlobalValue::LinkOnceLinkage: return 4;
Chris Lattner6b252422003-10-16 18:28:50 +0000919 }
920}
921
Chris Lattner00950542001-06-06 20:29:01 +0000922void BytecodeWriter::outputModuleInfoBlock(const Module *M) {
Reid Spencerad89bd62004-07-25 18:07:36 +0000923 BytecodeBlock ModuleInfoBlock(BytecodeFormat::ModuleGlobalInfoBlockID, *this);
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000924
Chris Lattner404cddf2005-11-12 01:33:40 +0000925 // Give numbers to sections as we encounter them.
926 unsigned SectionIDCounter = 0;
927 std::vector<std::string> SectionNames;
928 std::map<std::string, unsigned> SectionID;
929
Chris Lattner70cc3392001-09-10 07:58:01 +0000930 // Output the types for the global variables in the module...
Chris Lattner28caccf2005-05-06 20:27:03 +0000931 for (Module::const_global_iterator I = M->global_begin(),
Chris Lattner8eb52dd2005-11-06 07:11:04 +0000932 End = M->global_end(); I != End; ++I) {
Alkis Evlogimenos60596382003-10-17 02:02:40 +0000933 int Slot = Table.getSlot(I->getType());
Chris Lattner70cc3392001-09-10 07:58:01 +0000934 assert(Slot != -1 && "Module global vars is broken!");
Chris Lattnerd70684f2001-09-18 04:01:05 +0000935
Chris Lattner8eb52dd2005-11-06 07:11:04 +0000936 assert((I->hasInitializer() || !I->hasInternalLinkage()) &&
937 "Global must have an initializer or have external linkage!");
938
Chris Lattner22482a12003-10-18 06:30:21 +0000939 // Fields: bit0 = isConstant, bit1 = hasInitializer, bit2-4=Linkage,
Chris Lattner8eb52dd2005-11-06 07:11:04 +0000940 // bit5+ = Slot # for type.
Chris Lattner404cddf2005-11-12 01:33:40 +0000941 bool HasExtensionWord = (I->getAlignment() != 0) || I->hasSection();
Chris Lattner8eb52dd2005-11-06 07:11:04 +0000942
943 // If we need to use the extension byte, set linkage=3(internal) and
944 // initializer = 0 (impossible!).
945 if (!HasExtensionWord) {
946 unsigned oSlot = ((unsigned)Slot << 5) | (getEncodedLinkage(I) << 2) |
947 (I->hasInitializer() << 1) | (unsigned)I->isConstant();
948 output_vbr(oSlot);
949 } else {
950 unsigned oSlot = ((unsigned)Slot << 5) | (3 << 2) |
951 (0 << 1) | (unsigned)I->isConstant();
952 output_vbr(oSlot);
953
954 // The extension word has this format: bit 0 = has initializer, bit 1-3 =
Chris Lattner404cddf2005-11-12 01:33:40 +0000955 // linkage, bit 4-8 = alignment (log2), bit 9 = has SectionID,
956 // bits 10+ = future use.
Jeff Cohenba0ffcc2005-11-12 01:01:50 +0000957 unsigned ExtWord = (unsigned)I->hasInitializer() |
958 (getEncodedLinkage(I) << 1) |
Chris Lattner404cddf2005-11-12 01:33:40 +0000959 ((Log2_32(I->getAlignment())+1) << 4) |
960 ((unsigned)I->hasSection() << 9);
Chris Lattner8eb52dd2005-11-06 07:11:04 +0000961 output_vbr(ExtWord);
Chris Lattner404cddf2005-11-12 01:33:40 +0000962 if (I->hasSection()) {
963 // Give section names unique ID's.
964 unsigned &Entry = SectionID[I->getSection()];
965 if (Entry == 0) {
966 Entry = ++SectionIDCounter;
967 SectionNames.push_back(I->getSection());
968 }
969 output_vbr(Entry);
970 }
Chris Lattner8eb52dd2005-11-06 07:11:04 +0000971 }
Chris Lattnerd70684f2001-09-18 04:01:05 +0000972
Chris Lattner1b98c5c2001-10-13 06:48:38 +0000973 // If we have an initializer, output it now.
Chris Lattner0b12b5f2002-06-25 16:13:21 +0000974 if (I->hasInitializer()) {
Alkis Evlogimenos60596382003-10-17 02:02:40 +0000975 Slot = Table.getSlot((Value*)I->getInitializer());
Chris Lattnerd70684f2001-09-18 04:01:05 +0000976 assert(Slot != -1 && "No slot for global var initializer!");
Reid Spencerad89bd62004-07-25 18:07:36 +0000977 output_vbr((unsigned)Slot);
Chris Lattnerd70684f2001-09-18 04:01:05 +0000978 }
Chris Lattner70cc3392001-09-10 07:58:01 +0000979 }
Reid Spencerad89bd62004-07-25 18:07:36 +0000980 output_typeid((unsigned)Table.getSlot(Type::VoidTy));
Chris Lattner70cc3392001-09-10 07:58:01 +0000981
Chris Lattnera79e7cc2004-10-16 18:18:16 +0000982 // Output the types of the functions in this module.
Chris Lattner7fc9fe32001-06-27 23:41:11 +0000983 for (Module::const_iterator I = M->begin(), End = M->end(); I != End; ++I) {
Alkis Evlogimenos60596382003-10-17 02:02:40 +0000984 int Slot = Table.getSlot(I->getType());
Chris Lattnera79e7cc2004-10-16 18:18:16 +0000985 assert(Slot != -1 && "Module slot calculator is broken!");
Chris Lattner00950542001-06-06 20:29:01 +0000986 assert(Slot >= Type::FirstDerivedTyID && "Derived type not in range!");
Chris Lattnere73bd452005-11-06 07:43:39 +0000987 assert(((Slot << 6) >> 6) == Slot && "Slot # too big!");
Chris Lattner54b369e2005-11-06 07:46:13 +0000988 unsigned CC = I->getCallingConv()+1;
989 unsigned ID = (Slot << 5) | (CC & 15);
Chris Lattner479ffeb2005-05-06 20:42:57 +0000990
Chris Lattnerd6e431f2004-11-15 22:39:49 +0000991 if (I->isExternal()) // If external, we don't have an FunctionInfo block.
992 ID |= 1 << 4;
Chris Lattnere73bd452005-11-06 07:43:39 +0000993
Chris Lattner404cddf2005-11-12 01:33:40 +0000994 if (I->getAlignment() || I->hasSection() || (CC & ~15) != 0)
Chris Lattnere73bd452005-11-06 07:43:39 +0000995 ID |= 1 << 31; // Do we need an extension word?
996
Chris Lattnera79e7cc2004-10-16 18:18:16 +0000997 output_vbr(ID);
Chris Lattnere73bd452005-11-06 07:43:39 +0000998
999 if (ID & (1 << 31)) {
1000 // Extension byte: bits 0-4 = alignment, bits 5-9 = top nibble of calling
Chris Lattner404cddf2005-11-12 01:33:40 +00001001 // convention, bit 10 = hasSectionID.
1002 ID = (Log2_32(I->getAlignment())+1) | ((CC >> 4) << 5) |
1003 (I->hasSection() << 10);
Chris Lattnere73bd452005-11-06 07:43:39 +00001004 output_vbr(ID);
Chris Lattner404cddf2005-11-12 01:33:40 +00001005
1006 // Give section names unique ID's.
1007 if (I->hasSection()) {
1008 unsigned &Entry = SectionID[I->getSection()];
1009 if (Entry == 0) {
1010 Entry = ++SectionIDCounter;
1011 SectionNames.push_back(I->getSection());
1012 }
1013 output_vbr(Entry);
1014 }
Chris Lattnere73bd452005-11-06 07:43:39 +00001015 }
Chris Lattner00950542001-06-06 20:29:01 +00001016 }
Chris Lattnera79e7cc2004-10-16 18:18:16 +00001017 output_vbr((unsigned)Table.getSlot(Type::VoidTy) << 5);
Reid Spencerad89bd62004-07-25 18:07:36 +00001018
Chris Lattnera79e7cc2004-10-16 18:18:16 +00001019 // Emit the list of dependent libraries for the Module.
Reid Spencer5ac88122004-07-25 21:32:02 +00001020 Module::lib_iterator LI = M->lib_begin();
1021 Module::lib_iterator LE = M->lib_end();
Chris Lattnera79e7cc2004-10-16 18:18:16 +00001022 output_vbr(unsigned(LE - LI)); // Emit the number of dependent libraries.
1023 for (; LI != LE; ++LI)
Reid Spencer38d54be2004-08-17 07:45:14 +00001024 output(*LI);
Reid Spencerad89bd62004-07-25 18:07:36 +00001025
1026 // Output the target triple from the module
Reid Spencer38d54be2004-08-17 07:45:14 +00001027 output(M->getTargetTriple());
Chris Lattner404cddf2005-11-12 01:33:40 +00001028
1029 // Emit the table of section names.
1030 output_vbr((unsigned)SectionNames.size());
1031 for (unsigned i = 0, e = SectionNames.size(); i != e; ++i)
1032 output(SectionNames[i]);
Chris Lattner00950542001-06-06 20:29:01 +00001033}
1034
Chris Lattnercf3e67f2004-01-18 21:08:52 +00001035void BytecodeWriter::outputInstructions(const Function *F) {
Reid Spencerad89bd62004-07-25 18:07:36 +00001036 BytecodeBlock ILBlock(BytecodeFormat::InstructionListBlockID, *this);
Chris Lattnercf3e67f2004-01-18 21:08:52 +00001037 for (Function::const_iterator BB = F->begin(), E = F->end(); BB != E; ++BB)
1038 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I!=E; ++I)
1039 outputInstruction(*I);
Chris Lattnercf3e67f2004-01-18 21:08:52 +00001040}
1041
Chris Lattner186a1f72003-03-19 20:56:46 +00001042void BytecodeWriter::outputFunction(const Function *F) {
Chris Lattnerfd7f8fe2004-11-15 21:56:33 +00001043 // If this is an external function, there is nothing else to emit!
1044 if (F->isExternal()) return;
1045
Chris Lattnerd6e431f2004-11-15 22:39:49 +00001046 BytecodeBlock FunctionBlock(BytecodeFormat::FunctionBlockID, *this);
1047 output_vbr(getEncodedLinkage(F));
1048
Chris Lattnercf3e67f2004-01-18 21:08:52 +00001049 // Get slot information about the function...
1050 Table.incorporateFunction(F);
1051
1052 if (Table.getCompactionTable().empty()) {
1053 // Output information about the constants in the function if the compaction
1054 // table is not being used.
Chris Lattnere8fdde12001-09-07 16:39:41 +00001055 outputConstants(true);
Chris Lattnercf3e67f2004-01-18 21:08:52 +00001056 } else {
1057 // Otherwise, emit the compaction table.
1058 outputCompactionTable();
Chris Lattnere8fdde12001-09-07 16:39:41 +00001059 }
Misha Brukman23c6d2c2005-04-21 21:48:46 +00001060
Chris Lattnercf3e67f2004-01-18 21:08:52 +00001061 // Output all of the instructions in the body of the function
1062 outputInstructions(F);
Misha Brukman23c6d2c2005-04-21 21:48:46 +00001063
Chris Lattnercf3e67f2004-01-18 21:08:52 +00001064 // If needed, output the symbol table for the function...
1065 outputSymbolTable(F->getSymbolTable());
Misha Brukman23c6d2c2005-04-21 21:48:46 +00001066
Chris Lattnercf3e67f2004-01-18 21:08:52 +00001067 Table.purgeFunction();
1068}
1069
1070void BytecodeWriter::outputCompactionTablePlane(unsigned PlaneNo,
1071 const std::vector<const Value*> &Plane,
1072 unsigned StartNo) {
1073 unsigned End = Table.getModuleLevel(PlaneNo);
Chris Lattner52f86d62004-01-20 00:54:06 +00001074 if (Plane.empty() || StartNo == End || End == 0) return; // Nothing to emit
Chris Lattnercf3e67f2004-01-18 21:08:52 +00001075 assert(StartNo < End && "Cannot emit negative range!");
1076 assert(StartNo < Plane.size() && End <= Plane.size());
1077
Chris Lattnercf3e67f2004-01-18 21:08:52 +00001078 // Do not emit the null initializer!
Reid Spencercb3595c2004-07-04 11:45:47 +00001079 ++StartNo;
Chris Lattnercf3e67f2004-01-18 21:08:52 +00001080
Chris Lattner24102432004-01-18 22:35:34 +00001081 // Figure out which encoding to use. By far the most common case we have is
1082 // to emit 0-2 entries in a compaction table plane.
1083 switch (End-StartNo) {
1084 case 0: // Avoid emitting two vbr's if possible.
1085 case 1:
1086 case 2:
Reid Spencerad89bd62004-07-25 18:07:36 +00001087 output_vbr((PlaneNo << 2) | End-StartNo);
Chris Lattner24102432004-01-18 22:35:34 +00001088 break;
1089 default:
1090 // Output the number of things.
Reid Spencerad89bd62004-07-25 18:07:36 +00001091 output_vbr((unsigned(End-StartNo) << 2) | 3);
1092 output_typeid(PlaneNo); // Emit the type plane this is
Chris Lattner24102432004-01-18 22:35:34 +00001093 break;
1094 }
1095
Chris Lattnercf3e67f2004-01-18 21:08:52 +00001096 for (unsigned i = StartNo; i != End; ++i)
Reid Spencerad89bd62004-07-25 18:07:36 +00001097 output_vbr(Table.getGlobalSlot(Plane[i]));
Chris Lattnercf3e67f2004-01-18 21:08:52 +00001098}
1099
Reid Spencercb3595c2004-07-04 11:45:47 +00001100void BytecodeWriter::outputCompactionTypes(unsigned StartNo) {
1101 // Get the compaction type table from the slot calculator
1102 const std::vector<const Type*> &CTypes = Table.getCompactionTypes();
1103
1104 // The compaction types may have been uncompactified back to the
1105 // global types. If so, we just write an empty table
1106 if (CTypes.size() == 0 ) {
Reid Spencerad89bd62004-07-25 18:07:36 +00001107 output_vbr(0U);
Reid Spencercb3595c2004-07-04 11:45:47 +00001108 return;
1109 }
1110
1111 assert(CTypes.size() >= StartNo && "Invalid compaction types start index");
1112
1113 // Determine how many types to write
1114 unsigned NumTypes = CTypes.size() - StartNo;
1115
1116 // Output the number of types.
Reid Spencerad89bd62004-07-25 18:07:36 +00001117 output_vbr(NumTypes);
Reid Spencercb3595c2004-07-04 11:45:47 +00001118
1119 for (unsigned i = StartNo; i < StartNo+NumTypes; ++i)
Reid Spencerad89bd62004-07-25 18:07:36 +00001120 output_typeid(Table.getGlobalSlot(CTypes[i]));
Reid Spencercb3595c2004-07-04 11:45:47 +00001121}
1122
Chris Lattnercf3e67f2004-01-18 21:08:52 +00001123void BytecodeWriter::outputCompactionTable() {
Reid Spencer0033c182004-08-27 00:38:44 +00001124 // Avoid writing the compaction table at all if there is no content.
1125 if (Table.getCompactionTypes().size() >= Type::FirstDerivedTyID ||
1126 (!Table.CompactionTableIsEmpty())) {
Misha Brukman23c6d2c2005-04-21 21:48:46 +00001127 BytecodeBlock CTB(BytecodeFormat::CompactionTableBlockID, *this,
Reid Spencer0033c182004-08-27 00:38:44 +00001128 true/*ElideIfEmpty*/);
Chris Lattnerf9d71782004-10-14 01:46:07 +00001129 const std::vector<std::vector<const Value*> > &CT =
1130 Table.getCompactionTable();
Misha Brukman23c6d2c2005-04-21 21:48:46 +00001131
Reid Spencer0033c182004-08-27 00:38:44 +00001132 // First things first, emit the type compaction table if there is one.
1133 outputCompactionTypes(Type::FirstDerivedTyID);
Chris Lattnercf3e67f2004-01-18 21:08:52 +00001134
Reid Spencer0033c182004-08-27 00:38:44 +00001135 for (unsigned i = 0, e = CT.size(); i != e; ++i)
1136 outputCompactionTablePlane(i, CT[i], 0);
1137 }
Chris Lattner00950542001-06-06 20:29:01 +00001138}
1139
Chris Lattner00950542001-06-06 20:29:01 +00001140void BytecodeWriter::outputSymbolTable(const SymbolTable &MST) {
Chris Lattner737d3cd2004-01-10 19:56:59 +00001141 // Do not output the Bytecode block for an empty symbol table, it just wastes
1142 // space!
Chris Lattnerf9d71782004-10-14 01:46:07 +00001143 if (MST.isEmpty()) return;
Chris Lattner737d3cd2004-01-10 19:56:59 +00001144
Reid Spencerad89bd62004-07-25 18:07:36 +00001145 BytecodeBlock SymTabBlock(BytecodeFormat::SymbolTableBlockID, *this,
Chris Lattnerf9d71782004-10-14 01:46:07 +00001146 true/*ElideIfEmpty*/);
Chris Lattner00950542001-06-06 20:29:01 +00001147
Misha Brukman23c6d2c2005-04-21 21:48:46 +00001148 // Write the number of types
Reid Spencerad89bd62004-07-25 18:07:36 +00001149 output_vbr(MST.num_types());
Reid Spencer250c4182004-08-17 02:59:02 +00001150
1151 // Write each of the types
Reid Spencer94f2df22004-05-25 17:29:59 +00001152 for (SymbolTable::type_const_iterator TI = MST.type_begin(),
1153 TE = MST.type_end(); TI != TE; ++TI ) {
Reid Spencer250c4182004-08-17 02:59:02 +00001154 // Symtab entry:[def slot #][name]
Reid Spencerad89bd62004-07-25 18:07:36 +00001155 output_typeid((unsigned)Table.getSlot(TI->second));
Misha Brukman23c6d2c2005-04-21 21:48:46 +00001156 output(TI->first);
Reid Spencer94f2df22004-05-25 17:29:59 +00001157 }
1158
1159 // Now do each of the type planes in order.
Misha Brukman23c6d2c2005-04-21 21:48:46 +00001160 for (SymbolTable::plane_const_iterator PI = MST.plane_begin(),
Reid Spencer94f2df22004-05-25 17:29:59 +00001161 PE = MST.plane_end(); PI != PE; ++PI) {
1162 SymbolTable::value_const_iterator I = MST.value_begin(PI->first);
1163 SymbolTable::value_const_iterator End = MST.value_end(PI->first);
Chris Lattner00950542001-06-06 20:29:01 +00001164 int Slot;
Misha Brukman23c6d2c2005-04-21 21:48:46 +00001165
Chris Lattner00950542001-06-06 20:29:01 +00001166 if (I == End) continue; // Don't mess with an absent type...
1167
Reid Spencer250c4182004-08-17 02:59:02 +00001168 // Write the number of values in this plane
Chris Lattner001d16a2005-03-07 02:59:36 +00001169 output_vbr((unsigned)PI->second.size());
Chris Lattner00950542001-06-06 20:29:01 +00001170
Reid Spencer250c4182004-08-17 02:59:02 +00001171 // Write the slot number of the type for this plane
Reid Spencer94f2df22004-05-25 17:29:59 +00001172 Slot = Table.getSlot(PI->first);
Chris Lattner00950542001-06-06 20:29:01 +00001173 assert(Slot != -1 && "Type in symtab, but not in table!");
Reid Spencerad89bd62004-07-25 18:07:36 +00001174 output_typeid((unsigned)Slot);
Chris Lattner00950542001-06-06 20:29:01 +00001175
Reid Spencer250c4182004-08-17 02:59:02 +00001176 // Write each of the values in this plane
Chris Lattner7fc9fe32001-06-27 23:41:11 +00001177 for (; I != End; ++I) {
Chris Lattner00950542001-06-06 20:29:01 +00001178 // Symtab entry: [def slot #][name]
Alkis Evlogimenos60596382003-10-17 02:02:40 +00001179 Slot = Table.getSlot(I->second);
Chris Lattnere8fdde12001-09-07 16:39:41 +00001180 assert(Slot != -1 && "Value in symtab but has no slot number!!");
Reid Spencerad89bd62004-07-25 18:07:36 +00001181 output_vbr((unsigned)Slot);
Reid Spencer38d54be2004-08-17 07:45:14 +00001182 output(I->first);
Chris Lattner00950542001-06-06 20:29:01 +00001183 }
1184 }
1185}
1186
Reid Spencer17f52c52004-11-06 23:17:23 +00001187void llvm::WriteBytecodeToFile(const Module *M, std::ostream &Out,
1188 bool compress ) {
Reid Spencerad89bd62004-07-25 18:07:36 +00001189 assert(M && "You can't write a null module!!");
Chris Lattner00950542001-06-06 20:29:01 +00001190
Reid Spencer17f52c52004-11-06 23:17:23 +00001191 // Create a vector of unsigned char for the bytecode output. We
1192 // reserve 256KBytes of space in the vector so that we avoid doing
1193 // lots of little allocations. 256KBytes is sufficient for a large
1194 // proportion of the bytecode files we will encounter. Larger files
1195 // will be automatically doubled in size as needed (std::vector
1196 // behavior).
Reid Spencerad89bd62004-07-25 18:07:36 +00001197 std::vector<unsigned char> Buffer;
Reid Spencer17f52c52004-11-06 23:17:23 +00001198 Buffer.reserve(256 * 1024);
Chris Lattner00950542001-06-06 20:29:01 +00001199
Reid Spencer17f52c52004-11-06 23:17:23 +00001200 // The BytecodeWriter populates Buffer for us.
Reid Spencerad89bd62004-07-25 18:07:36 +00001201 BytecodeWriter BCW(Buffer, M);
Chris Lattner00950542001-06-06 20:29:01 +00001202
Reid Spencer17f52c52004-11-06 23:17:23 +00001203 // Keep track of how much we've written
Chris Lattnerce6ef112002-07-26 18:40:14 +00001204 BytesWritten += Buffer.size();
1205
Reid Spencer17f52c52004-11-06 23:17:23 +00001206 // Determine start and end points of the Buffer
Reid Spencer83296f52004-11-07 18:17:38 +00001207 const unsigned char *FirstByte = &Buffer.front();
Reid Spencer17f52c52004-11-06 23:17:23 +00001208
1209 // If we're supposed to compress this mess ...
1210 if (compress) {
1211
1212 // We signal compression by using an alternate magic number for the
Reid Spencer83296f52004-11-07 18:17:38 +00001213 // file. The compressed bytecode file's magic number is "llvc" instead
Misha Brukman23c6d2c2005-04-21 21:48:46 +00001214 // of "llvm".
Reid Spencer83296f52004-11-07 18:17:38 +00001215 char compressed_magic[4];
1216 compressed_magic[0] = 'l';
1217 compressed_magic[1] = 'l';
1218 compressed_magic[2] = 'v';
1219 compressed_magic[3] = 'c';
Reid Spencer17f52c52004-11-06 23:17:23 +00001220
Reid Spencer83296f52004-11-07 18:17:38 +00001221 Out.write(compressed_magic,4);
Reid Spencer17f52c52004-11-06 23:17:23 +00001222
Reid Spencera70d84d2004-11-14 22:01:41 +00001223 // Compress everything after the magic number (which we altered)
1224 uint64_t zipSize = Compressor::compressToStream(
Reid Spencer17f52c52004-11-06 23:17:23 +00001225 (char*)(FirstByte+4), // Skip the magic number
1226 Buffer.size()-4, // Skip the magic number
Reid Spencer84472d62004-11-25 19:38:05 +00001227 Out // Where to write compressed data
Reid Spencer17f52c52004-11-06 23:17:23 +00001228 );
1229
Reid Spencer17f52c52004-11-06 23:17:23 +00001230 } else {
1231
1232 // We're not compressing, so just write the entire block.
Reid Spencer83296f52004-11-07 18:17:38 +00001233 Out.write((char*)FirstByte, Buffer.size());
Chris Lattnere8fdde12001-09-07 16:39:41 +00001234 }
Reid Spencer17f52c52004-11-06 23:17:23 +00001235
1236 // make sure it hits disk now
Chris Lattner00950542001-06-06 20:29:01 +00001237 Out.flush();
1238}
Reid Spencere0125b62004-07-18 00:16:21 +00001239