blob: 90cfa96462a9445497f729ecbf88ed66edd903dd [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"
Reid Spencer551ccae2004-09-01 22:55:40 +000030#include "llvm/ADT/STLExtras.h"
31#include "llvm/ADT/Statistic.h"
Chris Lattner32abce62004-01-10 19:10:01 +000032#include <cstring>
Chris Lattner00950542001-06-06 20:29:01 +000033#include <algorithm>
Chris Lattner44f549b2004-01-10 18:49:43 +000034using namespace llvm;
Brian Gaeked0fde302003-11-11 22:41:34 +000035
Reid Spencer38d54be2004-08-17 07:45:14 +000036/// This value needs to be incremented every time the bytecode format changes
37/// so that the reader can distinguish which format of the bytecode file has
38/// been written.
39/// @brief The bytecode version number
Chris Lattnera79e7cc2004-10-16 18:18:16 +000040const unsigned BCVersionNum = 5;
Reid Spencer38d54be2004-08-17 07:45:14 +000041
Chris Lattner635cd932002-07-23 19:56:44 +000042static RegisterPass<WriteBytecodePass> X("emitbytecode", "Bytecode Writer");
43
Misha Brukman23c6d2c2005-04-21 21:48:46 +000044static Statistic<>
Chris Lattnera92f6962002-10-01 22:38:41 +000045BytesWritten("bytecodewriter", "Number of bytecode bytes written");
Chris Lattner635cd932002-07-23 19:56:44 +000046
Reid Spencerad89bd62004-07-25 18:07:36 +000047//===----------------------------------------------------------------------===//
48//=== Output Primitives ===//
49//===----------------------------------------------------------------------===//
50
51// output - If a position is specified, it must be in the valid portion of the
Misha Brukman23c6d2c2005-04-21 21:48:46 +000052// string... note that this should be inlined always so only the relevant IF
Reid Spencerad89bd62004-07-25 18:07:36 +000053// body should be included.
54inline void BytecodeWriter::output(unsigned i, int pos) {
55 if (pos == -1) { // Be endian clean, little endian is our friend
Misha Brukman23c6d2c2005-04-21 21:48:46 +000056 Out.push_back((unsigned char)i);
Reid Spencerad89bd62004-07-25 18:07:36 +000057 Out.push_back((unsigned char)(i >> 8));
58 Out.push_back((unsigned char)(i >> 16));
59 Out.push_back((unsigned char)(i >> 24));
60 } else {
61 Out[pos ] = (unsigned char)i;
62 Out[pos+1] = (unsigned char)(i >> 8);
63 Out[pos+2] = (unsigned char)(i >> 16);
64 Out[pos+3] = (unsigned char)(i >> 24);
65 }
66}
67
68inline void BytecodeWriter::output(int i) {
69 output((unsigned)i);
70}
71
72/// output_vbr - Output an unsigned value, by using the least number of bytes
73/// possible. This is useful because many of our "infinite" values are really
74/// very small most of the time; but can be large a few times.
Misha Brukman23c6d2c2005-04-21 21:48:46 +000075/// Data format used: If you read a byte with the high bit set, use the low
76/// seven bits as data and then read another byte.
Reid Spencerad89bd62004-07-25 18:07:36 +000077inline void BytecodeWriter::output_vbr(uint64_t i) {
78 while (1) {
79 if (i < 0x80) { // done?
80 Out.push_back((unsigned char)i); // We know the high bit is clear...
81 return;
82 }
Misha Brukman23c6d2c2005-04-21 21:48:46 +000083
Reid Spencerad89bd62004-07-25 18:07:36 +000084 // Nope, we are bigger than a character, output the next 7 bits and set the
85 // high bit to say that there is more coming...
86 Out.push_back(0x80 | ((unsigned char)i & 0x7F));
87 i >>= 7; // Shift out 7 bits now...
88 }
89}
90
91inline void BytecodeWriter::output_vbr(unsigned i) {
92 while (1) {
93 if (i < 0x80) { // done?
94 Out.push_back((unsigned char)i); // We know the high bit is clear...
95 return;
96 }
Misha Brukman23c6d2c2005-04-21 21:48:46 +000097
Reid Spencerad89bd62004-07-25 18:07:36 +000098 // Nope, we are bigger than a character, output the next 7 bits and set the
99 // high bit to say that there is more coming...
100 Out.push_back(0x80 | ((unsigned char)i & 0x7F));
101 i >>= 7; // Shift out 7 bits now...
102 }
103}
104
105inline void BytecodeWriter::output_typeid(unsigned i) {
106 if (i <= 0x00FFFFFF)
107 this->output_vbr(i);
108 else {
109 this->output_vbr(0x00FFFFFF);
110 this->output_vbr(i);
111 }
112}
113
114inline void BytecodeWriter::output_vbr(int64_t i) {
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000115 if (i < 0)
Reid Spencerad89bd62004-07-25 18:07:36 +0000116 output_vbr(((uint64_t)(-i) << 1) | 1); // Set low order sign bit...
117 else
118 output_vbr((uint64_t)i << 1); // Low order bit is clear.
119}
120
121
122inline void BytecodeWriter::output_vbr(int i) {
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000123 if (i < 0)
Reid Spencerad89bd62004-07-25 18:07:36 +0000124 output_vbr(((unsigned)(-i) << 1) | 1); // Set low order sign bit...
125 else
126 output_vbr((unsigned)i << 1); // Low order bit is clear.
127}
128
Reid Spencer38d54be2004-08-17 07:45:14 +0000129inline void BytecodeWriter::output(const std::string &s) {
Reid Spencerad89bd62004-07-25 18:07:36 +0000130 unsigned Len = s.length();
131 output_vbr(Len ); // Strings may have an arbitrary length...
132 Out.insert(Out.end(), s.begin(), s.end());
Reid Spencerad89bd62004-07-25 18:07:36 +0000133}
134
135inline void BytecodeWriter::output_data(const void *Ptr, const void *End) {
136 Out.insert(Out.end(), (const unsigned char*)Ptr, (const unsigned char*)End);
137}
138
139inline void BytecodeWriter::output_float(float& FloatVal) {
140 /// FIXME: This isn't optimal, it has size problems on some platforms
141 /// where FP is not IEEE.
142 union {
143 float f;
144 uint32_t i;
145 } FloatUnion;
146 FloatUnion.f = FloatVal;
147 Out.push_back( static_cast<unsigned char>( (FloatUnion.i & 0xFF )));
148 Out.push_back( static_cast<unsigned char>( (FloatUnion.i >> 8) & 0xFF));
149 Out.push_back( static_cast<unsigned char>( (FloatUnion.i >> 16) & 0xFF));
150 Out.push_back( static_cast<unsigned char>( (FloatUnion.i >> 24) & 0xFF));
151}
152
153inline void BytecodeWriter::output_double(double& DoubleVal) {
154 /// FIXME: This isn't optimal, it has size problems on some platforms
155 /// where FP is not IEEE.
156 union {
157 double d;
158 uint64_t i;
159 } DoubleUnion;
160 DoubleUnion.d = DoubleVal;
161 Out.push_back( static_cast<unsigned char>( (DoubleUnion.i & 0xFF )));
162 Out.push_back( static_cast<unsigned char>( (DoubleUnion.i >> 8) & 0xFF));
163 Out.push_back( static_cast<unsigned char>( (DoubleUnion.i >> 16) & 0xFF));
164 Out.push_back( static_cast<unsigned char>( (DoubleUnion.i >> 24) & 0xFF));
165 Out.push_back( static_cast<unsigned char>( (DoubleUnion.i >> 32) & 0xFF));
166 Out.push_back( static_cast<unsigned char>( (DoubleUnion.i >> 40) & 0xFF));
167 Out.push_back( static_cast<unsigned char>( (DoubleUnion.i >> 48) & 0xFF));
168 Out.push_back( static_cast<unsigned char>( (DoubleUnion.i >> 56) & 0xFF));
169}
170
171inline BytecodeBlock::BytecodeBlock(unsigned ID, BytecodeWriter& w,
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000172 bool elideIfEmpty, bool hasLongFormat )
Reid Spencerad89bd62004-07-25 18:07:36 +0000173 : Id(ID), Writer(w), ElideIfEmpty(elideIfEmpty), HasLongFormat(hasLongFormat){
174
175 if (HasLongFormat) {
176 w.output(ID);
177 w.output(0U); // For length in long format
178 } else {
179 w.output(0U); /// Place holder for ID and length for this block
180 }
181 Loc = w.size();
182}
183
Chris Lattnerb0bf6642004-10-14 01:35:17 +0000184inline BytecodeBlock::~BytecodeBlock() { // Do backpatch when block goes out
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000185 // of scope...
Reid Spencerad89bd62004-07-25 18:07:36 +0000186 if (Loc == Writer.size() && ElideIfEmpty) {
187 // If the block is empty, and we are allowed to, do not emit the block at
188 // all!
189 Writer.resize(Writer.size()-(HasLongFormat?8:4));
190 return;
191 }
192
Reid Spencerad89bd62004-07-25 18:07:36 +0000193 if (HasLongFormat)
194 Writer.output(unsigned(Writer.size()-Loc), int(Loc-4));
195 else
196 Writer.output(unsigned(Writer.size()-Loc) << 5 | (Id & 0x1F), int(Loc-4));
Reid Spencerad89bd62004-07-25 18:07:36 +0000197}
198
199//===----------------------------------------------------------------------===//
200//=== Constant Output ===//
201//===----------------------------------------------------------------------===//
202
203void BytecodeWriter::outputType(const Type *T) {
204 output_vbr((unsigned)T->getTypeID());
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000205
Reid Spencerad89bd62004-07-25 18:07:36 +0000206 // That's all there is to handling primitive types...
207 if (T->isPrimitiveType()) {
208 return; // We might do this if we alias a prim type: %x = type int
209 }
210
211 switch (T->getTypeID()) { // Handle derived types now.
212 case Type::FunctionTyID: {
213 const FunctionType *MT = cast<FunctionType>(T);
214 int Slot = Table.getSlot(MT->getReturnType());
215 assert(Slot != -1 && "Type used but not available!!");
216 output_typeid((unsigned)Slot);
217
218 // Output the number of arguments to function (+1 if varargs):
219 output_vbr((unsigned)MT->getNumParams()+MT->isVarArg());
220
221 // Output all of the arguments...
222 FunctionType::param_iterator I = MT->param_begin();
223 for (; I != MT->param_end(); ++I) {
224 Slot = Table.getSlot(*I);
225 assert(Slot != -1 && "Type used but not available!!");
226 output_typeid((unsigned)Slot);
227 }
228
229 // Terminate list with VoidTy if we are a varargs function...
230 if (MT->isVarArg())
231 output_typeid((unsigned)Type::VoidTyID);
232 break;
233 }
234
235 case Type::ArrayTyID: {
236 const ArrayType *AT = cast<ArrayType>(T);
237 int Slot = Table.getSlot(AT->getElementType());
238 assert(Slot != -1 && "Type used but not available!!");
239 output_typeid((unsigned)Slot);
Reid Spencerad89bd62004-07-25 18:07:36 +0000240 output_vbr(AT->getNumElements());
241 break;
242 }
243
Brian Gaeke715c90b2004-08-20 06:00:58 +0000244 case Type::PackedTyID: {
245 const PackedType *PT = cast<PackedType>(T);
246 int Slot = Table.getSlot(PT->getElementType());
247 assert(Slot != -1 && "Type used but not available!!");
248 output_typeid((unsigned)Slot);
249 output_vbr(PT->getNumElements());
250 break;
251 }
252
253
Reid Spencerad89bd62004-07-25 18:07:36 +0000254 case Type::StructTyID: {
255 const StructType *ST = cast<StructType>(T);
256
257 // Output all of the element types...
258 for (StructType::element_iterator I = ST->element_begin(),
259 E = ST->element_end(); I != E; ++I) {
260 int Slot = Table.getSlot(*I);
261 assert(Slot != -1 && "Type used but not available!!");
262 output_typeid((unsigned)Slot);
263 }
264
265 // Terminate list with VoidTy
266 output_typeid((unsigned)Type::VoidTyID);
267 break;
268 }
269
270 case Type::PointerTyID: {
271 const PointerType *PT = cast<PointerType>(T);
272 int Slot = Table.getSlot(PT->getElementType());
273 assert(Slot != -1 && "Type used but not available!!");
274 output_typeid((unsigned)Slot);
275 break;
276 }
277
Chris Lattnerb0bf6642004-10-14 01:35:17 +0000278 case Type::OpaqueTyID:
Reid Spencerad89bd62004-07-25 18:07:36 +0000279 // No need to emit anything, just the count of opaque types is enough.
280 break;
Reid Spencerad89bd62004-07-25 18:07:36 +0000281
Reid Spencerad89bd62004-07-25 18:07:36 +0000282 default:
283 std::cerr << __FILE__ << ":" << __LINE__ << ": Don't know how to serialize"
284 << " Type '" << T->getDescription() << "'\n";
285 break;
286 }
287}
288
289void BytecodeWriter::outputConstant(const Constant *CPV) {
290 assert((CPV->getType()->isPrimitiveType() || !CPV->isNullValue()) &&
291 "Shouldn't output null constants!");
292
293 // We must check for a ConstantExpr before switching by type because
294 // a ConstantExpr can be of any type, and has no explicit value.
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000295 //
Reid Spencerad89bd62004-07-25 18:07:36 +0000296 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CPV)) {
297 // FIXME: Encoding of constant exprs could be much more compact!
298 assert(CE->getNumOperands() > 0 && "ConstantExpr with 0 operands");
Chris Lattner129baf62004-12-04 21:28:47 +0000299 assert(CE->getNumOperands() != 1 || CE->getOpcode() == Instruction::Cast);
Chris Lattnera79e7cc2004-10-16 18:18:16 +0000300 output_vbr(1+CE->getNumOperands()); // flags as an expr
Reid Spencerad89bd62004-07-25 18:07:36 +0000301 output_vbr(CE->getOpcode()); // flags as an expr
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000302
Reid Spencerad89bd62004-07-25 18:07:36 +0000303 for (User::const_op_iterator OI = CE->op_begin(); OI != CE->op_end(); ++OI){
304 int Slot = Table.getSlot(*OI);
305 assert(Slot != -1 && "Unknown constant used in ConstantExpr!!");
306 output_vbr((unsigned)Slot);
307 Slot = Table.getSlot((*OI)->getType());
308 output_typeid((unsigned)Slot);
309 }
310 return;
Chris Lattnera79e7cc2004-10-16 18:18:16 +0000311 } else if (isa<UndefValue>(CPV)) {
312 output_vbr(1U); // 1 -> UndefValue constant.
313 return;
Reid Spencerad89bd62004-07-25 18:07:36 +0000314 } else {
315 output_vbr(0U); // flag as not a ConstantExpr
316 }
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000317
Reid Spencerad89bd62004-07-25 18:07:36 +0000318 switch (CPV->getType()->getTypeID()) {
319 case Type::BoolTyID: // Boolean Types
320 if (cast<ConstantBool>(CPV)->getValue())
321 output_vbr(1U);
322 else
323 output_vbr(0U);
324 break;
325
326 case Type::UByteTyID: // Unsigned integer types...
327 case Type::UShortTyID:
328 case Type::UIntTyID:
329 case Type::ULongTyID:
330 output_vbr(cast<ConstantUInt>(CPV)->getValue());
331 break;
332
333 case Type::SByteTyID: // Signed integer types...
334 case Type::ShortTyID:
335 case Type::IntTyID:
336 case Type::LongTyID:
337 output_vbr(cast<ConstantSInt>(CPV)->getValue());
338 break;
339
340 case Type::ArrayTyID: {
341 const ConstantArray *CPA = cast<ConstantArray>(CPV);
342 assert(!CPA->isString() && "Constant strings should be handled specially!");
343
Alkis Evlogimenos15876bb2004-08-04 08:44:43 +0000344 for (unsigned i = 0, e = CPA->getNumOperands(); i != e; ++i) {
Reid Spencerad89bd62004-07-25 18:07:36 +0000345 int Slot = Table.getSlot(CPA->getOperand(i));
346 assert(Slot != -1 && "Constant used but not available!!");
347 output_vbr((unsigned)Slot);
348 }
349 break;
350 }
351
Brian Gaeke715c90b2004-08-20 06:00:58 +0000352 case Type::PackedTyID: {
353 const ConstantPacked *CP = cast<ConstantPacked>(CPV);
354
355 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i) {
356 int Slot = Table.getSlot(CP->getOperand(i));
357 assert(Slot != -1 && "Constant used but not available!!");
358 output_vbr((unsigned)Slot);
359 }
360 break;
361 }
362
Reid Spencerad89bd62004-07-25 18:07:36 +0000363 case Type::StructTyID: {
364 const ConstantStruct *CPS = cast<ConstantStruct>(CPV);
Reid Spencerad89bd62004-07-25 18:07:36 +0000365
Alkis Evlogimenos15876bb2004-08-04 08:44:43 +0000366 for (unsigned i = 0, e = CPS->getNumOperands(); i != e; ++i) {
367 int Slot = Table.getSlot(CPS->getOperand(i));
Reid Spencerad89bd62004-07-25 18:07:36 +0000368 assert(Slot != -1 && "Constant used but not available!!");
369 output_vbr((unsigned)Slot);
370 }
371 break;
372 }
373
374 case Type::PointerTyID:
375 assert(0 && "No non-null, non-constant-expr constants allowed!");
376 abort();
377
378 case Type::FloatTyID: { // Floating point types...
379 float Tmp = (float)cast<ConstantFP>(CPV)->getValue();
380 output_float(Tmp);
381 break;
382 }
383 case Type::DoubleTyID: {
384 double Tmp = cast<ConstantFP>(CPV)->getValue();
385 output_double(Tmp);
386 break;
387 }
388
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000389 case Type::VoidTyID:
Reid Spencerad89bd62004-07-25 18:07:36 +0000390 case Type::LabelTyID:
391 default:
392 std::cerr << __FILE__ << ":" << __LINE__ << ": Don't know how to serialize"
393 << " type '" << *CPV->getType() << "'\n";
394 break;
395 }
396 return;
397}
398
399void BytecodeWriter::outputConstantStrings() {
400 SlotCalculator::string_iterator I = Table.string_begin();
401 SlotCalculator::string_iterator E = Table.string_end();
402 if (I == E) return; // No strings to emit
403
404 // If we have != 0 strings to emit, output them now. Strings are emitted into
405 // the 'void' type plane.
406 output_vbr(unsigned(E-I));
407 output_typeid(Type::VoidTyID);
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000408
Reid Spencerad89bd62004-07-25 18:07:36 +0000409 // Emit all of the strings.
410 for (I = Table.string_begin(); I != E; ++I) {
411 const ConstantArray *Str = *I;
412 int Slot = Table.getSlot(Str->getType());
413 assert(Slot != -1 && "Constant string of unknown type?");
414 output_typeid((unsigned)Slot);
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000415
Reid Spencerad89bd62004-07-25 18:07:36 +0000416 // Now that we emitted the type (which indicates the size of the string),
417 // emit all of the characters.
418 std::string Val = Str->getAsString();
419 output_data(Val.c_str(), Val.c_str()+Val.size());
420 }
421}
422
423//===----------------------------------------------------------------------===//
424//=== Instruction Output ===//
425//===----------------------------------------------------------------------===//
426typedef unsigned char uchar;
427
Chris Lattnerda895d62005-02-27 06:18:25 +0000428// outputInstructionFormat0 - Output those weird instructions that have a large
Chris Lattnerdee199f2005-05-06 22:34:01 +0000429// number of operands or have large operands themselves.
Reid Spencerad89bd62004-07-25 18:07:36 +0000430//
431// Format: [opcode] [type] [numargs] [arg0] [arg1] ... [arg<numargs-1>]
432//
Chris Lattnerf9d71782004-10-14 01:46:07 +0000433void BytecodeWriter::outputInstructionFormat0(const Instruction *I,
434 unsigned Opcode,
435 const SlotCalculator &Table,
436 unsigned Type) {
Reid Spencerad89bd62004-07-25 18:07:36 +0000437 // Opcode must have top two bits clear...
438 output_vbr(Opcode << 2); // Instruction Opcode ID
439 output_typeid(Type); // Result type
440
441 unsigned NumArgs = I->getNumOperands();
Andrew Lenharth558bc882005-06-18 18:34:52 +0000442 output_vbr(NumArgs + (isa<CastInst>(I) ||
Chris Lattnerdee199f2005-05-06 22:34:01 +0000443 isa<VAArgInst>(I) || Opcode == 56 || Opcode == 58));
Reid Spencerad89bd62004-07-25 18:07:36 +0000444
445 if (!isa<GetElementPtrInst>(&I)) {
446 for (unsigned i = 0; i < NumArgs; ++i) {
447 int Slot = Table.getSlot(I->getOperand(i));
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000448 assert(Slot >= 0 && "No slot number for value!?!?");
Reid Spencerad89bd62004-07-25 18:07:36 +0000449 output_vbr((unsigned)Slot);
450 }
451
452 if (isa<CastInst>(I) || isa<VAArgInst>(I)) {
453 int Slot = Table.getSlot(I->getType());
454 assert(Slot != -1 && "Cast return type unknown?");
455 output_typeid((unsigned)Slot);
Chris Lattnerdee199f2005-05-06 22:34:01 +0000456 } else if (Opcode == 56) { // Invoke escape sequence
457 output_vbr(cast<InvokeInst>(I)->getCallingConv());
458 } else if (Opcode == 58) { // Call escape sequence
459 output_vbr((cast<CallInst>(I)->getCallingConv() << 1) |
Jeff Cohen39cef602005-05-07 02:44:04 +0000460 unsigned(cast<CallInst>(I)->isTailCall()));
Reid Spencerad89bd62004-07-25 18:07:36 +0000461 }
Reid Spencerad89bd62004-07-25 18:07:36 +0000462 } else {
463 int Slot = Table.getSlot(I->getOperand(0));
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000464 assert(Slot >= 0 && "No slot number for value!?!?");
Reid Spencerad89bd62004-07-25 18:07:36 +0000465 output_vbr(unsigned(Slot));
466
467 // We need to encode the type of sequential type indices into their slot #
468 unsigned Idx = 1;
469 for (gep_type_iterator TI = gep_type_begin(I), E = gep_type_end(I);
470 Idx != NumArgs; ++TI, ++Idx) {
471 Slot = Table.getSlot(I->getOperand(Idx));
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000472 assert(Slot >= 0 && "No slot number for value!?!?");
473
Reid Spencerad89bd62004-07-25 18:07:36 +0000474 if (isa<SequentialType>(*TI)) {
475 unsigned IdxId;
476 switch (I->getOperand(Idx)->getType()->getTypeID()) {
477 default: assert(0 && "Unknown index type!");
478 case Type::UIntTyID: IdxId = 0; break;
479 case Type::IntTyID: IdxId = 1; break;
480 case Type::ULongTyID: IdxId = 2; break;
481 case Type::LongTyID: IdxId = 3; break;
482 }
483 Slot = (Slot << 2) | IdxId;
484 }
485 output_vbr(unsigned(Slot));
486 }
487 }
Reid Spencerad89bd62004-07-25 18:07:36 +0000488}
489
490
491// outputInstrVarArgsCall - Output the absurdly annoying varargs function calls.
492// This are more annoying than most because the signature of the call does not
493// tell us anything about the types of the arguments in the varargs portion.
494// Because of this, we encode (as type 0) all of the argument types explicitly
495// before the argument value. This really sucks, but you shouldn't be using
496// varargs functions in your code! *death to printf*!
497//
498// Format: [opcode] [type] [numargs] [arg0] [arg1] ... [arg<numargs-1>]
499//
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000500void BytecodeWriter::outputInstrVarArgsCall(const Instruction *I,
501 unsigned Opcode,
502 const SlotCalculator &Table,
503 unsigned Type) {
Reid Spencerad89bd62004-07-25 18:07:36 +0000504 assert(isa<CallInst>(I) || isa<InvokeInst>(I));
505 // Opcode must have top two bits clear...
506 output_vbr(Opcode << 2); // Instruction Opcode ID
507 output_typeid(Type); // Result type (varargs type)
508
509 const PointerType *PTy = cast<PointerType>(I->getOperand(0)->getType());
510 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
511 unsigned NumParams = FTy->getNumParams();
512
513 unsigned NumFixedOperands;
514 if (isa<CallInst>(I)) {
515 // Output an operand for the callee and each fixed argument, then two for
516 // each variable argument.
517 NumFixedOperands = 1+NumParams;
518 } else {
519 assert(isa<InvokeInst>(I) && "Not call or invoke??");
520 // Output an operand for the callee and destinations, then two for each
521 // variable argument.
522 NumFixedOperands = 3+NumParams;
523 }
524 output_vbr(2 * I->getNumOperands()-NumFixedOperands);
525
526 // The type for the function has already been emitted in the type field of the
527 // instruction. Just emit the slot # now.
528 for (unsigned i = 0; i != NumFixedOperands; ++i) {
529 int Slot = Table.getSlot(I->getOperand(i));
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000530 assert(Slot >= 0 && "No slot number for value!?!?");
Reid Spencerad89bd62004-07-25 18:07:36 +0000531 output_vbr((unsigned)Slot);
532 }
533
534 for (unsigned i = NumFixedOperands, e = I->getNumOperands(); i != e; ++i) {
535 // Output Arg Type ID
536 int Slot = Table.getSlot(I->getOperand(i)->getType());
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000537 assert(Slot >= 0 && "No slot number for value!?!?");
Reid Spencerad89bd62004-07-25 18:07:36 +0000538 output_typeid((unsigned)Slot);
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000539
Reid Spencerad89bd62004-07-25 18:07:36 +0000540 // Output arg ID itself
541 Slot = Table.getSlot(I->getOperand(i));
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000542 assert(Slot >= 0 && "No slot number for value!?!?");
Reid Spencerad89bd62004-07-25 18:07:36 +0000543 output_vbr((unsigned)Slot);
544 }
Reid Spencerad89bd62004-07-25 18:07:36 +0000545}
546
547
548// outputInstructionFormat1 - Output one operand instructions, knowing that no
549// operand index is >= 2^12.
550//
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000551inline void BytecodeWriter::outputInstructionFormat1(const Instruction *I,
552 unsigned Opcode,
553 unsigned *Slots,
554 unsigned Type) {
Reid Spencerad89bd62004-07-25 18:07:36 +0000555 // bits Instruction format:
556 // --------------------------
557 // 01-00: Opcode type, fixed to 1.
558 // 07-02: Opcode
559 // 19-08: Resulting type plane
560 // 31-20: Operand #1 (if set to (2^12-1), then zero operands)
561 //
Chris Lattnerf9d71782004-10-14 01:46:07 +0000562 output(1 | (Opcode << 2) | (Type << 8) | (Slots[0] << 20));
Reid Spencerad89bd62004-07-25 18:07:36 +0000563}
564
565
566// outputInstructionFormat2 - Output two operand instructions, knowing that no
567// operand index is >= 2^8.
568//
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000569inline void BytecodeWriter::outputInstructionFormat2(const Instruction *I,
570 unsigned Opcode,
571 unsigned *Slots,
572 unsigned Type) {
Reid Spencerad89bd62004-07-25 18:07:36 +0000573 // bits Instruction format:
574 // --------------------------
575 // 01-00: Opcode type, fixed to 2.
576 // 07-02: Opcode
577 // 15-08: Resulting type plane
578 // 23-16: Operand #1
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000579 // 31-24: Operand #2
Reid Spencerad89bd62004-07-25 18:07:36 +0000580 //
Chris Lattnerf9d71782004-10-14 01:46:07 +0000581 output(2 | (Opcode << 2) | (Type << 8) | (Slots[0] << 16) | (Slots[1] << 24));
Reid Spencerad89bd62004-07-25 18:07:36 +0000582}
583
584
585// outputInstructionFormat3 - Output three operand instructions, knowing that no
586// operand index is >= 2^6.
587//
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000588inline void BytecodeWriter::outputInstructionFormat3(const Instruction *I,
Reid Spencerad89bd62004-07-25 18:07:36 +0000589 unsigned Opcode,
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000590 unsigned *Slots,
591 unsigned Type) {
Reid Spencerad89bd62004-07-25 18:07:36 +0000592 // bits Instruction format:
593 // --------------------------
594 // 01-00: Opcode type, fixed to 3.
595 // 07-02: Opcode
596 // 13-08: Resulting type plane
597 // 19-14: Operand #1
598 // 25-20: Operand #2
599 // 31-26: Operand #3
600 //
Chris Lattnerf9d71782004-10-14 01:46:07 +0000601 output(3 | (Opcode << 2) | (Type << 8) |
Chris Lattner84d1ced2004-10-14 01:57:28 +0000602 (Slots[0] << 14) | (Slots[1] << 20) | (Slots[2] << 26));
Reid Spencerad89bd62004-07-25 18:07:36 +0000603}
604
605void BytecodeWriter::outputInstruction(const Instruction &I) {
Chris Lattnerbfed9242005-05-13 23:35:47 +0000606 assert(I.getOpcode() < 56 && "Opcode too big???");
Reid Spencerad89bd62004-07-25 18:07:36 +0000607 unsigned Opcode = I.getOpcode();
608 unsigned NumOperands = I.getNumOperands();
609
Chris Lattner38287bd2005-05-06 06:13:34 +0000610 // Encode 'tail call' as 61, 'volatile load' as 62, and 'volatile store' as
611 // 63.
Chris Lattnerdee199f2005-05-06 22:34:01 +0000612 if (const CallInst *CI = dyn_cast<CallInst>(&I)) {
613 if (CI->getCallingConv() == CallingConv::C) {
614 if (CI->isTailCall())
615 Opcode = 61; // CCC + Tail Call
616 else
617 ; // Opcode = Instruction::Call
618 } else if (CI->getCallingConv() == CallingConv::Fast) {
619 if (CI->isTailCall())
620 Opcode = 59; // FastCC + TailCall
621 else
622 Opcode = 60; // FastCC + Not Tail Call
623 } else {
624 Opcode = 58; // Call escape sequence.
625 }
626 } else if (const InvokeInst *II = dyn_cast<InvokeInst>(&I)) {
627 if (II->getCallingConv() == CallingConv::Fast)
628 Opcode = 57; // FastCC invoke.
629 else if (II->getCallingConv() != CallingConv::C)
630 Opcode = 56; // Invoke escape sequence.
631
632 } else if (isa<LoadInst>(I) && cast<LoadInst>(I).isVolatile()) {
Reid Spencerad89bd62004-07-25 18:07:36 +0000633 Opcode = 62;
Chris Lattnerdee199f2005-05-06 22:34:01 +0000634 } else if (isa<StoreInst>(I) && cast<StoreInst>(I).isVolatile()) {
Reid Spencerad89bd62004-07-25 18:07:36 +0000635 Opcode = 63;
Chris Lattnerdee199f2005-05-06 22:34:01 +0000636 }
Reid Spencerad89bd62004-07-25 18:07:36 +0000637
638 // Figure out which type to encode with the instruction. Typically we want
639 // the type of the first parameter, as opposed to the type of the instruction
640 // (for example, with setcc, we always know it returns bool, but the type of
641 // the first param is actually interesting). But if we have no arguments
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000642 // we take the type of the instruction itself.
Reid Spencerad89bd62004-07-25 18:07:36 +0000643 //
644 const Type *Ty;
645 switch (I.getOpcode()) {
646 case Instruction::Select:
647 case Instruction::Malloc:
648 case Instruction::Alloca:
649 Ty = I.getType(); // These ALWAYS want to encode the return type
650 break;
651 case Instruction::Store:
652 Ty = I.getOperand(1)->getType(); // Encode the pointer type...
653 assert(isa<PointerType>(Ty) && "Store to nonpointer type!?!?");
654 break;
655 default: // Otherwise use the default behavior...
656 Ty = NumOperands ? I.getOperand(0)->getType() : I.getType();
657 break;
658 }
659
660 unsigned Type;
661 int Slot = Table.getSlot(Ty);
662 assert(Slot != -1 && "Type not available!!?!");
663 Type = (unsigned)Slot;
664
665 // Varargs calls and invokes are encoded entirely different from any other
666 // instructions.
667 if (const CallInst *CI = dyn_cast<CallInst>(&I)){
668 const PointerType *Ty =cast<PointerType>(CI->getCalledValue()->getType());
669 if (cast<FunctionType>(Ty->getElementType())->isVarArg()) {
670 outputInstrVarArgsCall(CI, Opcode, Table, Type);
671 return;
672 }
673 } else if (const InvokeInst *II = dyn_cast<InvokeInst>(&I)) {
674 const PointerType *Ty =cast<PointerType>(II->getCalledValue()->getType());
675 if (cast<FunctionType>(Ty->getElementType())->isVarArg()) {
676 outputInstrVarArgsCall(II, Opcode, Table, Type);
677 return;
678 }
679 }
680
681 if (NumOperands <= 3) {
682 // Make sure that we take the type number into consideration. We don't want
683 // to overflow the field size for the instruction format we select.
684 //
685 unsigned MaxOpSlot = Type;
686 unsigned Slots[3]; Slots[0] = (1 << 12)-1; // Marker to signify 0 operands
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000687
Reid Spencerad89bd62004-07-25 18:07:36 +0000688 for (unsigned i = 0; i != NumOperands; ++i) {
689 int slot = Table.getSlot(I.getOperand(i));
690 assert(slot != -1 && "Broken bytecode!");
691 if (unsigned(slot) > MaxOpSlot) MaxOpSlot = unsigned(slot);
692 Slots[i] = unsigned(slot);
693 }
694
695 // Handle the special cases for various instructions...
696 if (isa<CastInst>(I) || isa<VAArgInst>(I)) {
697 // Cast has to encode the destination type as the second argument in the
698 // packet, or else we won't know what type to cast to!
699 Slots[1] = Table.getSlot(I.getType());
700 assert(Slots[1] != ~0U && "Cast return type unknown?");
701 if (Slots[1] > MaxOpSlot) MaxOpSlot = Slots[1];
702 NumOperands++;
Reid Spencerad89bd62004-07-25 18:07:36 +0000703 } else if (const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(&I)) {
704 // We need to encode the type of sequential type indices into their slot #
705 unsigned Idx = 1;
706 for (gep_type_iterator I = gep_type_begin(GEP), E = gep_type_end(GEP);
707 I != E; ++I, ++Idx)
708 if (isa<SequentialType>(*I)) {
709 unsigned IdxId;
710 switch (GEP->getOperand(Idx)->getType()->getTypeID()) {
711 default: assert(0 && "Unknown index type!");
712 case Type::UIntTyID: IdxId = 0; break;
713 case Type::IntTyID: IdxId = 1; break;
714 case Type::ULongTyID: IdxId = 2; break;
715 case Type::LongTyID: IdxId = 3; break;
716 }
717 Slots[Idx] = (Slots[Idx] << 2) | IdxId;
718 if (Slots[Idx] > MaxOpSlot) MaxOpSlot = Slots[Idx];
719 }
Chris Lattnerdee199f2005-05-06 22:34:01 +0000720 } else if (Opcode == 58) {
721 // If this is the escape sequence for call, emit the tailcall/cc info.
722 const CallInst &CI = cast<CallInst>(I);
723 ++NumOperands;
724 if (NumOperands < 3) {
Jeff Cohen39cef602005-05-07 02:44:04 +0000725 Slots[NumOperands-1] = (CI.getCallingConv() << 1)|unsigned(CI.isTailCall());
Chris Lattnerdee199f2005-05-06 22:34:01 +0000726 if (Slots[NumOperands-1] > MaxOpSlot)
727 MaxOpSlot = Slots[NumOperands-1];
728 }
729 } else if (Opcode == 56) {
730 // Invoke escape seq has at least 4 operands to encode.
731 ++NumOperands;
Reid Spencerad89bd62004-07-25 18:07:36 +0000732 }
733
734 // Decide which instruction encoding to use. This is determined primarily
735 // by the number of operands, and secondarily by whether or not the max
736 // operand will fit into the instruction encoding. More operands == fewer
737 // bits per operand.
738 //
739 switch (NumOperands) {
740 case 0:
741 case 1:
742 if (MaxOpSlot < (1 << 12)-1) { // -1 because we use 4095 to indicate 0 ops
743 outputInstructionFormat1(&I, Opcode, Slots, Type);
744 return;
745 }
746 break;
747
748 case 2:
749 if (MaxOpSlot < (1 << 8)) {
750 outputInstructionFormat2(&I, Opcode, Slots, Type);
751 return;
752 }
753 break;
754
755 case 3:
756 if (MaxOpSlot < (1 << 6)) {
757 outputInstructionFormat3(&I, Opcode, Slots, Type);
758 return;
759 }
760 break;
761 default:
762 break;
763 }
764 }
765
766 // If we weren't handled before here, we either have a large number of
767 // operands or a large operand index that we are referring to.
768 outputInstructionFormat0(&I, Opcode, Table, Type);
769}
770
771//===----------------------------------------------------------------------===//
772//=== Block Output ===//
773//===----------------------------------------------------------------------===//
774
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000775BytecodeWriter::BytecodeWriter(std::vector<unsigned char> &o, const Module *M)
Reid Spencer798ff642004-05-26 07:37:11 +0000776 : Out(o), Table(M) {
Chris Lattner00950542001-06-06 20:29:01 +0000777
Chris Lattner83bb3d22004-01-14 23:36:54 +0000778 // Emit the signature...
779 static const unsigned char *Sig = (const unsigned char*)"llvm";
Reid Spencerad89bd62004-07-25 18:07:36 +0000780 output_data(Sig, Sig+4);
Chris Lattner00950542001-06-06 20:29:01 +0000781
782 // Emit the top level CLASS block.
Reid Spencerad89bd62004-07-25 18:07:36 +0000783 BytecodeBlock ModuleBlock(BytecodeFormat::ModuleBlockID, *this, false, true);
Chris Lattner00950542001-06-06 20:29:01 +0000784
Chris Lattnerd445c6b2003-08-24 13:47:36 +0000785 bool isBigEndian = M->getEndianness() == Module::BigEndian;
786 bool hasLongPointers = M->getPointerSize() == Module::Pointer64;
787 bool hasNoEndianness = M->getEndianness() == Module::AnyEndianness;
788 bool hasNoPointerSize = M->getPointerSize() == Module::AnyPointerSize;
Chris Lattner186a1f72003-03-19 20:56:46 +0000789
Chris Lattnera79e7cc2004-10-16 18:18:16 +0000790 // Output the version identifier and other information.
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000791 unsigned Version = (BCVersionNum << 4) |
Reid Spencer38d54be2004-08-17 07:45:14 +0000792 (unsigned)isBigEndian | (hasLongPointers << 1) |
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000793 (hasNoEndianness << 2) |
Reid Spencer38d54be2004-08-17 07:45:14 +0000794 (hasNoPointerSize << 3);
Reid Spencerad89bd62004-07-25 18:07:36 +0000795 output_vbr(Version);
Chris Lattner00950542001-06-06 20:29:01 +0000796
Reid Spencercb3595c2004-07-04 11:45:47 +0000797 // The Global type plane comes first
Chris Lattner186a1f72003-03-19 20:56:46 +0000798 {
Reid Spencerad89bd62004-07-25 18:07:36 +0000799 BytecodeBlock CPool(BytecodeFormat::GlobalTypePlaneBlockID, *this );
Reid Spencercb3595c2004-07-04 11:45:47 +0000800 outputTypes(Type::FirstDerivedTyID);
Chris Lattner186a1f72003-03-19 20:56:46 +0000801 }
Chris Lattner00950542001-06-06 20:29:01 +0000802
Chris Lattner186a1f72003-03-19 20:56:46 +0000803 // The ModuleInfoBlock follows directly after the type information
Chris Lattnere8fdde12001-09-07 16:39:41 +0000804 outputModuleInfoBlock(M);
805
Chris Lattner186a1f72003-03-19 20:56:46 +0000806 // Output module level constants, used for global variable initializers
807 outputConstants(false);
808
Chris Lattnerb5794002002-04-07 22:49:37 +0000809 // Do the whole module now! Process each function at a time...
Chris Lattner0b12b5f2002-06-25 16:13:21 +0000810 for (Module::const_iterator I = M->begin(), E = M->end(); I != E; ++I)
Chris Lattner186a1f72003-03-19 20:56:46 +0000811 outputFunction(I);
Chris Lattnere8fdde12001-09-07 16:39:41 +0000812
813 // If needed, output the symbol table for the module...
Chris Lattner6e6026b2002-11-20 18:36:02 +0000814 outputSymbolTable(M->getSymbolTable());
Chris Lattner00950542001-06-06 20:29:01 +0000815}
816
Chris Lattnerf9d71782004-10-14 01:46:07 +0000817void BytecodeWriter::outputTypes(unsigned TypeNum) {
Reid Spencercb3595c2004-07-04 11:45:47 +0000818 // Write the type plane for types first because earlier planes (e.g. for a
819 // primitive type like float) may have constants constructed using types
820 // coming later (e.g., via getelementptr from a pointer type). The type
821 // plane is needed before types can be fwd or bkwd referenced.
822 const std::vector<const Type*>& Types = Table.getTypes();
823 assert(!Types.empty() && "No types at all?");
824 assert(TypeNum <= Types.size() && "Invalid TypeNo index");
825
826 unsigned NumEntries = Types.size() - TypeNum;
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000827
Reid Spencercb3595c2004-07-04 11:45:47 +0000828 // Output type header: [num entries]
Reid Spencerad89bd62004-07-25 18:07:36 +0000829 output_vbr(NumEntries);
Reid Spencercb3595c2004-07-04 11:45:47 +0000830
831 for (unsigned i = TypeNum; i < TypeNum+NumEntries; ++i)
832 outputType(Types[i]);
833}
834
Vikram S. Advea7dac3d2002-07-14 23:07:51 +0000835// Helper function for outputConstants().
836// Writes out all the constants in the plane Plane starting at entry StartNo.
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000837//
Vikram S. Advea7dac3d2002-07-14 23:07:51 +0000838void BytecodeWriter::outputConstantsInPlane(const std::vector<const Value*>
839 &Plane, unsigned StartNo) {
840 unsigned ValNo = StartNo;
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000841
Chris Lattner83bb3d22004-01-14 23:36:54 +0000842 // Scan through and ignore function arguments, global values, and constant
843 // strings.
844 for (; ValNo < Plane.size() &&
845 (isa<Argument>(Plane[ValNo]) || isa<GlobalValue>(Plane[ValNo]) ||
846 (isa<ConstantArray>(Plane[ValNo]) &&
847 cast<ConstantArray>(Plane[ValNo])->isString())); ValNo++)
Vikram S. Advea7dac3d2002-07-14 23:07:51 +0000848 /*empty*/;
849
850 unsigned NC = ValNo; // Number of constants
Reid Spencercb3595c2004-07-04 11:45:47 +0000851 for (; NC < Plane.size() && (isa<Constant>(Plane[NC])); NC++)
Vikram S. Advea7dac3d2002-07-14 23:07:51 +0000852 /*empty*/;
853 NC -= ValNo; // Convert from index into count
854 if (NC == 0) return; // Skip empty type planes...
855
Chris Lattnerd6942d72004-01-14 16:54:21 +0000856 // FIXME: Most slabs only have 1 or 2 entries! We should encode this much
857 // more compactly.
858
Vikram S. Advea7dac3d2002-07-14 23:07:51 +0000859 // Output type header: [num entries][type id number]
860 //
Reid Spencerad89bd62004-07-25 18:07:36 +0000861 output_vbr(NC);
Vikram S. Advea7dac3d2002-07-14 23:07:51 +0000862
863 // Output the Type ID Number...
Alkis Evlogimenos60596382003-10-17 02:02:40 +0000864 int Slot = Table.getSlot(Plane.front()->getType());
Vikram S. Advea7dac3d2002-07-14 23:07:51 +0000865 assert (Slot != -1 && "Type in constant pool but not in function!!");
Reid Spencerad89bd62004-07-25 18:07:36 +0000866 output_typeid((unsigned)Slot);
Vikram S. Advea7dac3d2002-07-14 23:07:51 +0000867
Vikram S. Advea7dac3d2002-07-14 23:07:51 +0000868 for (unsigned i = ValNo; i < ValNo+NC; ++i) {
869 const Value *V = Plane[i];
Reid Spencere0125b62004-07-18 00:16:21 +0000870 if (const Constant *C = dyn_cast<Constant>(V)) {
871 outputConstant(C);
Vikram S. Advea7dac3d2002-07-14 23:07:51 +0000872 }
873 }
874}
875
Chris Lattner9e60d8d2005-05-05 22:21:19 +0000876static inline bool hasNullValue(const Type *Ty) {
877 return Ty != Type::LabelTy && Ty != Type::VoidTy && !isa<OpaqueType>(Ty);
Chris Lattner80b97342004-01-17 23:25:43 +0000878}
879
Chris Lattner79df7c02002-03-26 18:01:55 +0000880void BytecodeWriter::outputConstants(bool isFunction) {
Reid Spencerad89bd62004-07-25 18:07:36 +0000881 BytecodeBlock CPool(BytecodeFormat::ConstantPoolBlockID, *this,
Chris Lattner0baa0af2004-01-15 21:06:57 +0000882 true /* Elide block if empty */);
Chris Lattner00950542001-06-06 20:29:01 +0000883
884 unsigned NumPlanes = Table.getNumPlanes();
Chris Lattnerf69315b2003-05-22 18:35:38 +0000885
Reid Spencere0125b62004-07-18 00:16:21 +0000886 if (isFunction)
887 // Output the type plane before any constants!
Chris Lattnera79e7cc2004-10-16 18:18:16 +0000888 outputTypes(Table.getModuleTypeLevel());
Reid Spencere0125b62004-07-18 00:16:21 +0000889 else
Chris Lattnerf9d71782004-10-14 01:46:07 +0000890 // Output module-level string constants before any other constants.
Chris Lattner83bb3d22004-01-14 23:36:54 +0000891 outputConstantStrings();
892
Reid Spencercb3595c2004-07-04 11:45:47 +0000893 for (unsigned pno = 0; pno != NumPlanes; pno++) {
894 const std::vector<const Value*> &Plane = Table.getPlane(pno);
895 if (!Plane.empty()) { // Skip empty type planes...
896 unsigned ValNo = 0;
897 if (isFunction) // Don't re-emit module constants
Reid Spencer0852c802004-07-04 11:46:15 +0000898 ValNo += Table.getModuleLevel(pno);
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000899
Chris Lattner9e60d8d2005-05-05 22:21:19 +0000900 if (hasNullValue(Plane[0]->getType())) {
Reid Spencer0852c802004-07-04 11:46:15 +0000901 // Skip zero initializer
902 if (ValNo == 0)
903 ValNo = 1;
Chris Lattnerf69315b2003-05-22 18:35:38 +0000904 }
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000905
Reid Spencercb3595c2004-07-04 11:45:47 +0000906 // Write out constants in the plane
907 outputConstantsInPlane(Plane, ValNo);
Chris Lattnerf69315b2003-05-22 18:35:38 +0000908 }
Reid Spencercb3595c2004-07-04 11:45:47 +0000909 }
Chris Lattner00950542001-06-06 20:29:01 +0000910}
911
Chris Lattner6b252422003-10-16 18:28:50 +0000912static unsigned getEncodedLinkage(const GlobalValue *GV) {
913 switch (GV->getLinkage()) {
914 default: assert(0 && "Invalid linkage!");
915 case GlobalValue::ExternalLinkage: return 0;
Chris Lattner6b252422003-10-16 18:28:50 +0000916 case GlobalValue::WeakLinkage: return 1;
917 case GlobalValue::AppendingLinkage: return 2;
918 case GlobalValue::InternalLinkage: return 3;
Chris Lattner22482a12003-10-18 06:30:21 +0000919 case GlobalValue::LinkOnceLinkage: return 4;
Chris Lattner6b252422003-10-16 18:28:50 +0000920 }
921}
922
Chris Lattner00950542001-06-06 20:29:01 +0000923void BytecodeWriter::outputModuleInfoBlock(const Module *M) {
Reid Spencerad89bd62004-07-25 18:07:36 +0000924 BytecodeBlock ModuleInfoBlock(BytecodeFormat::ModuleGlobalInfoBlockID, *this);
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000925
Chris Lattner70cc3392001-09-10 07:58:01 +0000926 // Output the types for the global variables in the module...
Chris Lattner28caccf2005-05-06 20:27:03 +0000927 for (Module::const_global_iterator I = M->global_begin(),
928 End = M->global_end(); I != End;++I) {
Alkis Evlogimenos60596382003-10-17 02:02:40 +0000929 int Slot = Table.getSlot(I->getType());
Chris Lattner70cc3392001-09-10 07:58:01 +0000930 assert(Slot != -1 && "Module global vars is broken!");
Chris Lattnerd70684f2001-09-18 04:01:05 +0000931
Chris Lattner22482a12003-10-18 06:30:21 +0000932 // Fields: bit0 = isConstant, bit1 = hasInitializer, bit2-4=Linkage,
933 // bit5+ = Slot # for type
Chris Lattnerf74acc72004-10-14 02:31:35 +0000934 unsigned oSlot = ((unsigned)Slot << 5) | (getEncodedLinkage(I) << 2) |
Chris Lattner036de032004-06-25 20:52:10 +0000935 (I->hasInitializer() << 1) | (unsigned)I->isConstant();
Chris Lattnera79e7cc2004-10-16 18:18:16 +0000936 output_vbr(oSlot);
Chris Lattnerd70684f2001-09-18 04:01:05 +0000937
Chris Lattner1b98c5c2001-10-13 06:48:38 +0000938 // If we have an initializer, output it now.
Chris Lattner0b12b5f2002-06-25 16:13:21 +0000939 if (I->hasInitializer()) {
Alkis Evlogimenos60596382003-10-17 02:02:40 +0000940 Slot = Table.getSlot((Value*)I->getInitializer());
Chris Lattnerd70684f2001-09-18 04:01:05 +0000941 assert(Slot != -1 && "No slot for global var initializer!");
Reid Spencerad89bd62004-07-25 18:07:36 +0000942 output_vbr((unsigned)Slot);
Chris Lattnerd70684f2001-09-18 04:01:05 +0000943 }
Chris Lattner70cc3392001-09-10 07:58:01 +0000944 }
Reid Spencerad89bd62004-07-25 18:07:36 +0000945 output_typeid((unsigned)Table.getSlot(Type::VoidTy));
Chris Lattner70cc3392001-09-10 07:58:01 +0000946
Chris Lattnera79e7cc2004-10-16 18:18:16 +0000947 // Output the types of the functions in this module.
Chris Lattner7fc9fe32001-06-27 23:41:11 +0000948 for (Module::const_iterator I = M->begin(), End = M->end(); I != End; ++I) {
Alkis Evlogimenos60596382003-10-17 02:02:40 +0000949 int Slot = Table.getSlot(I->getType());
Chris Lattnera79e7cc2004-10-16 18:18:16 +0000950 assert(Slot != -1 && "Module slot calculator is broken!");
Chris Lattner00950542001-06-06 20:29:01 +0000951 assert(Slot >= Type::FirstDerivedTyID && "Derived type not in range!");
Chris Lattnera79e7cc2004-10-16 18:18:16 +0000952 assert(((Slot << 5) >> 5) == Slot && "Slot # too big!");
Chris Lattner479ffeb2005-05-06 20:42:57 +0000953 unsigned ID = (Slot << 5);
954
955 if (I->getCallingConv() < 15)
956 ID += I->getCallingConv()+1;
957
Chris Lattnerd6e431f2004-11-15 22:39:49 +0000958 if (I->isExternal()) // If external, we don't have an FunctionInfo block.
959 ID |= 1 << 4;
Chris Lattnera79e7cc2004-10-16 18:18:16 +0000960 output_vbr(ID);
Chris Lattner479ffeb2005-05-06 20:42:57 +0000961
962 if (I->getCallingConv() >= 15)
963 output_vbr(I->getCallingConv());
Chris Lattner00950542001-06-06 20:29:01 +0000964 }
Chris Lattnera79e7cc2004-10-16 18:18:16 +0000965 output_vbr((unsigned)Table.getSlot(Type::VoidTy) << 5);
Reid Spencerad89bd62004-07-25 18:07:36 +0000966
Chris Lattnera79e7cc2004-10-16 18:18:16 +0000967 // Emit the list of dependent libraries for the Module.
Reid Spencer5ac88122004-07-25 21:32:02 +0000968 Module::lib_iterator LI = M->lib_begin();
969 Module::lib_iterator LE = M->lib_end();
Chris Lattnera79e7cc2004-10-16 18:18:16 +0000970 output_vbr(unsigned(LE - LI)); // Emit the number of dependent libraries.
971 for (; LI != LE; ++LI)
Reid Spencer38d54be2004-08-17 07:45:14 +0000972 output(*LI);
Reid Spencerad89bd62004-07-25 18:07:36 +0000973
974 // Output the target triple from the module
Reid Spencer38d54be2004-08-17 07:45:14 +0000975 output(M->getTargetTriple());
Chris Lattner00950542001-06-06 20:29:01 +0000976}
977
Chris Lattnercf3e67f2004-01-18 21:08:52 +0000978void BytecodeWriter::outputInstructions(const Function *F) {
Reid Spencerad89bd62004-07-25 18:07:36 +0000979 BytecodeBlock ILBlock(BytecodeFormat::InstructionListBlockID, *this);
Chris Lattnercf3e67f2004-01-18 21:08:52 +0000980 for (Function::const_iterator BB = F->begin(), E = F->end(); BB != E; ++BB)
981 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I!=E; ++I)
982 outputInstruction(*I);
Chris Lattnercf3e67f2004-01-18 21:08:52 +0000983}
984
Chris Lattner186a1f72003-03-19 20:56:46 +0000985void BytecodeWriter::outputFunction(const Function *F) {
Chris Lattnerfd7f8fe2004-11-15 21:56:33 +0000986 // If this is an external function, there is nothing else to emit!
987 if (F->isExternal()) return;
988
Chris Lattnerd6e431f2004-11-15 22:39:49 +0000989 BytecodeBlock FunctionBlock(BytecodeFormat::FunctionBlockID, *this);
990 output_vbr(getEncodedLinkage(F));
991
Chris Lattnercf3e67f2004-01-18 21:08:52 +0000992 // Get slot information about the function...
993 Table.incorporateFunction(F);
994
995 if (Table.getCompactionTable().empty()) {
996 // Output information about the constants in the function if the compaction
997 // table is not being used.
Chris Lattnere8fdde12001-09-07 16:39:41 +0000998 outputConstants(true);
Chris Lattnercf3e67f2004-01-18 21:08:52 +0000999 } else {
1000 // Otherwise, emit the compaction table.
1001 outputCompactionTable();
Chris Lattnere8fdde12001-09-07 16:39:41 +00001002 }
Misha Brukman23c6d2c2005-04-21 21:48:46 +00001003
Chris Lattnercf3e67f2004-01-18 21:08:52 +00001004 // Output all of the instructions in the body of the function
1005 outputInstructions(F);
Misha Brukman23c6d2c2005-04-21 21:48:46 +00001006
Chris Lattnercf3e67f2004-01-18 21:08:52 +00001007 // If needed, output the symbol table for the function...
1008 outputSymbolTable(F->getSymbolTable());
Misha Brukman23c6d2c2005-04-21 21:48:46 +00001009
Chris Lattnercf3e67f2004-01-18 21:08:52 +00001010 Table.purgeFunction();
1011}
1012
1013void BytecodeWriter::outputCompactionTablePlane(unsigned PlaneNo,
1014 const std::vector<const Value*> &Plane,
1015 unsigned StartNo) {
1016 unsigned End = Table.getModuleLevel(PlaneNo);
Chris Lattner52f86d62004-01-20 00:54:06 +00001017 if (Plane.empty() || StartNo == End || End == 0) return; // Nothing to emit
Chris Lattnercf3e67f2004-01-18 21:08:52 +00001018 assert(StartNo < End && "Cannot emit negative range!");
1019 assert(StartNo < Plane.size() && End <= Plane.size());
1020
Chris Lattnercf3e67f2004-01-18 21:08:52 +00001021 // Do not emit the null initializer!
Reid Spencercb3595c2004-07-04 11:45:47 +00001022 ++StartNo;
Chris Lattnercf3e67f2004-01-18 21:08:52 +00001023
Chris Lattner24102432004-01-18 22:35:34 +00001024 // Figure out which encoding to use. By far the most common case we have is
1025 // to emit 0-2 entries in a compaction table plane.
1026 switch (End-StartNo) {
1027 case 0: // Avoid emitting two vbr's if possible.
1028 case 1:
1029 case 2:
Reid Spencerad89bd62004-07-25 18:07:36 +00001030 output_vbr((PlaneNo << 2) | End-StartNo);
Chris Lattner24102432004-01-18 22:35:34 +00001031 break;
1032 default:
1033 // Output the number of things.
Reid Spencerad89bd62004-07-25 18:07:36 +00001034 output_vbr((unsigned(End-StartNo) << 2) | 3);
1035 output_typeid(PlaneNo); // Emit the type plane this is
Chris Lattner24102432004-01-18 22:35:34 +00001036 break;
1037 }
1038
Chris Lattnercf3e67f2004-01-18 21:08:52 +00001039 for (unsigned i = StartNo; i != End; ++i)
Reid Spencerad89bd62004-07-25 18:07:36 +00001040 output_vbr(Table.getGlobalSlot(Plane[i]));
Chris Lattnercf3e67f2004-01-18 21:08:52 +00001041}
1042
Reid Spencercb3595c2004-07-04 11:45:47 +00001043void BytecodeWriter::outputCompactionTypes(unsigned StartNo) {
1044 // Get the compaction type table from the slot calculator
1045 const std::vector<const Type*> &CTypes = Table.getCompactionTypes();
1046
1047 // The compaction types may have been uncompactified back to the
1048 // global types. If so, we just write an empty table
1049 if (CTypes.size() == 0 ) {
Reid Spencerad89bd62004-07-25 18:07:36 +00001050 output_vbr(0U);
Reid Spencercb3595c2004-07-04 11:45:47 +00001051 return;
1052 }
1053
1054 assert(CTypes.size() >= StartNo && "Invalid compaction types start index");
1055
1056 // Determine how many types to write
1057 unsigned NumTypes = CTypes.size() - StartNo;
1058
1059 // Output the number of types.
Reid Spencerad89bd62004-07-25 18:07:36 +00001060 output_vbr(NumTypes);
Reid Spencercb3595c2004-07-04 11:45:47 +00001061
1062 for (unsigned i = StartNo; i < StartNo+NumTypes; ++i)
Reid Spencerad89bd62004-07-25 18:07:36 +00001063 output_typeid(Table.getGlobalSlot(CTypes[i]));
Reid Spencercb3595c2004-07-04 11:45:47 +00001064}
1065
Chris Lattnercf3e67f2004-01-18 21:08:52 +00001066void BytecodeWriter::outputCompactionTable() {
Reid Spencer0033c182004-08-27 00:38:44 +00001067 // Avoid writing the compaction table at all if there is no content.
1068 if (Table.getCompactionTypes().size() >= Type::FirstDerivedTyID ||
1069 (!Table.CompactionTableIsEmpty())) {
Misha Brukman23c6d2c2005-04-21 21:48:46 +00001070 BytecodeBlock CTB(BytecodeFormat::CompactionTableBlockID, *this,
Reid Spencer0033c182004-08-27 00:38:44 +00001071 true/*ElideIfEmpty*/);
Chris Lattnerf9d71782004-10-14 01:46:07 +00001072 const std::vector<std::vector<const Value*> > &CT =
1073 Table.getCompactionTable();
Misha Brukman23c6d2c2005-04-21 21:48:46 +00001074
Reid Spencer0033c182004-08-27 00:38:44 +00001075 // First things first, emit the type compaction table if there is one.
1076 outputCompactionTypes(Type::FirstDerivedTyID);
Chris Lattnercf3e67f2004-01-18 21:08:52 +00001077
Reid Spencer0033c182004-08-27 00:38:44 +00001078 for (unsigned i = 0, e = CT.size(); i != e; ++i)
1079 outputCompactionTablePlane(i, CT[i], 0);
1080 }
Chris Lattner00950542001-06-06 20:29:01 +00001081}
1082
Chris Lattner00950542001-06-06 20:29:01 +00001083void BytecodeWriter::outputSymbolTable(const SymbolTable &MST) {
Chris Lattner737d3cd2004-01-10 19:56:59 +00001084 // Do not output the Bytecode block for an empty symbol table, it just wastes
1085 // space!
Chris Lattnerf9d71782004-10-14 01:46:07 +00001086 if (MST.isEmpty()) return;
Chris Lattner737d3cd2004-01-10 19:56:59 +00001087
Reid Spencerad89bd62004-07-25 18:07:36 +00001088 BytecodeBlock SymTabBlock(BytecodeFormat::SymbolTableBlockID, *this,
Chris Lattnerf9d71782004-10-14 01:46:07 +00001089 true/*ElideIfEmpty*/);
Chris Lattner00950542001-06-06 20:29:01 +00001090
Misha Brukman23c6d2c2005-04-21 21:48:46 +00001091 // Write the number of types
Reid Spencerad89bd62004-07-25 18:07:36 +00001092 output_vbr(MST.num_types());
Reid Spencer250c4182004-08-17 02:59:02 +00001093
1094 // Write each of the types
Reid Spencer94f2df22004-05-25 17:29:59 +00001095 for (SymbolTable::type_const_iterator TI = MST.type_begin(),
1096 TE = MST.type_end(); TI != TE; ++TI ) {
Reid Spencer250c4182004-08-17 02:59:02 +00001097 // Symtab entry:[def slot #][name]
Reid Spencerad89bd62004-07-25 18:07:36 +00001098 output_typeid((unsigned)Table.getSlot(TI->second));
Misha Brukman23c6d2c2005-04-21 21:48:46 +00001099 output(TI->first);
Reid Spencer94f2df22004-05-25 17:29:59 +00001100 }
1101
1102 // Now do each of the type planes in order.
Misha Brukman23c6d2c2005-04-21 21:48:46 +00001103 for (SymbolTable::plane_const_iterator PI = MST.plane_begin(),
Reid Spencer94f2df22004-05-25 17:29:59 +00001104 PE = MST.plane_end(); PI != PE; ++PI) {
1105 SymbolTable::value_const_iterator I = MST.value_begin(PI->first);
1106 SymbolTable::value_const_iterator End = MST.value_end(PI->first);
Chris Lattner00950542001-06-06 20:29:01 +00001107 int Slot;
Misha Brukman23c6d2c2005-04-21 21:48:46 +00001108
Chris Lattner00950542001-06-06 20:29:01 +00001109 if (I == End) continue; // Don't mess with an absent type...
1110
Reid Spencer250c4182004-08-17 02:59:02 +00001111 // Write the number of values in this plane
Chris Lattner001d16a2005-03-07 02:59:36 +00001112 output_vbr((unsigned)PI->second.size());
Chris Lattner00950542001-06-06 20:29:01 +00001113
Reid Spencer250c4182004-08-17 02:59:02 +00001114 // Write the slot number of the type for this plane
Reid Spencer94f2df22004-05-25 17:29:59 +00001115 Slot = Table.getSlot(PI->first);
Chris Lattner00950542001-06-06 20:29:01 +00001116 assert(Slot != -1 && "Type in symtab, but not in table!");
Reid Spencerad89bd62004-07-25 18:07:36 +00001117 output_typeid((unsigned)Slot);
Chris Lattner00950542001-06-06 20:29:01 +00001118
Reid Spencer250c4182004-08-17 02:59:02 +00001119 // Write each of the values in this plane
Chris Lattner7fc9fe32001-06-27 23:41:11 +00001120 for (; I != End; ++I) {
Chris Lattner00950542001-06-06 20:29:01 +00001121 // Symtab entry: [def slot #][name]
Alkis Evlogimenos60596382003-10-17 02:02:40 +00001122 Slot = Table.getSlot(I->second);
Chris Lattnere8fdde12001-09-07 16:39:41 +00001123 assert(Slot != -1 && "Value in symtab but has no slot number!!");
Reid Spencerad89bd62004-07-25 18:07:36 +00001124 output_vbr((unsigned)Slot);
Reid Spencer38d54be2004-08-17 07:45:14 +00001125 output(I->first);
Chris Lattner00950542001-06-06 20:29:01 +00001126 }
1127 }
1128}
1129
Reid Spencer17f52c52004-11-06 23:17:23 +00001130void llvm::WriteBytecodeToFile(const Module *M, std::ostream &Out,
1131 bool compress ) {
Reid Spencerad89bd62004-07-25 18:07:36 +00001132 assert(M && "You can't write a null module!!");
Chris Lattner00950542001-06-06 20:29:01 +00001133
Reid Spencer17f52c52004-11-06 23:17:23 +00001134 // Create a vector of unsigned char for the bytecode output. We
1135 // reserve 256KBytes of space in the vector so that we avoid doing
1136 // lots of little allocations. 256KBytes is sufficient for a large
1137 // proportion of the bytecode files we will encounter. Larger files
1138 // will be automatically doubled in size as needed (std::vector
1139 // behavior).
Reid Spencerad89bd62004-07-25 18:07:36 +00001140 std::vector<unsigned char> Buffer;
Reid Spencer17f52c52004-11-06 23:17:23 +00001141 Buffer.reserve(256 * 1024);
Chris Lattner00950542001-06-06 20:29:01 +00001142
Reid Spencer17f52c52004-11-06 23:17:23 +00001143 // The BytecodeWriter populates Buffer for us.
Reid Spencerad89bd62004-07-25 18:07:36 +00001144 BytecodeWriter BCW(Buffer, M);
Chris Lattner00950542001-06-06 20:29:01 +00001145
Reid Spencer17f52c52004-11-06 23:17:23 +00001146 // Keep track of how much we've written
Chris Lattnerce6ef112002-07-26 18:40:14 +00001147 BytesWritten += Buffer.size();
1148
Reid Spencer17f52c52004-11-06 23:17:23 +00001149 // Determine start and end points of the Buffer
Reid Spencer83296f52004-11-07 18:17:38 +00001150 const unsigned char *FirstByte = &Buffer.front();
Reid Spencer17f52c52004-11-06 23:17:23 +00001151
1152 // If we're supposed to compress this mess ...
1153 if (compress) {
1154
1155 // We signal compression by using an alternate magic number for the
Reid Spencer83296f52004-11-07 18:17:38 +00001156 // file. The compressed bytecode file's magic number is "llvc" instead
Misha Brukman23c6d2c2005-04-21 21:48:46 +00001157 // of "llvm".
Reid Spencer83296f52004-11-07 18:17:38 +00001158 char compressed_magic[4];
1159 compressed_magic[0] = 'l';
1160 compressed_magic[1] = 'l';
1161 compressed_magic[2] = 'v';
1162 compressed_magic[3] = 'c';
Reid Spencer17f52c52004-11-06 23:17:23 +00001163
Reid Spencer83296f52004-11-07 18:17:38 +00001164 Out.write(compressed_magic,4);
Reid Spencer17f52c52004-11-06 23:17:23 +00001165
Reid Spencera70d84d2004-11-14 22:01:41 +00001166 // Compress everything after the magic number (which we altered)
1167 uint64_t zipSize = Compressor::compressToStream(
Reid Spencer17f52c52004-11-06 23:17:23 +00001168 (char*)(FirstByte+4), // Skip the magic number
1169 Buffer.size()-4, // Skip the magic number
Reid Spencer84472d62004-11-25 19:38:05 +00001170 Out // Where to write compressed data
Reid Spencer17f52c52004-11-06 23:17:23 +00001171 );
1172
Reid Spencer17f52c52004-11-06 23:17:23 +00001173 } else {
1174
1175 // We're not compressing, so just write the entire block.
Reid Spencer83296f52004-11-07 18:17:38 +00001176 Out.write((char*)FirstByte, Buffer.size());
Chris Lattnere8fdde12001-09-07 16:39:41 +00001177 }
Reid Spencer17f52c52004-11-06 23:17:23 +00001178
1179 // make sure it hits disk now
Chris Lattner00950542001-06-06 20:29:01 +00001180 Out.flush();
1181}
Reid Spencere0125b62004-07-18 00:16:21 +00001182