blob: ce6d08a5c03699ed4b5be47f7577c062858c0699 [file] [log] [blame]
Chris Lattner14999342004-01-10 19:07:06 +00001//===-- Writer.cpp - Library for writing LLVM bytecode files --------------===//
John Criswellb576c942003-10-20 19:43:21 +00002//
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//===----------------------------------------------------------------------===//
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 Lattner83bb3d22004-01-14 23:36:54 +000022#include "llvm/Constants.h"
23#include "llvm/DerivedTypes.h"
Reid Spencerad89bd62004-07-25 18:07:36 +000024#include "llvm/Instructions.h"
Chris Lattner00950542001-06-06 20:29:01 +000025#include "llvm/Module.h"
Chris Lattner00950542001-06-06 20:29:01 +000026#include "llvm/SymbolTable.h"
Reid Spencerad89bd62004-07-25 18:07:36 +000027#include "llvm/Support/GetElementPtrTypeIterator.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000028#include "llvm/ADT/STLExtras.h"
29#include "llvm/ADT/Statistic.h"
Chris Lattner32abce62004-01-10 19:10:01 +000030#include <cstring>
Chris Lattner00950542001-06-06 20:29:01 +000031#include <algorithm>
Chris Lattner44f549b2004-01-10 18:49:43 +000032using namespace llvm;
Brian Gaeked0fde302003-11-11 22:41:34 +000033
Reid Spencer38d54be2004-08-17 07:45:14 +000034/// This value needs to be incremented every time the bytecode format changes
35/// so that the reader can distinguish which format of the bytecode file has
36/// been written.
37/// @brief The bytecode version number
38const unsigned BCVersionNum = 4;
39
Chris Lattner635cd932002-07-23 19:56:44 +000040static RegisterPass<WriteBytecodePass> X("emitbytecode", "Bytecode Writer");
41
Chris Lattnerce6ef112002-07-26 18:40:14 +000042static Statistic<>
Chris Lattnera92f6962002-10-01 22:38:41 +000043BytesWritten("bytecodewriter", "Number of bytecode bytes written");
Chris Lattner635cd932002-07-23 19:56:44 +000044
Reid Spencerad89bd62004-07-25 18:07:36 +000045//===----------------------------------------------------------------------===//
46//=== Output Primitives ===//
47//===----------------------------------------------------------------------===//
48
49// output - If a position is specified, it must be in the valid portion of the
50// string... note that this should be inlined always so only the relevant IF
51// body should be included.
52inline void BytecodeWriter::output(unsigned i, int pos) {
53 if (pos == -1) { // Be endian clean, little endian is our friend
54 Out.push_back((unsigned char)i);
55 Out.push_back((unsigned char)(i >> 8));
56 Out.push_back((unsigned char)(i >> 16));
57 Out.push_back((unsigned char)(i >> 24));
58 } else {
59 Out[pos ] = (unsigned char)i;
60 Out[pos+1] = (unsigned char)(i >> 8);
61 Out[pos+2] = (unsigned char)(i >> 16);
62 Out[pos+3] = (unsigned char)(i >> 24);
63 }
64}
65
66inline void BytecodeWriter::output(int i) {
67 output((unsigned)i);
68}
69
70/// output_vbr - Output an unsigned value, by using the least number of bytes
71/// possible. This is useful because many of our "infinite" values are really
72/// very small most of the time; but can be large a few times.
73/// Data format used: If you read a byte with the high bit set, use the low
Reid Spencer38d54be2004-08-17 07:45:14 +000074/// seven bits as data and then read another byte.
Reid Spencerad89bd62004-07-25 18:07:36 +000075inline void BytecodeWriter::output_vbr(uint64_t i) {
76 while (1) {
77 if (i < 0x80) { // done?
78 Out.push_back((unsigned char)i); // We know the high bit is clear...
79 return;
80 }
81
82 // Nope, we are bigger than a character, output the next 7 bits and set the
83 // high bit to say that there is more coming...
84 Out.push_back(0x80 | ((unsigned char)i & 0x7F));
85 i >>= 7; // Shift out 7 bits now...
86 }
87}
88
89inline void BytecodeWriter::output_vbr(unsigned i) {
90 while (1) {
91 if (i < 0x80) { // done?
92 Out.push_back((unsigned char)i); // We know the high bit is clear...
93 return;
94 }
95
96 // Nope, we are bigger than a character, output the next 7 bits and set the
97 // high bit to say that there is more coming...
98 Out.push_back(0x80 | ((unsigned char)i & 0x7F));
99 i >>= 7; // Shift out 7 bits now...
100 }
101}
102
103inline void BytecodeWriter::output_typeid(unsigned i) {
104 if (i <= 0x00FFFFFF)
105 this->output_vbr(i);
106 else {
107 this->output_vbr(0x00FFFFFF);
108 this->output_vbr(i);
109 }
110}
111
112inline void BytecodeWriter::output_vbr(int64_t i) {
113 if (i < 0)
114 output_vbr(((uint64_t)(-i) << 1) | 1); // Set low order sign bit...
115 else
116 output_vbr((uint64_t)i << 1); // Low order bit is clear.
117}
118
119
120inline void BytecodeWriter::output_vbr(int i) {
121 if (i < 0)
122 output_vbr(((unsigned)(-i) << 1) | 1); // Set low order sign bit...
123 else
124 output_vbr((unsigned)i << 1); // Low order bit is clear.
125}
126
Reid Spencer38d54be2004-08-17 07:45:14 +0000127inline void BytecodeWriter::output(const std::string &s) {
Reid Spencerad89bd62004-07-25 18:07:36 +0000128 unsigned Len = s.length();
129 output_vbr(Len ); // Strings may have an arbitrary length...
130 Out.insert(Out.end(), s.begin(), s.end());
Reid Spencerad89bd62004-07-25 18:07:36 +0000131}
132
133inline void BytecodeWriter::output_data(const void *Ptr, const void *End) {
134 Out.insert(Out.end(), (const unsigned char*)Ptr, (const unsigned char*)End);
135}
136
137inline void BytecodeWriter::output_float(float& FloatVal) {
138 /// FIXME: This isn't optimal, it has size problems on some platforms
139 /// where FP is not IEEE.
140 union {
141 float f;
142 uint32_t i;
143 } FloatUnion;
144 FloatUnion.f = FloatVal;
145 Out.push_back( static_cast<unsigned char>( (FloatUnion.i & 0xFF )));
146 Out.push_back( static_cast<unsigned char>( (FloatUnion.i >> 8) & 0xFF));
147 Out.push_back( static_cast<unsigned char>( (FloatUnion.i >> 16) & 0xFF));
148 Out.push_back( static_cast<unsigned char>( (FloatUnion.i >> 24) & 0xFF));
149}
150
151inline void BytecodeWriter::output_double(double& DoubleVal) {
152 /// FIXME: This isn't optimal, it has size problems on some platforms
153 /// where FP is not IEEE.
154 union {
155 double d;
156 uint64_t i;
157 } DoubleUnion;
158 DoubleUnion.d = DoubleVal;
159 Out.push_back( static_cast<unsigned char>( (DoubleUnion.i & 0xFF )));
160 Out.push_back( static_cast<unsigned char>( (DoubleUnion.i >> 8) & 0xFF));
161 Out.push_back( static_cast<unsigned char>( (DoubleUnion.i >> 16) & 0xFF));
162 Out.push_back( static_cast<unsigned char>( (DoubleUnion.i >> 24) & 0xFF));
163 Out.push_back( static_cast<unsigned char>( (DoubleUnion.i >> 32) & 0xFF));
164 Out.push_back( static_cast<unsigned char>( (DoubleUnion.i >> 40) & 0xFF));
165 Out.push_back( static_cast<unsigned char>( (DoubleUnion.i >> 48) & 0xFF));
166 Out.push_back( static_cast<unsigned char>( (DoubleUnion.i >> 56) & 0xFF));
167}
168
169inline 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
Chris Lattnerb0bf6642004-10-14 01:35:17 +0000182inline BytecodeBlock::~BytecodeBlock() { // Do backpatch when block goes out
183 // of scope...
Reid Spencerad89bd62004-07-25 18:07:36 +0000184 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
Reid Spencerad89bd62004-07-25 18:07:36 +0000191 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));
Reid Spencerad89bd62004-07-25 18:07:36 +0000195}
196
197//===----------------------------------------------------------------------===//
198//=== Constant Output ===//
199//===----------------------------------------------------------------------===//
200
201void BytecodeWriter::outputType(const Type *T) {
202 output_vbr((unsigned)T->getTypeID());
203
204 // That's all there is to handling primitive types...
205 if (T->isPrimitiveType()) {
206 return; // We might do this if we alias a prim type: %x = type int
207 }
208
209 switch (T->getTypeID()) { // Handle derived types now.
210 case Type::FunctionTyID: {
211 const FunctionType *MT = cast<FunctionType>(T);
212 int Slot = Table.getSlot(MT->getReturnType());
213 assert(Slot != -1 && "Type used but not available!!");
214 output_typeid((unsigned)Slot);
215
216 // Output the number of arguments to function (+1 if varargs):
217 output_vbr((unsigned)MT->getNumParams()+MT->isVarArg());
218
219 // Output all of the arguments...
220 FunctionType::param_iterator I = MT->param_begin();
221 for (; I != MT->param_end(); ++I) {
222 Slot = Table.getSlot(*I);
223 assert(Slot != -1 && "Type used but not available!!");
224 output_typeid((unsigned)Slot);
225 }
226
227 // Terminate list with VoidTy if we are a varargs function...
228 if (MT->isVarArg())
229 output_typeid((unsigned)Type::VoidTyID);
230 break;
231 }
232
233 case Type::ArrayTyID: {
234 const ArrayType *AT = cast<ArrayType>(T);
235 int Slot = Table.getSlot(AT->getElementType());
236 assert(Slot != -1 && "Type used but not available!!");
237 output_typeid((unsigned)Slot);
Reid Spencerad89bd62004-07-25 18:07:36 +0000238 output_vbr(AT->getNumElements());
239 break;
240 }
241
Brian Gaeke715c90b2004-08-20 06:00:58 +0000242 case Type::PackedTyID: {
243 const PackedType *PT = cast<PackedType>(T);
244 int Slot = Table.getSlot(PT->getElementType());
245 assert(Slot != -1 && "Type used but not available!!");
246 output_typeid((unsigned)Slot);
247 output_vbr(PT->getNumElements());
248 break;
249 }
250
251
Reid Spencerad89bd62004-07-25 18:07:36 +0000252 case Type::StructTyID: {
253 const StructType *ST = cast<StructType>(T);
254
255 // Output all of the element types...
256 for (StructType::element_iterator I = ST->element_begin(),
257 E = ST->element_end(); I != E; ++I) {
258 int Slot = Table.getSlot(*I);
259 assert(Slot != -1 && "Type used but not available!!");
260 output_typeid((unsigned)Slot);
261 }
262
263 // Terminate list with VoidTy
264 output_typeid((unsigned)Type::VoidTyID);
265 break;
266 }
267
268 case Type::PointerTyID: {
269 const PointerType *PT = cast<PointerType>(T);
270 int Slot = Table.getSlot(PT->getElementType());
271 assert(Slot != -1 && "Type used but not available!!");
272 output_typeid((unsigned)Slot);
273 break;
274 }
275
Chris Lattnerb0bf6642004-10-14 01:35:17 +0000276 case Type::OpaqueTyID:
Reid Spencerad89bd62004-07-25 18:07:36 +0000277 // No need to emit anything, just the count of opaque types is enough.
278 break;
Reid Spencerad89bd62004-07-25 18:07:36 +0000279
Reid Spencerad89bd62004-07-25 18:07:36 +0000280 default:
281 std::cerr << __FILE__ << ":" << __LINE__ << ": Don't know how to serialize"
282 << " Type '" << T->getDescription() << "'\n";
283 break;
284 }
285}
286
287void BytecodeWriter::outputConstant(const Constant *CPV) {
288 assert((CPV->getType()->isPrimitiveType() || !CPV->isNullValue()) &&
289 "Shouldn't output null constants!");
290
291 // We must check for a ConstantExpr before switching by type because
292 // a ConstantExpr can be of any type, and has no explicit value.
293 //
294 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CPV)) {
295 // FIXME: Encoding of constant exprs could be much more compact!
296 assert(CE->getNumOperands() > 0 && "ConstantExpr with 0 operands");
297 output_vbr(CE->getNumOperands()); // flags as an expr
298 output_vbr(CE->getOpcode()); // flags as an expr
299
300 for (User::const_op_iterator OI = CE->op_begin(); OI != CE->op_end(); ++OI){
301 int Slot = Table.getSlot(*OI);
302 assert(Slot != -1 && "Unknown constant used in ConstantExpr!!");
303 output_vbr((unsigned)Slot);
304 Slot = Table.getSlot((*OI)->getType());
305 output_typeid((unsigned)Slot);
306 }
307 return;
308 } else {
309 output_vbr(0U); // flag as not a ConstantExpr
310 }
311
312 switch (CPV->getType()->getTypeID()) {
313 case Type::BoolTyID: // Boolean Types
314 if (cast<ConstantBool>(CPV)->getValue())
315 output_vbr(1U);
316 else
317 output_vbr(0U);
318 break;
319
320 case Type::UByteTyID: // Unsigned integer types...
321 case Type::UShortTyID:
322 case Type::UIntTyID:
323 case Type::ULongTyID:
324 output_vbr(cast<ConstantUInt>(CPV)->getValue());
325 break;
326
327 case Type::SByteTyID: // Signed integer types...
328 case Type::ShortTyID:
329 case Type::IntTyID:
330 case Type::LongTyID:
331 output_vbr(cast<ConstantSInt>(CPV)->getValue());
332 break;
333
334 case Type::ArrayTyID: {
335 const ConstantArray *CPA = cast<ConstantArray>(CPV);
336 assert(!CPA->isString() && "Constant strings should be handled specially!");
337
Alkis Evlogimenos15876bb2004-08-04 08:44:43 +0000338 for (unsigned i = 0, e = CPA->getNumOperands(); i != e; ++i) {
Reid Spencerad89bd62004-07-25 18:07:36 +0000339 int Slot = Table.getSlot(CPA->getOperand(i));
340 assert(Slot != -1 && "Constant used but not available!!");
341 output_vbr((unsigned)Slot);
342 }
343 break;
344 }
345
Brian Gaeke715c90b2004-08-20 06:00:58 +0000346 case Type::PackedTyID: {
347 const ConstantPacked *CP = cast<ConstantPacked>(CPV);
348
349 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i) {
350 int Slot = Table.getSlot(CP->getOperand(i));
351 assert(Slot != -1 && "Constant used but not available!!");
352 output_vbr((unsigned)Slot);
353 }
354 break;
355 }
356
Reid Spencerad89bd62004-07-25 18:07:36 +0000357 case Type::StructTyID: {
358 const ConstantStruct *CPS = cast<ConstantStruct>(CPV);
Reid Spencerad89bd62004-07-25 18:07:36 +0000359
Alkis Evlogimenos15876bb2004-08-04 08:44:43 +0000360 for (unsigned i = 0, e = CPS->getNumOperands(); i != e; ++i) {
361 int Slot = Table.getSlot(CPS->getOperand(i));
Reid Spencerad89bd62004-07-25 18:07:36 +0000362 assert(Slot != -1 && "Constant used but not available!!");
363 output_vbr((unsigned)Slot);
364 }
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 std::cerr << __FILE__ << ":" << __LINE__ << ": Don't know how to serialize"
387 << " type '" << *CPV->getType() << "'\n";
388 break;
389 }
390 return;
391}
392
393void BytecodeWriter::outputConstantStrings() {
394 SlotCalculator::string_iterator I = Table.string_begin();
395 SlotCalculator::string_iterator E = Table.string_end();
396 if (I == E) return; // No strings to emit
397
398 // If we have != 0 strings to emit, output them now. Strings are emitted into
399 // the 'void' type plane.
400 output_vbr(unsigned(E-I));
401 output_typeid(Type::VoidTyID);
402
403 // Emit all of the strings.
404 for (I = Table.string_begin(); I != E; ++I) {
405 const ConstantArray *Str = *I;
406 int Slot = Table.getSlot(Str->getType());
407 assert(Slot != -1 && "Constant string of unknown type?");
408 output_typeid((unsigned)Slot);
409
410 // Now that we emitted the type (which indicates the size of the string),
411 // emit all of the characters.
412 std::string Val = Str->getAsString();
413 output_data(Val.c_str(), Val.c_str()+Val.size());
414 }
415}
416
417//===----------------------------------------------------------------------===//
418//=== Instruction Output ===//
419//===----------------------------------------------------------------------===//
420typedef unsigned char uchar;
421
422// outputInstructionFormat0 - Output those wierd instructions that have a large
423// number of operands or have large operands themselves...
424//
425// Format: [opcode] [type] [numargs] [arg0] [arg1] ... [arg<numargs-1>]
426//
Chris Lattnerf9d71782004-10-14 01:46:07 +0000427void BytecodeWriter::outputInstructionFormat0(const Instruction *I,
428 unsigned Opcode,
429 const SlotCalculator &Table,
430 unsigned Type) {
Reid Spencerad89bd62004-07-25 18:07:36 +0000431 // Opcode must have top two bits clear...
432 output_vbr(Opcode << 2); // Instruction Opcode ID
433 output_typeid(Type); // Result type
434
435 unsigned NumArgs = I->getNumOperands();
436 output_vbr(NumArgs + (isa<CastInst>(I) || isa<VANextInst>(I) ||
437 isa<VAArgInst>(I)));
438
439 if (!isa<GetElementPtrInst>(&I)) {
440 for (unsigned i = 0; i < NumArgs; ++i) {
441 int Slot = Table.getSlot(I->getOperand(i));
442 assert(Slot >= 0 && "No slot number for value!?!?");
443 output_vbr((unsigned)Slot);
444 }
445
446 if (isa<CastInst>(I) || isa<VAArgInst>(I)) {
447 int Slot = Table.getSlot(I->getType());
448 assert(Slot != -1 && "Cast return type unknown?");
449 output_typeid((unsigned)Slot);
450 } else if (const VANextInst *VAI = dyn_cast<VANextInst>(I)) {
451 int Slot = Table.getSlot(VAI->getArgType());
452 assert(Slot != -1 && "VarArg argument type unknown?");
453 output_typeid((unsigned)Slot);
454 }
455
456 } else {
457 int Slot = Table.getSlot(I->getOperand(0));
458 assert(Slot >= 0 && "No slot number for value!?!?");
459 output_vbr(unsigned(Slot));
460
461 // We need to encode the type of sequential type indices into their slot #
462 unsigned Idx = 1;
463 for (gep_type_iterator TI = gep_type_begin(I), E = gep_type_end(I);
464 Idx != NumArgs; ++TI, ++Idx) {
465 Slot = Table.getSlot(I->getOperand(Idx));
466 assert(Slot >= 0 && "No slot number for value!?!?");
467
468 if (isa<SequentialType>(*TI)) {
469 unsigned IdxId;
470 switch (I->getOperand(Idx)->getType()->getTypeID()) {
471 default: assert(0 && "Unknown index type!");
472 case Type::UIntTyID: IdxId = 0; break;
473 case Type::IntTyID: IdxId = 1; break;
474 case Type::ULongTyID: IdxId = 2; break;
475 case Type::LongTyID: IdxId = 3; break;
476 }
477 Slot = (Slot << 2) | IdxId;
478 }
479 output_vbr(unsigned(Slot));
480 }
481 }
Reid Spencerad89bd62004-07-25 18:07:36 +0000482}
483
484
485// outputInstrVarArgsCall - Output the absurdly annoying varargs function calls.
486// This are more annoying than most because the signature of the call does not
487// tell us anything about the types of the arguments in the varargs portion.
488// Because of this, we encode (as type 0) all of the argument types explicitly
489// before the argument value. This really sucks, but you shouldn't be using
490// varargs functions in your code! *death to printf*!
491//
492// Format: [opcode] [type] [numargs] [arg0] [arg1] ... [arg<numargs-1>]
493//
494void BytecodeWriter::outputInstrVarArgsCall(const Instruction *I,
495 unsigned Opcode,
496 const SlotCalculator &Table,
497 unsigned Type) {
498 assert(isa<CallInst>(I) || isa<InvokeInst>(I));
499 // Opcode must have top two bits clear...
500 output_vbr(Opcode << 2); // Instruction Opcode ID
501 output_typeid(Type); // Result type (varargs type)
502
503 const PointerType *PTy = cast<PointerType>(I->getOperand(0)->getType());
504 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
505 unsigned NumParams = FTy->getNumParams();
506
507 unsigned NumFixedOperands;
508 if (isa<CallInst>(I)) {
509 // Output an operand for the callee and each fixed argument, then two for
510 // each variable argument.
511 NumFixedOperands = 1+NumParams;
512 } else {
513 assert(isa<InvokeInst>(I) && "Not call or invoke??");
514 // Output an operand for the callee and destinations, then two for each
515 // variable argument.
516 NumFixedOperands = 3+NumParams;
517 }
518 output_vbr(2 * I->getNumOperands()-NumFixedOperands);
519
520 // The type for the function has already been emitted in the type field of the
521 // instruction. Just emit the slot # now.
522 for (unsigned i = 0; i != NumFixedOperands; ++i) {
523 int Slot = Table.getSlot(I->getOperand(i));
524 assert(Slot >= 0 && "No slot number for value!?!?");
525 output_vbr((unsigned)Slot);
526 }
527
528 for (unsigned i = NumFixedOperands, e = I->getNumOperands(); i != e; ++i) {
529 // Output Arg Type ID
530 int Slot = Table.getSlot(I->getOperand(i)->getType());
531 assert(Slot >= 0 && "No slot number for value!?!?");
532 output_typeid((unsigned)Slot);
533
534 // Output arg ID itself
535 Slot = Table.getSlot(I->getOperand(i));
536 assert(Slot >= 0 && "No slot number for value!?!?");
537 output_vbr((unsigned)Slot);
538 }
Reid Spencerad89bd62004-07-25 18:07:36 +0000539}
540
541
542// outputInstructionFormat1 - Output one operand instructions, knowing that no
543// operand index is >= 2^12.
544//
545inline void BytecodeWriter::outputInstructionFormat1(const Instruction *I,
546 unsigned Opcode,
547 unsigned *Slots,
548 unsigned Type) {
549 // bits Instruction format:
550 // --------------------------
551 // 01-00: Opcode type, fixed to 1.
552 // 07-02: Opcode
553 // 19-08: Resulting type plane
554 // 31-20: Operand #1 (if set to (2^12-1), then zero operands)
555 //
Chris Lattnerf9d71782004-10-14 01:46:07 +0000556 output(1 | (Opcode << 2) | (Type << 8) | (Slots[0] << 20));
Reid Spencerad89bd62004-07-25 18:07:36 +0000557}
558
559
560// outputInstructionFormat2 - Output two operand instructions, knowing that no
561// operand index is >= 2^8.
562//
563inline void BytecodeWriter::outputInstructionFormat2(const Instruction *I,
564 unsigned Opcode,
565 unsigned *Slots,
566 unsigned Type) {
567 // bits Instruction format:
568 // --------------------------
569 // 01-00: Opcode type, fixed to 2.
570 // 07-02: Opcode
571 // 15-08: Resulting type plane
572 // 23-16: Operand #1
573 // 31-24: Operand #2
574 //
Chris Lattnerf9d71782004-10-14 01:46:07 +0000575 output(2 | (Opcode << 2) | (Type << 8) | (Slots[0] << 16) | (Slots[1] << 24));
Reid Spencerad89bd62004-07-25 18:07:36 +0000576}
577
578
579// outputInstructionFormat3 - Output three operand instructions, knowing that no
580// operand index is >= 2^6.
581//
582inline void BytecodeWriter::outputInstructionFormat3(const Instruction *I,
583 unsigned Opcode,
584 unsigned *Slots,
585 unsigned Type) {
586 // bits Instruction format:
587 // --------------------------
588 // 01-00: Opcode type, fixed to 3.
589 // 07-02: Opcode
590 // 13-08: Resulting type plane
591 // 19-14: Operand #1
592 // 25-20: Operand #2
593 // 31-26: Operand #3
594 //
Chris Lattnerf9d71782004-10-14 01:46:07 +0000595 output(3 | (Opcode << 2) | (Type << 8) |
Chris Lattner84d1ced2004-10-14 01:57:28 +0000596 (Slots[0] << 14) | (Slots[1] << 20) | (Slots[2] << 26));
Reid Spencerad89bd62004-07-25 18:07:36 +0000597}
598
599void BytecodeWriter::outputInstruction(const Instruction &I) {
600 assert(I.getOpcode() < 62 && "Opcode too big???");
601 unsigned Opcode = I.getOpcode();
602 unsigned NumOperands = I.getNumOperands();
603
604 // Encode 'volatile load' as 62 and 'volatile store' as 63.
605 if (isa<LoadInst>(I) && cast<LoadInst>(I).isVolatile())
606 Opcode = 62;
607 if (isa<StoreInst>(I) && cast<StoreInst>(I).isVolatile())
608 Opcode = 63;
609
610 // Figure out which type to encode with the instruction. Typically we want
611 // the type of the first parameter, as opposed to the type of the instruction
612 // (for example, with setcc, we always know it returns bool, but the type of
613 // the first param is actually interesting). But if we have no arguments
614 // we take the type of the instruction itself.
615 //
616 const Type *Ty;
617 switch (I.getOpcode()) {
618 case Instruction::Select:
619 case Instruction::Malloc:
620 case Instruction::Alloca:
621 Ty = I.getType(); // These ALWAYS want to encode the return type
622 break;
623 case Instruction::Store:
624 Ty = I.getOperand(1)->getType(); // Encode the pointer type...
625 assert(isa<PointerType>(Ty) && "Store to nonpointer type!?!?");
626 break;
627 default: // Otherwise use the default behavior...
628 Ty = NumOperands ? I.getOperand(0)->getType() : I.getType();
629 break;
630 }
631
632 unsigned Type;
633 int Slot = Table.getSlot(Ty);
634 assert(Slot != -1 && "Type not available!!?!");
635 Type = (unsigned)Slot;
636
637 // Varargs calls and invokes are encoded entirely different from any other
638 // instructions.
639 if (const CallInst *CI = dyn_cast<CallInst>(&I)){
640 const PointerType *Ty =cast<PointerType>(CI->getCalledValue()->getType());
641 if (cast<FunctionType>(Ty->getElementType())->isVarArg()) {
642 outputInstrVarArgsCall(CI, Opcode, Table, Type);
643 return;
644 }
645 } else if (const InvokeInst *II = dyn_cast<InvokeInst>(&I)) {
646 const PointerType *Ty =cast<PointerType>(II->getCalledValue()->getType());
647 if (cast<FunctionType>(Ty->getElementType())->isVarArg()) {
648 outputInstrVarArgsCall(II, Opcode, Table, Type);
649 return;
650 }
651 }
652
653 if (NumOperands <= 3) {
654 // Make sure that we take the type number into consideration. We don't want
655 // to overflow the field size for the instruction format we select.
656 //
657 unsigned MaxOpSlot = Type;
658 unsigned Slots[3]; Slots[0] = (1 << 12)-1; // Marker to signify 0 operands
659
660 for (unsigned i = 0; i != NumOperands; ++i) {
661 int slot = Table.getSlot(I.getOperand(i));
662 assert(slot != -1 && "Broken bytecode!");
663 if (unsigned(slot) > MaxOpSlot) MaxOpSlot = unsigned(slot);
664 Slots[i] = unsigned(slot);
665 }
666
667 // Handle the special cases for various instructions...
668 if (isa<CastInst>(I) || isa<VAArgInst>(I)) {
669 // Cast has to encode the destination type as the second argument in the
670 // packet, or else we won't know what type to cast to!
671 Slots[1] = Table.getSlot(I.getType());
672 assert(Slots[1] != ~0U && "Cast return type unknown?");
673 if (Slots[1] > MaxOpSlot) MaxOpSlot = Slots[1];
674 NumOperands++;
675 } else if (const VANextInst *VANI = dyn_cast<VANextInst>(&I)) {
676 Slots[1] = Table.getSlot(VANI->getArgType());
677 assert(Slots[1] != ~0U && "va_next return type unknown?");
678 if (Slots[1] > MaxOpSlot) MaxOpSlot = Slots[1];
679 NumOperands++;
680 } else if (const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(&I)) {
681 // We need to encode the type of sequential type indices into their slot #
682 unsigned Idx = 1;
683 for (gep_type_iterator I = gep_type_begin(GEP), E = gep_type_end(GEP);
684 I != E; ++I, ++Idx)
685 if (isa<SequentialType>(*I)) {
686 unsigned IdxId;
687 switch (GEP->getOperand(Idx)->getType()->getTypeID()) {
688 default: assert(0 && "Unknown index type!");
689 case Type::UIntTyID: IdxId = 0; break;
690 case Type::IntTyID: IdxId = 1; break;
691 case Type::ULongTyID: IdxId = 2; break;
692 case Type::LongTyID: IdxId = 3; break;
693 }
694 Slots[Idx] = (Slots[Idx] << 2) | IdxId;
695 if (Slots[Idx] > MaxOpSlot) MaxOpSlot = Slots[Idx];
696 }
697 }
698
699 // Decide which instruction encoding to use. This is determined primarily
700 // by the number of operands, and secondarily by whether or not the max
701 // operand will fit into the instruction encoding. More operands == fewer
702 // bits per operand.
703 //
704 switch (NumOperands) {
705 case 0:
706 case 1:
707 if (MaxOpSlot < (1 << 12)-1) { // -1 because we use 4095 to indicate 0 ops
708 outputInstructionFormat1(&I, Opcode, Slots, Type);
709 return;
710 }
711 break;
712
713 case 2:
714 if (MaxOpSlot < (1 << 8)) {
715 outputInstructionFormat2(&I, Opcode, Slots, Type);
716 return;
717 }
718 break;
719
720 case 3:
721 if (MaxOpSlot < (1 << 6)) {
722 outputInstructionFormat3(&I, Opcode, Slots, Type);
723 return;
724 }
725 break;
726 default:
727 break;
728 }
729 }
730
731 // If we weren't handled before here, we either have a large number of
732 // operands or a large operand index that we are referring to.
733 outputInstructionFormat0(&I, Opcode, Table, Type);
734}
735
736//===----------------------------------------------------------------------===//
737//=== Block Output ===//
738//===----------------------------------------------------------------------===//
739
740BytecodeWriter::BytecodeWriter(std::vector<unsigned char> &o, const Module *M)
Reid Spencer798ff642004-05-26 07:37:11 +0000741 : Out(o), Table(M) {
Chris Lattner00950542001-06-06 20:29:01 +0000742
Chris Lattner83bb3d22004-01-14 23:36:54 +0000743 // Emit the signature...
744 static const unsigned char *Sig = (const unsigned char*)"llvm";
Reid Spencerad89bd62004-07-25 18:07:36 +0000745 output_data(Sig, Sig+4);
Chris Lattner00950542001-06-06 20:29:01 +0000746
747 // Emit the top level CLASS block.
Reid Spencerad89bd62004-07-25 18:07:36 +0000748 BytecodeBlock ModuleBlock(BytecodeFormat::ModuleBlockID, *this, false, true);
Chris Lattner00950542001-06-06 20:29:01 +0000749
Chris Lattnerd445c6b2003-08-24 13:47:36 +0000750 bool isBigEndian = M->getEndianness() == Module::BigEndian;
751 bool hasLongPointers = M->getPointerSize() == Module::Pointer64;
752 bool hasNoEndianness = M->getEndianness() == Module::AnyEndianness;
753 bool hasNoPointerSize = M->getPointerSize() == Module::AnyPointerSize;
Chris Lattner186a1f72003-03-19 20:56:46 +0000754
Chris Lattner5fa428f2004-04-05 01:27:26 +0000755 // Output the version identifier... we are currently on bytecode version #2,
756 // which corresponds to LLVM v1.3.
Reid Spencer38d54be2004-08-17 07:45:14 +0000757 unsigned Version = (BCVersionNum << 4) |
758 (unsigned)isBigEndian | (hasLongPointers << 1) |
759 (hasNoEndianness << 2) |
760 (hasNoPointerSize << 3);
Reid Spencerad89bd62004-07-25 18:07:36 +0000761 output_vbr(Version);
Chris Lattner00950542001-06-06 20:29:01 +0000762
Reid Spencercb3595c2004-07-04 11:45:47 +0000763 // The Global type plane comes first
Chris Lattner186a1f72003-03-19 20:56:46 +0000764 {
Reid Spencerad89bd62004-07-25 18:07:36 +0000765 BytecodeBlock CPool(BytecodeFormat::GlobalTypePlaneBlockID, *this );
Reid Spencercb3595c2004-07-04 11:45:47 +0000766 outputTypes(Type::FirstDerivedTyID);
Chris Lattner186a1f72003-03-19 20:56:46 +0000767 }
Chris Lattner00950542001-06-06 20:29:01 +0000768
Chris Lattner186a1f72003-03-19 20:56:46 +0000769 // The ModuleInfoBlock follows directly after the type information
Chris Lattnere8fdde12001-09-07 16:39:41 +0000770 outputModuleInfoBlock(M);
771
Chris Lattner186a1f72003-03-19 20:56:46 +0000772 // Output module level constants, used for global variable initializers
773 outputConstants(false);
774
Chris Lattnerb5794002002-04-07 22:49:37 +0000775 // Do the whole module now! Process each function at a time...
Chris Lattner0b12b5f2002-06-25 16:13:21 +0000776 for (Module::const_iterator I = M->begin(), E = M->end(); I != E; ++I)
Chris Lattner186a1f72003-03-19 20:56:46 +0000777 outputFunction(I);
Chris Lattnere8fdde12001-09-07 16:39:41 +0000778
779 // If needed, output the symbol table for the module...
Chris Lattner6e6026b2002-11-20 18:36:02 +0000780 outputSymbolTable(M->getSymbolTable());
Chris Lattner00950542001-06-06 20:29:01 +0000781}
782
Chris Lattnerf9d71782004-10-14 01:46:07 +0000783void BytecodeWriter::outputTypes(unsigned TypeNum) {
Reid Spencercb3595c2004-07-04 11:45:47 +0000784 // Write the type plane for types first because earlier planes (e.g. for a
785 // primitive type like float) may have constants constructed using types
786 // coming later (e.g., via getelementptr from a pointer type). The type
787 // plane is needed before types can be fwd or bkwd referenced.
788 const std::vector<const Type*>& Types = Table.getTypes();
789 assert(!Types.empty() && "No types at all?");
790 assert(TypeNum <= Types.size() && "Invalid TypeNo index");
791
792 unsigned NumEntries = Types.size() - TypeNum;
793
794 // Output type header: [num entries]
Reid Spencerad89bd62004-07-25 18:07:36 +0000795 output_vbr(NumEntries);
Reid Spencercb3595c2004-07-04 11:45:47 +0000796
797 for (unsigned i = TypeNum; i < TypeNum+NumEntries; ++i)
798 outputType(Types[i]);
799}
800
Vikram S. Advea7dac3d2002-07-14 23:07:51 +0000801// Helper function for outputConstants().
802// Writes out all the constants in the plane Plane starting at entry StartNo.
803//
804void BytecodeWriter::outputConstantsInPlane(const std::vector<const Value*>
805 &Plane, unsigned StartNo) {
806 unsigned ValNo = StartNo;
807
Chris Lattner83bb3d22004-01-14 23:36:54 +0000808 // Scan through and ignore function arguments, global values, and constant
809 // strings.
810 for (; ValNo < Plane.size() &&
811 (isa<Argument>(Plane[ValNo]) || isa<GlobalValue>(Plane[ValNo]) ||
812 (isa<ConstantArray>(Plane[ValNo]) &&
813 cast<ConstantArray>(Plane[ValNo])->isString())); ValNo++)
Vikram S. Advea7dac3d2002-07-14 23:07:51 +0000814 /*empty*/;
815
816 unsigned NC = ValNo; // Number of constants
Reid Spencercb3595c2004-07-04 11:45:47 +0000817 for (; NC < Plane.size() && (isa<Constant>(Plane[NC])); NC++)
Vikram S. Advea7dac3d2002-07-14 23:07:51 +0000818 /*empty*/;
819 NC -= ValNo; // Convert from index into count
820 if (NC == 0) return; // Skip empty type planes...
821
Chris Lattnerd6942d72004-01-14 16:54:21 +0000822 // FIXME: Most slabs only have 1 or 2 entries! We should encode this much
823 // more compactly.
824
Vikram S. Advea7dac3d2002-07-14 23:07:51 +0000825 // Output type header: [num entries][type id number]
826 //
Reid Spencerad89bd62004-07-25 18:07:36 +0000827 output_vbr(NC);
Vikram S. Advea7dac3d2002-07-14 23:07:51 +0000828
829 // Output the Type ID Number...
Alkis Evlogimenos60596382003-10-17 02:02:40 +0000830 int Slot = Table.getSlot(Plane.front()->getType());
Vikram S. Advea7dac3d2002-07-14 23:07:51 +0000831 assert (Slot != -1 && "Type in constant pool but not in function!!");
Reid Spencerad89bd62004-07-25 18:07:36 +0000832 output_typeid((unsigned)Slot);
Vikram S. Advea7dac3d2002-07-14 23:07:51 +0000833
Vikram S. Advea7dac3d2002-07-14 23:07:51 +0000834 for (unsigned i = ValNo; i < ValNo+NC; ++i) {
835 const Value *V = Plane[i];
Reid Spencere0125b62004-07-18 00:16:21 +0000836 if (const Constant *C = dyn_cast<Constant>(V)) {
837 outputConstant(C);
Vikram S. Advea7dac3d2002-07-14 23:07:51 +0000838 }
839 }
840}
841
Chris Lattner80b97342004-01-17 23:25:43 +0000842static inline bool hasNullValue(unsigned TyID) {
Reid Spencercb3595c2004-07-04 11:45:47 +0000843 return TyID != Type::LabelTyID && TyID != Type::VoidTyID;
Chris Lattner80b97342004-01-17 23:25:43 +0000844}
845
Chris Lattner79df7c02002-03-26 18:01:55 +0000846void BytecodeWriter::outputConstants(bool isFunction) {
Reid Spencerad89bd62004-07-25 18:07:36 +0000847 BytecodeBlock CPool(BytecodeFormat::ConstantPoolBlockID, *this,
Chris Lattner0baa0af2004-01-15 21:06:57 +0000848 true /* Elide block if empty */);
Chris Lattner00950542001-06-06 20:29:01 +0000849
850 unsigned NumPlanes = Table.getNumPlanes();
Chris Lattnerf69315b2003-05-22 18:35:38 +0000851
Reid Spencere0125b62004-07-18 00:16:21 +0000852 if (isFunction)
853 // Output the type plane before any constants!
Reid Spencercb3595c2004-07-04 11:45:47 +0000854 outputTypes( Table.getModuleTypeLevel() );
Reid Spencere0125b62004-07-18 00:16:21 +0000855 else
Chris Lattnerf9d71782004-10-14 01:46:07 +0000856 // Output module-level string constants before any other constants.
Chris Lattner83bb3d22004-01-14 23:36:54 +0000857 outputConstantStrings();
858
Reid Spencercb3595c2004-07-04 11:45:47 +0000859 for (unsigned pno = 0; pno != NumPlanes; pno++) {
860 const std::vector<const Value*> &Plane = Table.getPlane(pno);
861 if (!Plane.empty()) { // Skip empty type planes...
862 unsigned ValNo = 0;
863 if (isFunction) // Don't re-emit module constants
Reid Spencer0852c802004-07-04 11:46:15 +0000864 ValNo += Table.getModuleLevel(pno);
Reid Spencercb3595c2004-07-04 11:45:47 +0000865
866 if (hasNullValue(pno)) {
Reid Spencer0852c802004-07-04 11:46:15 +0000867 // Skip zero initializer
868 if (ValNo == 0)
869 ValNo = 1;
Chris Lattnerf69315b2003-05-22 18:35:38 +0000870 }
Reid Spencercb3595c2004-07-04 11:45:47 +0000871
872 // Write out constants in the plane
873 outputConstantsInPlane(Plane, ValNo);
Chris Lattnerf69315b2003-05-22 18:35:38 +0000874 }
Reid Spencercb3595c2004-07-04 11:45:47 +0000875 }
Chris Lattner00950542001-06-06 20:29:01 +0000876}
877
Chris Lattner6b252422003-10-16 18:28:50 +0000878static unsigned getEncodedLinkage(const GlobalValue *GV) {
879 switch (GV->getLinkage()) {
880 default: assert(0 && "Invalid linkage!");
881 case GlobalValue::ExternalLinkage: return 0;
Chris Lattner6b252422003-10-16 18:28:50 +0000882 case GlobalValue::WeakLinkage: return 1;
883 case GlobalValue::AppendingLinkage: return 2;
884 case GlobalValue::InternalLinkage: return 3;
Chris Lattner22482a12003-10-18 06:30:21 +0000885 case GlobalValue::LinkOnceLinkage: return 4;
Chris Lattner6b252422003-10-16 18:28:50 +0000886 }
887}
888
Chris Lattner00950542001-06-06 20:29:01 +0000889void BytecodeWriter::outputModuleInfoBlock(const Module *M) {
Reid Spencerad89bd62004-07-25 18:07:36 +0000890 BytecodeBlock ModuleInfoBlock(BytecodeFormat::ModuleGlobalInfoBlockID, *this);
Chris Lattner00950542001-06-06 20:29:01 +0000891
Chris Lattner70cc3392001-09-10 07:58:01 +0000892 // Output the types for the global variables in the module...
893 for (Module::const_giterator I = M->gbegin(), End = M->gend(); I != End;++I) {
Alkis Evlogimenos60596382003-10-17 02:02:40 +0000894 int Slot = Table.getSlot(I->getType());
Chris Lattner70cc3392001-09-10 07:58:01 +0000895 assert(Slot != -1 && "Module global vars is broken!");
Chris Lattnerd70684f2001-09-18 04:01:05 +0000896
Chris Lattner22482a12003-10-18 06:30:21 +0000897 // Fields: bit0 = isConstant, bit1 = hasInitializer, bit2-4=Linkage,
898 // bit5+ = Slot # for type
Chris Lattner84d1ced2004-10-14 01:57:28 +0000899 unsigned oSlot = ((unsigned)Slot << 6) | (getEncodedLinkage(I) << 2) |
Chris Lattner036de032004-06-25 20:52:10 +0000900 (I->hasInitializer() << 1) | (unsigned)I->isConstant();
Reid Spencerad89bd62004-07-25 18:07:36 +0000901 output_vbr(oSlot );
Chris Lattnerd70684f2001-09-18 04:01:05 +0000902
Chris Lattner1b98c5c2001-10-13 06:48:38 +0000903 // If we have an initializer, output it now.
Chris Lattner0b12b5f2002-06-25 16:13:21 +0000904 if (I->hasInitializer()) {
Alkis Evlogimenos60596382003-10-17 02:02:40 +0000905 Slot = Table.getSlot((Value*)I->getInitializer());
Chris Lattnerd70684f2001-09-18 04:01:05 +0000906 assert(Slot != -1 && "No slot for global var initializer!");
Reid Spencerad89bd62004-07-25 18:07:36 +0000907 output_vbr((unsigned)Slot);
Chris Lattnerd70684f2001-09-18 04:01:05 +0000908 }
Chris Lattner70cc3392001-09-10 07:58:01 +0000909 }
Reid Spencerad89bd62004-07-25 18:07:36 +0000910 output_typeid((unsigned)Table.getSlot(Type::VoidTy));
Chris Lattner70cc3392001-09-10 07:58:01 +0000911
Chris Lattnerb5794002002-04-07 22:49:37 +0000912 // Output the types of the functions in this module...
Chris Lattner7fc9fe32001-06-27 23:41:11 +0000913 for (Module::const_iterator I = M->begin(), End = M->end(); I != End; ++I) {
Alkis Evlogimenos60596382003-10-17 02:02:40 +0000914 int Slot = Table.getSlot(I->getType());
Chris Lattner00950542001-06-06 20:29:01 +0000915 assert(Slot != -1 && "Module const pool is broken!");
916 assert(Slot >= Type::FirstDerivedTyID && "Derived type not in range!");
Reid Spencerad89bd62004-07-25 18:07:36 +0000917 output_typeid((unsigned)Slot);
Chris Lattner00950542001-06-06 20:29:01 +0000918 }
Reid Spencerad89bd62004-07-25 18:07:36 +0000919 output_typeid((unsigned)Table.getSlot(Type::VoidTy));
920
921 // Put out the list of dependent libraries for the Module
Reid Spencer5ac88122004-07-25 21:32:02 +0000922 Module::lib_iterator LI = M->lib_begin();
923 Module::lib_iterator LE = M->lib_end();
Reid Spencerad89bd62004-07-25 18:07:36 +0000924 output_vbr( unsigned(LE - LI) ); // Put out the number of dependent libraries
925 for ( ; LI != LE; ++LI ) {
Reid Spencer38d54be2004-08-17 07:45:14 +0000926 output(*LI);
Reid Spencerad89bd62004-07-25 18:07:36 +0000927 }
928
929 // Output the target triple from the module
Reid Spencer38d54be2004-08-17 07:45:14 +0000930 output(M->getTargetTriple());
Chris Lattner00950542001-06-06 20:29:01 +0000931}
932
Chris Lattnercf3e67f2004-01-18 21:08:52 +0000933void BytecodeWriter::outputInstructions(const Function *F) {
Reid Spencerad89bd62004-07-25 18:07:36 +0000934 BytecodeBlock ILBlock(BytecodeFormat::InstructionListBlockID, *this);
Chris Lattnercf3e67f2004-01-18 21:08:52 +0000935 for (Function::const_iterator BB = F->begin(), E = F->end(); BB != E; ++BB)
936 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I!=E; ++I)
937 outputInstruction(*I);
Chris Lattnercf3e67f2004-01-18 21:08:52 +0000938}
939
Chris Lattner186a1f72003-03-19 20:56:46 +0000940void BytecodeWriter::outputFunction(const Function *F) {
Reid Spencerad89bd62004-07-25 18:07:36 +0000941 BytecodeBlock FunctionBlock(BytecodeFormat::FunctionBlockID, *this);
942 output_vbr(getEncodedLinkage(F));
Chris Lattnerd23b1d32001-11-26 18:56:10 +0000943
Chris Lattnercf3e67f2004-01-18 21:08:52 +0000944 // If this is an external function, there is nothing else to emit!
945 if (F->isExternal()) return;
Chris Lattner00950542001-06-06 20:29:01 +0000946
Chris Lattnercf3e67f2004-01-18 21:08:52 +0000947 // Get slot information about the function...
948 Table.incorporateFunction(F);
949
950 if (Table.getCompactionTable().empty()) {
951 // Output information about the constants in the function if the compaction
952 // table is not being used.
Chris Lattnere8fdde12001-09-07 16:39:41 +0000953 outputConstants(true);
Chris Lattnercf3e67f2004-01-18 21:08:52 +0000954 } else {
955 // Otherwise, emit the compaction table.
956 outputCompactionTable();
Chris Lattnere8fdde12001-09-07 16:39:41 +0000957 }
Chris Lattnercf3e67f2004-01-18 21:08:52 +0000958
959 // Output all of the instructions in the body of the function
960 outputInstructions(F);
961
962 // If needed, output the symbol table for the function...
963 outputSymbolTable(F->getSymbolTable());
964
965 Table.purgeFunction();
966}
967
968void BytecodeWriter::outputCompactionTablePlane(unsigned PlaneNo,
969 const std::vector<const Value*> &Plane,
970 unsigned StartNo) {
971 unsigned End = Table.getModuleLevel(PlaneNo);
Chris Lattner52f86d62004-01-20 00:54:06 +0000972 if (Plane.empty() || StartNo == End || End == 0) return; // Nothing to emit
Chris Lattnercf3e67f2004-01-18 21:08:52 +0000973 assert(StartNo < End && "Cannot emit negative range!");
974 assert(StartNo < Plane.size() && End <= Plane.size());
975
Chris Lattnercf3e67f2004-01-18 21:08:52 +0000976 // Do not emit the null initializer!
Reid Spencercb3595c2004-07-04 11:45:47 +0000977 ++StartNo;
Chris Lattnercf3e67f2004-01-18 21:08:52 +0000978
Chris Lattner24102432004-01-18 22:35:34 +0000979 // Figure out which encoding to use. By far the most common case we have is
980 // to emit 0-2 entries in a compaction table plane.
981 switch (End-StartNo) {
982 case 0: // Avoid emitting two vbr's if possible.
983 case 1:
984 case 2:
Reid Spencerad89bd62004-07-25 18:07:36 +0000985 output_vbr((PlaneNo << 2) | End-StartNo);
Chris Lattner24102432004-01-18 22:35:34 +0000986 break;
987 default:
988 // Output the number of things.
Reid Spencerad89bd62004-07-25 18:07:36 +0000989 output_vbr((unsigned(End-StartNo) << 2) | 3);
990 output_typeid(PlaneNo); // Emit the type plane this is
Chris Lattner24102432004-01-18 22:35:34 +0000991 break;
992 }
993
Chris Lattnercf3e67f2004-01-18 21:08:52 +0000994 for (unsigned i = StartNo; i != End; ++i)
Reid Spencerad89bd62004-07-25 18:07:36 +0000995 output_vbr(Table.getGlobalSlot(Plane[i]));
Chris Lattnercf3e67f2004-01-18 21:08:52 +0000996}
997
Reid Spencercb3595c2004-07-04 11:45:47 +0000998void BytecodeWriter::outputCompactionTypes(unsigned StartNo) {
999 // Get the compaction type table from the slot calculator
1000 const std::vector<const Type*> &CTypes = Table.getCompactionTypes();
1001
1002 // The compaction types may have been uncompactified back to the
1003 // global types. If so, we just write an empty table
1004 if (CTypes.size() == 0 ) {
Reid Spencerad89bd62004-07-25 18:07:36 +00001005 output_vbr(0U);
Reid Spencercb3595c2004-07-04 11:45:47 +00001006 return;
1007 }
1008
1009 assert(CTypes.size() >= StartNo && "Invalid compaction types start index");
1010
1011 // Determine how many types to write
1012 unsigned NumTypes = CTypes.size() - StartNo;
1013
1014 // Output the number of types.
Reid Spencerad89bd62004-07-25 18:07:36 +00001015 output_vbr(NumTypes);
Reid Spencercb3595c2004-07-04 11:45:47 +00001016
1017 for (unsigned i = StartNo; i < StartNo+NumTypes; ++i)
Reid Spencerad89bd62004-07-25 18:07:36 +00001018 output_typeid(Table.getGlobalSlot(CTypes[i]));
Reid Spencercb3595c2004-07-04 11:45:47 +00001019}
1020
Chris Lattnercf3e67f2004-01-18 21:08:52 +00001021void BytecodeWriter::outputCompactionTable() {
Reid Spencer0033c182004-08-27 00:38:44 +00001022 // Avoid writing the compaction table at all if there is no content.
1023 if (Table.getCompactionTypes().size() >= Type::FirstDerivedTyID ||
1024 (!Table.CompactionTableIsEmpty())) {
1025 BytecodeBlock CTB(BytecodeFormat::CompactionTableBlockID, *this,
1026 true/*ElideIfEmpty*/);
Chris Lattnerf9d71782004-10-14 01:46:07 +00001027 const std::vector<std::vector<const Value*> > &CT =
1028 Table.getCompactionTable();
Reid Spencer0033c182004-08-27 00:38:44 +00001029
1030 // First things first, emit the type compaction table if there is one.
1031 outputCompactionTypes(Type::FirstDerivedTyID);
Chris Lattnercf3e67f2004-01-18 21:08:52 +00001032
Reid Spencer0033c182004-08-27 00:38:44 +00001033 for (unsigned i = 0, e = CT.size(); i != e; ++i)
1034 outputCompactionTablePlane(i, CT[i], 0);
1035 }
Chris Lattner00950542001-06-06 20:29:01 +00001036}
1037
Chris Lattner00950542001-06-06 20:29:01 +00001038void BytecodeWriter::outputSymbolTable(const SymbolTable &MST) {
Chris Lattner737d3cd2004-01-10 19:56:59 +00001039 // Do not output the Bytecode block for an empty symbol table, it just wastes
1040 // space!
Chris Lattnerf9d71782004-10-14 01:46:07 +00001041 if (MST.isEmpty()) return;
Chris Lattner737d3cd2004-01-10 19:56:59 +00001042
Reid Spencerad89bd62004-07-25 18:07:36 +00001043 BytecodeBlock SymTabBlock(BytecodeFormat::SymbolTableBlockID, *this,
Chris Lattnerf9d71782004-10-14 01:46:07 +00001044 true/*ElideIfEmpty*/);
Chris Lattner00950542001-06-06 20:29:01 +00001045
Reid Spencer250c4182004-08-17 02:59:02 +00001046 // Write the number of types
Reid Spencerad89bd62004-07-25 18:07:36 +00001047 output_vbr(MST.num_types());
Reid Spencer250c4182004-08-17 02:59:02 +00001048
1049 // Write each of the types
Reid Spencer94f2df22004-05-25 17:29:59 +00001050 for (SymbolTable::type_const_iterator TI = MST.type_begin(),
1051 TE = MST.type_end(); TI != TE; ++TI ) {
Reid Spencer250c4182004-08-17 02:59:02 +00001052 // Symtab entry:[def slot #][name]
Reid Spencerad89bd62004-07-25 18:07:36 +00001053 output_typeid((unsigned)Table.getSlot(TI->second));
Reid Spencer38d54be2004-08-17 07:45:14 +00001054 output(TI->first);
Reid Spencer94f2df22004-05-25 17:29:59 +00001055 }
1056
1057 // Now do each of the type planes in order.
1058 for (SymbolTable::plane_const_iterator PI = MST.plane_begin(),
1059 PE = MST.plane_end(); PI != PE; ++PI) {
1060 SymbolTable::value_const_iterator I = MST.value_begin(PI->first);
1061 SymbolTable::value_const_iterator End = MST.value_end(PI->first);
Chris Lattner00950542001-06-06 20:29:01 +00001062 int Slot;
1063
1064 if (I == End) continue; // Don't mess with an absent type...
1065
Reid Spencer250c4182004-08-17 02:59:02 +00001066 // Write the number of values in this plane
Reid Spencerad89bd62004-07-25 18:07:36 +00001067 output_vbr(MST.type_size(PI->first));
Chris Lattner00950542001-06-06 20:29:01 +00001068
Reid Spencer250c4182004-08-17 02:59:02 +00001069 // Write the slot number of the type for this plane
Reid Spencer94f2df22004-05-25 17:29:59 +00001070 Slot = Table.getSlot(PI->first);
Chris Lattner00950542001-06-06 20:29:01 +00001071 assert(Slot != -1 && "Type in symtab, but not in table!");
Reid Spencerad89bd62004-07-25 18:07:36 +00001072 output_typeid((unsigned)Slot);
Chris Lattner00950542001-06-06 20:29:01 +00001073
Reid Spencer250c4182004-08-17 02:59:02 +00001074 // Write each of the values in this plane
Chris Lattner7fc9fe32001-06-27 23:41:11 +00001075 for (; I != End; ++I) {
Chris Lattner00950542001-06-06 20:29:01 +00001076 // Symtab entry: [def slot #][name]
Alkis Evlogimenos60596382003-10-17 02:02:40 +00001077 Slot = Table.getSlot(I->second);
Chris Lattnere8fdde12001-09-07 16:39:41 +00001078 assert(Slot != -1 && "Value in symtab but has no slot number!!");
Reid Spencerad89bd62004-07-25 18:07:36 +00001079 output_vbr((unsigned)Slot);
Reid Spencer38d54be2004-08-17 07:45:14 +00001080 output(I->first);
Chris Lattner00950542001-06-06 20:29:01 +00001081 }
1082 }
1083}
1084
Reid Spencerad89bd62004-07-25 18:07:36 +00001085void llvm::WriteBytecodeToFile(const Module *M, std::ostream &Out) {
1086 assert(M && "You can't write a null module!!");
Chris Lattner00950542001-06-06 20:29:01 +00001087
Reid Spencerad89bd62004-07-25 18:07:36 +00001088 std::vector<unsigned char> Buffer;
1089 Buffer.reserve(64 * 1024); // avoid lots of little reallocs
Chris Lattner00950542001-06-06 20:29:01 +00001090
1091 // This object populates buffer for us...
Reid Spencerad89bd62004-07-25 18:07:36 +00001092 BytecodeWriter BCW(Buffer, M);
Chris Lattner00950542001-06-06 20:29:01 +00001093
Chris Lattnerce6ef112002-07-26 18:40:14 +00001094 // Keep track of how much we've written...
1095 BytesWritten += Buffer.size();
1096
Chris Lattnere8fdde12001-09-07 16:39:41 +00001097 // Okay, write the deque out to the ostream now... the deque is not
1098 // sequential in memory, however, so write out as much as possible in big
1099 // chunks, until we're done.
1100 //
Chris Lattnerf9d71782004-10-14 01:46:07 +00001101 for (std::vector<unsigned char>::const_iterator I = Buffer.begin(),
Chris Lattner823cacc2004-10-14 02:06:48 +00001102 E = Buffer.end(); I != E; ) {
Chris Lattnere8fdde12001-09-07 16:39:41 +00001103 // Scan to see how big this chunk is...
1104 const unsigned char *ChunkPtr = &*I;
1105 const unsigned char *LastPtr = ChunkPtr;
1106 while (I != E) {
1107 const unsigned char *ThisPtr = &*++I;
Chris Lattner036de032004-06-25 20:52:10 +00001108 if (++LastPtr != ThisPtr) // Advanced by more than a byte of memory?
Chris Lattner5cb17412001-11-04 21:32:41 +00001109 break;
Chris Lattnere8fdde12001-09-07 16:39:41 +00001110 }
1111
1112 // Write out the chunk...
Chris Lattnerd6162282004-06-25 00:35:55 +00001113 Out.write((char*)ChunkPtr, unsigned(LastPtr-ChunkPtr));
Chris Lattnere8fdde12001-09-07 16:39:41 +00001114 }
Chris Lattner00950542001-06-06 20:29:01 +00001115 Out.flush();
1116}
Reid Spencere0125b62004-07-18 00:16:21 +00001117
1118// vim: sw=2 ai