blob: d5f3f9301d57bb47498f5503b5c68961ff3752c0 [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
Chris Lattner1c560ad2006-12-19 23:16:47 +000020#define DEBUG_TYPE "bytecodewriter"
Chris Lattner00950542001-06-06 20:29:01 +000021#include "WriterInternals.h"
Chris Lattner635cd932002-07-23 19:56:44 +000022#include "llvm/Bytecode/WriteBytecodePass.h"
Chris Lattnerdee199f2005-05-06 22:34:01 +000023#include "llvm/CallingConv.h"
Chris Lattner83bb3d22004-01-14 23:36:54 +000024#include "llvm/Constants.h"
25#include "llvm/DerivedTypes.h"
Chris Lattner3bc5a602006-01-25 23:08:15 +000026#include "llvm/InlineAsm.h"
Reid Spencerad89bd62004-07-25 18:07:36 +000027#include "llvm/Instructions.h"
Chris Lattner00950542001-06-06 20:29:01 +000028#include "llvm/Module.h"
Chris Lattner00950542001-06-06 20:29:01 +000029#include "llvm/SymbolTable.h"
Reid Spencer78d033e2007-01-06 07:24:44 +000030#include "llvm/TypeSymbolTable.h"
Reid Spencerad89bd62004-07-25 18:07:36 +000031#include "llvm/Support/GetElementPtrTypeIterator.h"
Reid Spencer17f52c52004-11-06 23:17:23 +000032#include "llvm/Support/Compressor.h"
Jim Laskeycb6682f2005-08-17 19:34:49 +000033#include "llvm/Support/MathExtras.h"
Bill Wendling68fe61d2006-11-29 00:19:40 +000034#include "llvm/Support/Streams.h"
Reid Spencer32f55532006-06-07 23:18:34 +000035#include "llvm/System/Program.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000036#include "llvm/ADT/STLExtras.h"
37#include "llvm/ADT/Statistic.h"
Chris Lattner32abce62004-01-10 19:10:01 +000038#include <cstring>
Chris Lattner00950542001-06-06 20:29:01 +000039#include <algorithm>
Chris Lattner44f549b2004-01-10 18:49:43 +000040using namespace llvm;
Brian Gaeked0fde302003-11-11 22:41:34 +000041
Reid Spencer38d54be2004-08-17 07:45:14 +000042/// This value needs to be incremented every time the bytecode format changes
43/// so that the reader can distinguish which format of the bytecode file has
44/// been written.
45/// @brief The bytecode version number
Reid Spencer6996feb2006-11-08 21:27:54 +000046const unsigned BCVersionNum = 7;
Reid Spencer38d54be2004-08-17 07:45:14 +000047
Chris Lattner635cd932002-07-23 19:56:44 +000048static RegisterPass<WriteBytecodePass> X("emitbytecode", "Bytecode Writer");
49
Chris Lattner1c560ad2006-12-19 23:16:47 +000050STATISTIC(BytesWritten, "Number of bytecode bytes written");
Chris Lattner635cd932002-07-23 19:56:44 +000051
Reid Spencerad89bd62004-07-25 18:07:36 +000052//===----------------------------------------------------------------------===//
53//=== Output Primitives ===//
54//===----------------------------------------------------------------------===//
55
56// output - If a position is specified, it must be in the valid portion of the
Misha Brukman23c6d2c2005-04-21 21:48:46 +000057// string... note that this should be inlined always so only the relevant IF
Reid Spencerad89bd62004-07-25 18:07:36 +000058// body should be included.
59inline void BytecodeWriter::output(unsigned i, int pos) {
60 if (pos == -1) { // Be endian clean, little endian is our friend
Misha Brukman23c6d2c2005-04-21 21:48:46 +000061 Out.push_back((unsigned char)i);
Reid Spencerad89bd62004-07-25 18:07:36 +000062 Out.push_back((unsigned char)(i >> 8));
63 Out.push_back((unsigned char)(i >> 16));
64 Out.push_back((unsigned char)(i >> 24));
65 } else {
66 Out[pos ] = (unsigned char)i;
67 Out[pos+1] = (unsigned char)(i >> 8);
68 Out[pos+2] = (unsigned char)(i >> 16);
69 Out[pos+3] = (unsigned char)(i >> 24);
70 }
71}
72
73inline void BytecodeWriter::output(int i) {
74 output((unsigned)i);
75}
76
77/// output_vbr - Output an unsigned value, by using the least number of bytes
78/// possible. This is useful because many of our "infinite" values are really
79/// very small most of the time; but can be large a few times.
Misha Brukman23c6d2c2005-04-21 21:48:46 +000080/// Data format used: If you read a byte with the high bit set, use the low
81/// seven bits as data and then read another byte.
Reid Spencerad89bd62004-07-25 18:07:36 +000082inline void BytecodeWriter::output_vbr(uint64_t i) {
83 while (1) {
84 if (i < 0x80) { // done?
85 Out.push_back((unsigned char)i); // We know the high bit is clear...
86 return;
87 }
Misha Brukman23c6d2c2005-04-21 21:48:46 +000088
Reid Spencerad89bd62004-07-25 18:07:36 +000089 // Nope, we are bigger than a character, output the next 7 bits and set the
90 // high bit to say that there is more coming...
91 Out.push_back(0x80 | ((unsigned char)i & 0x7F));
92 i >>= 7; // Shift out 7 bits now...
93 }
94}
95
96inline void BytecodeWriter::output_vbr(unsigned i) {
97 while (1) {
98 if (i < 0x80) { // done?
99 Out.push_back((unsigned char)i); // We know the high bit is clear...
100 return;
101 }
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000102
Reid Spencerad89bd62004-07-25 18:07:36 +0000103 // Nope, we are bigger than a character, output the next 7 bits and set the
104 // high bit to say that there is more coming...
105 Out.push_back(0x80 | ((unsigned char)i & 0x7F));
106 i >>= 7; // Shift out 7 bits now...
107 }
108}
109
110inline void BytecodeWriter::output_typeid(unsigned i) {
111 if (i <= 0x00FFFFFF)
112 this->output_vbr(i);
113 else {
114 this->output_vbr(0x00FFFFFF);
115 this->output_vbr(i);
116 }
117}
118
119inline void BytecodeWriter::output_vbr(int64_t i) {
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000120 if (i < 0)
Reid Spencerad89bd62004-07-25 18:07:36 +0000121 output_vbr(((uint64_t)(-i) << 1) | 1); // Set low order sign bit...
122 else
123 output_vbr((uint64_t)i << 1); // Low order bit is clear.
124}
125
126
127inline void BytecodeWriter::output_vbr(int i) {
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000128 if (i < 0)
Reid Spencerad89bd62004-07-25 18:07:36 +0000129 output_vbr(((unsigned)(-i) << 1) | 1); // Set low order sign bit...
130 else
131 output_vbr((unsigned)i << 1); // Low order bit is clear.
132}
133
Reid Spencer38d54be2004-08-17 07:45:14 +0000134inline void BytecodeWriter::output(const std::string &s) {
Reid Spencerad89bd62004-07-25 18:07:36 +0000135 unsigned Len = s.length();
Chris Lattnerc847f7c2006-07-28 22:07:54 +0000136 output_vbr(Len); // Strings may have an arbitrary length.
Reid Spencerad89bd62004-07-25 18:07:36 +0000137 Out.insert(Out.end(), s.begin(), s.end());
Reid Spencerad89bd62004-07-25 18:07:36 +0000138}
139
140inline void BytecodeWriter::output_data(const void *Ptr, const void *End) {
141 Out.insert(Out.end(), (const unsigned char*)Ptr, (const unsigned char*)End);
142}
143
144inline void BytecodeWriter::output_float(float& FloatVal) {
145 /// FIXME: This isn't optimal, it has size problems on some platforms
146 /// where FP is not IEEE.
Jim Laskeycb6682f2005-08-17 19:34:49 +0000147 uint32_t i = FloatToBits(FloatVal);
Chris Lattnerc847f7c2006-07-28 22:07:54 +0000148 Out.push_back( static_cast<unsigned char>( (i ) & 0xFF));
149 Out.push_back( static_cast<unsigned char>( (i >> 8 ) & 0xFF));
Jim Laskeycb6682f2005-08-17 19:34:49 +0000150 Out.push_back( static_cast<unsigned char>( (i >> 16) & 0xFF));
151 Out.push_back( static_cast<unsigned char>( (i >> 24) & 0xFF));
Reid Spencerad89bd62004-07-25 18:07:36 +0000152}
153
154inline void BytecodeWriter::output_double(double& DoubleVal) {
155 /// FIXME: This isn't optimal, it has size problems on some platforms
156 /// where FP is not IEEE.
Jim Laskeycb6682f2005-08-17 19:34:49 +0000157 uint64_t i = DoubleToBits(DoubleVal);
Chris Lattnerc847f7c2006-07-28 22:07:54 +0000158 Out.push_back( static_cast<unsigned char>( (i ) & 0xFF));
159 Out.push_back( static_cast<unsigned char>( (i >> 8 ) & 0xFF));
Jim Laskeycb6682f2005-08-17 19:34:49 +0000160 Out.push_back( static_cast<unsigned char>( (i >> 16) & 0xFF));
161 Out.push_back( static_cast<unsigned char>( (i >> 24) & 0xFF));
162 Out.push_back( static_cast<unsigned char>( (i >> 32) & 0xFF));
163 Out.push_back( static_cast<unsigned char>( (i >> 40) & 0xFF));
164 Out.push_back( static_cast<unsigned char>( (i >> 48) & 0xFF));
165 Out.push_back( static_cast<unsigned char>( (i >> 56) & 0xFF));
Reid Spencerad89bd62004-07-25 18:07:36 +0000166}
167
Chris Lattnerc76ea432005-11-12 18:34:09 +0000168inline BytecodeBlock::BytecodeBlock(unsigned ID, BytecodeWriter &w,
169 bool elideIfEmpty, bool hasLongFormat)
Reid Spencerad89bd62004-07-25 18:07:36 +0000170 : Id(ID), Writer(w), ElideIfEmpty(elideIfEmpty), HasLongFormat(hasLongFormat){
171
172 if (HasLongFormat) {
173 w.output(ID);
174 w.output(0U); // For length in long format
175 } else {
176 w.output(0U); /// Place holder for ID and length for this block
177 }
178 Loc = w.size();
179}
180
Chris Lattnerb0bf6642004-10-14 01:35:17 +0000181inline BytecodeBlock::~BytecodeBlock() { // Do backpatch when block goes out
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000182 // of scope...
Reid Spencerad89bd62004-07-25 18:07:36 +0000183 if (Loc == Writer.size() && ElideIfEmpty) {
184 // If the block is empty, and we are allowed to, do not emit the block at
185 // all!
186 Writer.resize(Writer.size()-(HasLongFormat?8:4));
187 return;
188 }
189
Reid Spencerad89bd62004-07-25 18:07:36 +0000190 if (HasLongFormat)
191 Writer.output(unsigned(Writer.size()-Loc), int(Loc-4));
192 else
193 Writer.output(unsigned(Writer.size()-Loc) << 5 | (Id & 0x1F), int(Loc-4));
Reid Spencerad89bd62004-07-25 18:07:36 +0000194}
195
196//===----------------------------------------------------------------------===//
197//=== Constant Output ===//
198//===----------------------------------------------------------------------===//
199
200void BytecodeWriter::outputType(const Type *T) {
Andrew Lenharth38ecbf12006-12-08 18:06:16 +0000201 const StructType* STy = dyn_cast<StructType>(T);
202 if(STy && STy->isPacked())
Reid Spencera54b7cb2007-01-12 07:05:14 +0000203 output_vbr((unsigned)Type::PackedStructTyID);
Andrew Lenharth38ecbf12006-12-08 18:06:16 +0000204 else
205 output_vbr((unsigned)T->getTypeID());
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000206
Reid Spencerad89bd62004-07-25 18:07:36 +0000207 // That's all there is to handling primitive types...
Reid Spencera54b7cb2007-01-12 07:05:14 +0000208 if (T->isPrimitiveType())
Reid Spencerad89bd62004-07-25 18:07:36 +0000209 return; // We might do this if we alias a prim type: %x = type int
Reid Spencerad89bd62004-07-25 18:07:36 +0000210
211 switch (T->getTypeID()) { // Handle derived types now.
Reid Spencera54b7cb2007-01-12 07:05:14 +0000212 case Type::IntegerTyID:
213 output_vbr(cast<IntegerType>(T)->getBitWidth());
214 break;
Reid Spencerad89bd62004-07-25 18:07:36 +0000215 case Type::FunctionTyID: {
216 const FunctionType *MT = cast<FunctionType>(T);
217 int Slot = Table.getSlot(MT->getReturnType());
218 assert(Slot != -1 && "Type used but not available!!");
219 output_typeid((unsigned)Slot);
Reid Spencer88cfda22006-12-31 05:44:24 +0000220 output_vbr(unsigned(MT->getParamAttrs(0)));
Reid Spencerad89bd62004-07-25 18:07:36 +0000221
222 // Output the number of arguments to function (+1 if varargs):
223 output_vbr((unsigned)MT->getNumParams()+MT->isVarArg());
224
225 // Output all of the arguments...
226 FunctionType::param_iterator I = MT->param_begin();
Reid Spencer88cfda22006-12-31 05:44:24 +0000227 unsigned Idx = 1;
Reid Spencerad89bd62004-07-25 18:07:36 +0000228 for (; I != MT->param_end(); ++I) {
229 Slot = Table.getSlot(*I);
230 assert(Slot != -1 && "Type used but not available!!");
231 output_typeid((unsigned)Slot);
Reid Spencer88cfda22006-12-31 05:44:24 +0000232 output_vbr(unsigned(MT->getParamAttrs(Idx)));
233 Idx++;
Reid Spencerad89bd62004-07-25 18:07:36 +0000234 }
235
236 // Terminate list with VoidTy if we are a varargs function...
237 if (MT->isVarArg())
238 output_typeid((unsigned)Type::VoidTyID);
239 break;
240 }
241
242 case Type::ArrayTyID: {
243 const ArrayType *AT = cast<ArrayType>(T);
244 int Slot = Table.getSlot(AT->getElementType());
245 assert(Slot != -1 && "Type used but not available!!");
246 output_typeid((unsigned)Slot);
Reid Spencerad89bd62004-07-25 18:07:36 +0000247 output_vbr(AT->getNumElements());
248 break;
249 }
250
Brian Gaeke715c90b2004-08-20 06:00:58 +0000251 case Type::PackedTyID: {
252 const PackedType *PT = cast<PackedType>(T);
253 int Slot = Table.getSlot(PT->getElementType());
254 assert(Slot != -1 && "Type used but not available!!");
255 output_typeid((unsigned)Slot);
256 output_vbr(PT->getNumElements());
257 break;
258 }
259
Reid Spencerad89bd62004-07-25 18:07:36 +0000260 case Type::StructTyID: {
261 const StructType *ST = cast<StructType>(T);
Reid Spencerad89bd62004-07-25 18:07:36 +0000262 // Output all of the element types...
263 for (StructType::element_iterator I = ST->element_begin(),
264 E = ST->element_end(); I != E; ++I) {
265 int Slot = Table.getSlot(*I);
266 assert(Slot != -1 && "Type used but not available!!");
267 output_typeid((unsigned)Slot);
268 }
269
270 // Terminate list with VoidTy
271 output_typeid((unsigned)Type::VoidTyID);
272 break;
273 }
274
275 case Type::PointerTyID: {
276 const PointerType *PT = cast<PointerType>(T);
277 int Slot = Table.getSlot(PT->getElementType());
278 assert(Slot != -1 && "Type used but not available!!");
279 output_typeid((unsigned)Slot);
280 break;
281 }
282
Chris Lattnerb0bf6642004-10-14 01:35:17 +0000283 case Type::OpaqueTyID:
Reid Spencerad89bd62004-07-25 18:07:36 +0000284 // No need to emit anything, just the count of opaque types is enough.
285 break;
Reid Spencerad89bd62004-07-25 18:07:36 +0000286
Reid Spencerad89bd62004-07-25 18:07:36 +0000287 default:
Bill Wendlinge8156192006-12-07 01:30:32 +0000288 cerr << __FILE__ << ":" << __LINE__ << ": Don't know how to serialize"
289 << " Type '" << T->getDescription() << "'\n";
Reid Spencerad89bd62004-07-25 18:07:36 +0000290 break;
291 }
292}
293
294void BytecodeWriter::outputConstant(const Constant *CPV) {
Chris Lattner42a75512007-01-15 02:27:26 +0000295 assert(((CPV->getType()->isPrimitiveType() || CPV->getType()->isInteger()) ||
Reid Spencera54b7cb2007-01-12 07:05:14 +0000296 !CPV->isNullValue()) && "Shouldn't output null constants!");
Reid Spencerad89bd62004-07-25 18:07:36 +0000297
298 // We must check for a ConstantExpr before switching by type because
299 // a ConstantExpr can be of any type, and has no explicit value.
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000300 //
Reid Spencerad89bd62004-07-25 18:07:36 +0000301 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CPV)) {
302 // FIXME: Encoding of constant exprs could be much more compact!
303 assert(CE->getNumOperands() > 0 && "ConstantExpr with 0 operands");
Reid Spencer3da59db2006-11-27 01:05:10 +0000304 assert(CE->getNumOperands() != 1 || CE->isCast());
Chris Lattnera79e7cc2004-10-16 18:18:16 +0000305 output_vbr(1+CE->getNumOperands()); // flags as an expr
Reid Spencerb83eb642006-10-20 07:07:24 +0000306 output_vbr(CE->getOpcode()); // Put out the CE op code
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000307
Reid Spencerad89bd62004-07-25 18:07:36 +0000308 for (User::const_op_iterator OI = CE->op_begin(); OI != CE->op_end(); ++OI){
309 int Slot = Table.getSlot(*OI);
310 assert(Slot != -1 && "Unknown constant used in ConstantExpr!!");
311 output_vbr((unsigned)Slot);
312 Slot = Table.getSlot((*OI)->getType());
313 output_typeid((unsigned)Slot);
314 }
Reid Spencer595b4772006-12-04 05:23:49 +0000315 if (CE->isCompare())
316 output_vbr((unsigned)CE->getPredicate());
Reid Spencerad89bd62004-07-25 18:07:36 +0000317 return;
Chris Lattnera79e7cc2004-10-16 18:18:16 +0000318 } else if (isa<UndefValue>(CPV)) {
319 output_vbr(1U); // 1 -> UndefValue constant.
320 return;
Reid Spencerad89bd62004-07-25 18:07:36 +0000321 } else {
Reid Spencerb83eb642006-10-20 07:07:24 +0000322 output_vbr(0U); // flag as not a ConstantExpr (i.e. 0 operands)
Reid Spencerad89bd62004-07-25 18:07:36 +0000323 }
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000324
Reid Spencerad89bd62004-07-25 18:07:36 +0000325 switch (CPV->getType()->getTypeID()) {
Reid Spencera54b7cb2007-01-12 07:05:14 +0000326 case Type::IntegerTyID: { // Integer types...
327 unsigned NumBits = cast<IntegerType>(CPV->getType())->getBitWidth();
Chris Lattnerfb939312007-01-12 23:26:17 +0000328 if (NumBits <= 32)
Reid Spencera54b7cb2007-01-12 07:05:14 +0000329 output_vbr(uint32_t(cast<ConstantInt>(CPV)->getZExtValue()));
330 else if (NumBits <= 64)
331 output_vbr(uint64_t(cast<ConstantInt>(CPV)->getZExtValue()));
332 else
333 assert("Integer types > 64 bits not supported.");
Reid Spencerad89bd62004-07-25 18:07:36 +0000334 break;
Reid Spencera54b7cb2007-01-12 07:05:14 +0000335 }
Reid Spencerad89bd62004-07-25 18:07:36 +0000336
Reid Spencerad89bd62004-07-25 18:07:36 +0000337 case Type::ArrayTyID: {
338 const ConstantArray *CPA = cast<ConstantArray>(CPV);
339 assert(!CPA->isString() && "Constant strings should be handled specially!");
340
Alkis Evlogimenos15876bb2004-08-04 08:44:43 +0000341 for (unsigned i = 0, e = CPA->getNumOperands(); i != e; ++i) {
Reid Spencerad89bd62004-07-25 18:07:36 +0000342 int Slot = Table.getSlot(CPA->getOperand(i));
343 assert(Slot != -1 && "Constant used but not available!!");
344 output_vbr((unsigned)Slot);
345 }
346 break;
347 }
348
Brian Gaeke715c90b2004-08-20 06:00:58 +0000349 case Type::PackedTyID: {
350 const ConstantPacked *CP = cast<ConstantPacked>(CPV);
351
352 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i) {
353 int Slot = Table.getSlot(CP->getOperand(i));
354 assert(Slot != -1 && "Constant used but not available!!");
355 output_vbr((unsigned)Slot);
356 }
357 break;
358 }
359
Reid Spencerad89bd62004-07-25 18:07:36 +0000360 case Type::StructTyID: {
361 const ConstantStruct *CPS = cast<ConstantStruct>(CPV);
Reid Spencerad89bd62004-07-25 18:07:36 +0000362
Alkis Evlogimenos15876bb2004-08-04 08:44:43 +0000363 for (unsigned i = 0, e = CPS->getNumOperands(); i != e; ++i) {
364 int Slot = Table.getSlot(CPS->getOperand(i));
Reid Spencerad89bd62004-07-25 18:07:36 +0000365 assert(Slot != -1 && "Constant used but not available!!");
366 output_vbr((unsigned)Slot);
367 }
368 break;
369 }
370
371 case Type::PointerTyID:
372 assert(0 && "No non-null, non-constant-expr constants allowed!");
373 abort();
374
375 case Type::FloatTyID: { // Floating point types...
376 float Tmp = (float)cast<ConstantFP>(CPV)->getValue();
377 output_float(Tmp);
378 break;
379 }
380 case Type::DoubleTyID: {
381 double Tmp = cast<ConstantFP>(CPV)->getValue();
382 output_double(Tmp);
383 break;
384 }
385
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000386 case Type::VoidTyID:
Reid Spencerad89bd62004-07-25 18:07:36 +0000387 case Type::LabelTyID:
388 default:
Bill Wendlinge8156192006-12-07 01:30:32 +0000389 cerr << __FILE__ << ":" << __LINE__ << ": Don't know how to serialize"
390 << " type '" << *CPV->getType() << "'\n";
Reid Spencerad89bd62004-07-25 18:07:36 +0000391 break;
392 }
393 return;
394}
395
Chris Lattner3bc5a602006-01-25 23:08:15 +0000396/// outputInlineAsm - InlineAsm's get emitted to the constant pool, so they can
397/// be shared by multiple uses.
398void BytecodeWriter::outputInlineAsm(const InlineAsm *IA) {
399 // Output a marker, so we know when we have one one parsing the constant pool.
400 // Note that this encoding is 5 bytes: not very efficient for a marker. Since
401 // unique inline asms are rare, this should hardly matter.
402 output_vbr(~0U);
403
404 output(IA->getAsmString());
405 output(IA->getConstraintString());
406 output_vbr(unsigned(IA->hasSideEffects()));
407}
408
Reid Spencerad89bd62004-07-25 18:07:36 +0000409void BytecodeWriter::outputConstantStrings() {
410 SlotCalculator::string_iterator I = Table.string_begin();
411 SlotCalculator::string_iterator E = Table.string_end();
412 if (I == E) return; // No strings to emit
413
414 // If we have != 0 strings to emit, output them now. Strings are emitted into
415 // the 'void' type plane.
416 output_vbr(unsigned(E-I));
417 output_typeid(Type::VoidTyID);
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000418
Reid Spencerad89bd62004-07-25 18:07:36 +0000419 // Emit all of the strings.
420 for (I = Table.string_begin(); I != E; ++I) {
421 const ConstantArray *Str = *I;
422 int Slot = Table.getSlot(Str->getType());
423 assert(Slot != -1 && "Constant string of unknown type?");
424 output_typeid((unsigned)Slot);
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000425
Reid Spencerad89bd62004-07-25 18:07:36 +0000426 // Now that we emitted the type (which indicates the size of the string),
427 // emit all of the characters.
428 std::string Val = Str->getAsString();
429 output_data(Val.c_str(), Val.c_str()+Val.size());
430 }
431}
432
433//===----------------------------------------------------------------------===//
434//=== Instruction Output ===//
435//===----------------------------------------------------------------------===//
Reid Spencerad89bd62004-07-25 18:07:36 +0000436
Chris Lattnerda895d62005-02-27 06:18:25 +0000437// outputInstructionFormat0 - Output those weird instructions that have a large
Chris Lattnerdee199f2005-05-06 22:34:01 +0000438// number of operands or have large operands themselves.
Reid Spencerad89bd62004-07-25 18:07:36 +0000439//
440// Format: [opcode] [type] [numargs] [arg0] [arg1] ... [arg<numargs-1>]
441//
Chris Lattnerf9d71782004-10-14 01:46:07 +0000442void BytecodeWriter::outputInstructionFormat0(const Instruction *I,
443 unsigned Opcode,
444 const SlotCalculator &Table,
445 unsigned Type) {
Reid Spencerad89bd62004-07-25 18:07:36 +0000446 // Opcode must have top two bits clear...
447 output_vbr(Opcode << 2); // Instruction Opcode ID
448 output_typeid(Type); // Result type
449
450 unsigned NumArgs = I->getNumOperands();
Reid Spencercae60532006-12-06 04:27:07 +0000451 output_vbr(NumArgs + (isa<CastInst>(I) || isa<InvokeInst>(I) ||
452 isa<CmpInst>(I) || isa<VAArgInst>(I) || Opcode == 58));
Reid Spencerad89bd62004-07-25 18:07:36 +0000453
454 if (!isa<GetElementPtrInst>(&I)) {
455 for (unsigned i = 0; i < NumArgs; ++i) {
456 int Slot = Table.getSlot(I->getOperand(i));
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000457 assert(Slot >= 0 && "No slot number for value!?!?");
Reid Spencerad89bd62004-07-25 18:07:36 +0000458 output_vbr((unsigned)Slot);
459 }
460
461 if (isa<CastInst>(I) || isa<VAArgInst>(I)) {
462 int Slot = Table.getSlot(I->getType());
463 assert(Slot != -1 && "Cast return type unknown?");
464 output_typeid((unsigned)Slot);
Reid Spencercae60532006-12-06 04:27:07 +0000465 } else if (isa<CmpInst>(I)) {
466 output_vbr(unsigned(cast<CmpInst>(I)->getPredicate()));
Reid Spencer3da59db2006-11-27 01:05:10 +0000467 } else if (isa<InvokeInst>(I)) {
Chris Lattnerdee199f2005-05-06 22:34:01 +0000468 output_vbr(cast<InvokeInst>(I)->getCallingConv());
469 } else if (Opcode == 58) { // Call escape sequence
470 output_vbr((cast<CallInst>(I)->getCallingConv() << 1) |
Jeff Cohen39cef602005-05-07 02:44:04 +0000471 unsigned(cast<CallInst>(I)->isTailCall()));
Reid Spencerad89bd62004-07-25 18:07:36 +0000472 }
Reid Spencerad89bd62004-07-25 18:07:36 +0000473 } else {
474 int Slot = Table.getSlot(I->getOperand(0));
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000475 assert(Slot >= 0 && "No slot number for value!?!?");
Reid Spencerad89bd62004-07-25 18:07:36 +0000476 output_vbr(unsigned(Slot));
477
478 // We need to encode the type of sequential type indices into their slot #
479 unsigned Idx = 1;
480 for (gep_type_iterator TI = gep_type_begin(I), E = gep_type_end(I);
481 Idx != NumArgs; ++TI, ++Idx) {
482 Slot = Table.getSlot(I->getOperand(Idx));
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000483 assert(Slot >= 0 && "No slot number for value!?!?");
484
Reid Spencerad89bd62004-07-25 18:07:36 +0000485 if (isa<SequentialType>(*TI)) {
Reid Spencera54b7cb2007-01-12 07:05:14 +0000486 // These should be either 32-bits or 64-bits, however, with bit
487 // accurate types we just distinguish between less than or equal to
488 // 32-bits or greater than 32-bits.
Reid Spencer790366b2007-01-13 00:10:02 +0000489 unsigned BitWidth =
490 cast<IntegerType>(I->getOperand(Idx)->getType())->getBitWidth();
491 assert(BitWidth == 32 || BitWidth == 64 &&
492 "Invalid bitwidth for GEP index");
493 unsigned IdxId = BitWidth == 32 ? 0 : 1;
Reid Spencer88cfda22006-12-31 05:44:24 +0000494 Slot = (Slot << 1) | IdxId;
Reid Spencerad89bd62004-07-25 18:07:36 +0000495 }
496 output_vbr(unsigned(Slot));
497 }
498 }
Reid Spencerad89bd62004-07-25 18:07:36 +0000499}
500
501
502// outputInstrVarArgsCall - Output the absurdly annoying varargs function calls.
503// This are more annoying than most because the signature of the call does not
504// tell us anything about the types of the arguments in the varargs portion.
505// Because of this, we encode (as type 0) all of the argument types explicitly
506// before the argument value. This really sucks, but you shouldn't be using
507// varargs functions in your code! *death to printf*!
508//
509// Format: [opcode] [type] [numargs] [arg0] [arg1] ... [arg<numargs-1>]
510//
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000511void BytecodeWriter::outputInstrVarArgsCall(const Instruction *I,
512 unsigned Opcode,
513 const SlotCalculator &Table,
514 unsigned Type) {
Reid Spencerad89bd62004-07-25 18:07:36 +0000515 assert(isa<CallInst>(I) || isa<InvokeInst>(I));
516 // Opcode must have top two bits clear...
517 output_vbr(Opcode << 2); // Instruction Opcode ID
518 output_typeid(Type); // Result type (varargs type)
519
520 const PointerType *PTy = cast<PointerType>(I->getOperand(0)->getType());
521 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
522 unsigned NumParams = FTy->getNumParams();
523
524 unsigned NumFixedOperands;
525 if (isa<CallInst>(I)) {
526 // Output an operand for the callee and each fixed argument, then two for
527 // each variable argument.
528 NumFixedOperands = 1+NumParams;
529 } else {
530 assert(isa<InvokeInst>(I) && "Not call or invoke??");
531 // Output an operand for the callee and destinations, then two for each
532 // variable argument.
533 NumFixedOperands = 3+NumParams;
534 }
Reid Spencer3da59db2006-11-27 01:05:10 +0000535 output_vbr(2 * I->getNumOperands()-NumFixedOperands +
536 unsigned(Opcode == 58 || isa<InvokeInst>(I)));
Reid Spencerad89bd62004-07-25 18:07:36 +0000537
538 // The type for the function has already been emitted in the type field of the
539 // instruction. Just emit the slot # now.
540 for (unsigned i = 0; i != NumFixedOperands; ++i) {
541 int 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 }
545
546 for (unsigned i = NumFixedOperands, e = I->getNumOperands(); i != e; ++i) {
547 // Output Arg Type ID
548 int Slot = Table.getSlot(I->getOperand(i)->getType());
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000549 assert(Slot >= 0 && "No slot number for value!?!?");
Reid Spencerad89bd62004-07-25 18:07:36 +0000550 output_typeid((unsigned)Slot);
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000551
Reid Spencerad89bd62004-07-25 18:07:36 +0000552 // Output arg ID itself
553 Slot = Table.getSlot(I->getOperand(i));
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000554 assert(Slot >= 0 && "No slot number for value!?!?");
Reid Spencerad89bd62004-07-25 18:07:36 +0000555 output_vbr((unsigned)Slot);
556 }
Chris Lattnera65371e2006-05-26 18:42:34 +0000557
Reid Spencer3da59db2006-11-27 01:05:10 +0000558 if (isa<InvokeInst>(I)) {
559 // Emit the tail call/calling conv for invoke instructions
560 output_vbr(cast<InvokeInst>(I)->getCallingConv());
561 } else if (Opcode == 58) {
Chris Lattnera65371e2006-05-26 18:42:34 +0000562 const CallInst *CI = cast<CallInst>(I);
563 output_vbr((CI->getCallingConv() << 1) | unsigned(CI->isTailCall()));
Chris Lattnera65371e2006-05-26 18:42:34 +0000564 }
Reid Spencerad89bd62004-07-25 18:07:36 +0000565}
566
567
568// outputInstructionFormat1 - Output one operand instructions, knowing that no
569// operand index is >= 2^12.
570//
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000571inline void BytecodeWriter::outputInstructionFormat1(const Instruction *I,
572 unsigned Opcode,
573 unsigned *Slots,
574 unsigned Type) {
Reid Spencerad89bd62004-07-25 18:07:36 +0000575 // bits Instruction format:
576 // --------------------------
577 // 01-00: Opcode type, fixed to 1.
578 // 07-02: Opcode
579 // 19-08: Resulting type plane
580 // 31-20: Operand #1 (if set to (2^12-1), then zero operands)
581 //
Chris Lattnerf9d71782004-10-14 01:46:07 +0000582 output(1 | (Opcode << 2) | (Type << 8) | (Slots[0] << 20));
Reid Spencerad89bd62004-07-25 18:07:36 +0000583}
584
585
586// outputInstructionFormat2 - Output two operand instructions, knowing that no
587// operand index is >= 2^8.
588//
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000589inline void BytecodeWriter::outputInstructionFormat2(const Instruction *I,
590 unsigned Opcode,
591 unsigned *Slots,
592 unsigned Type) {
Reid Spencerad89bd62004-07-25 18:07:36 +0000593 // bits Instruction format:
594 // --------------------------
595 // 01-00: Opcode type, fixed to 2.
596 // 07-02: Opcode
597 // 15-08: Resulting type plane
598 // 23-16: Operand #1
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000599 // 31-24: Operand #2
Reid Spencerad89bd62004-07-25 18:07:36 +0000600 //
Chris Lattnerf9d71782004-10-14 01:46:07 +0000601 output(2 | (Opcode << 2) | (Type << 8) | (Slots[0] << 16) | (Slots[1] << 24));
Reid Spencerad89bd62004-07-25 18:07:36 +0000602}
603
604
605// outputInstructionFormat3 - Output three operand instructions, knowing that no
606// operand index is >= 2^6.
607//
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000608inline void BytecodeWriter::outputInstructionFormat3(const Instruction *I,
Reid Spencerad89bd62004-07-25 18:07:36 +0000609 unsigned Opcode,
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000610 unsigned *Slots,
611 unsigned Type) {
Reid Spencerad89bd62004-07-25 18:07:36 +0000612 // bits Instruction format:
613 // --------------------------
614 // 01-00: Opcode type, fixed to 3.
615 // 07-02: Opcode
616 // 13-08: Resulting type plane
617 // 19-14: Operand #1
618 // 25-20: Operand #2
619 // 31-26: Operand #3
620 //
Chris Lattnerf9d71782004-10-14 01:46:07 +0000621 output(3 | (Opcode << 2) | (Type << 8) |
Chris Lattner84d1ced2004-10-14 01:57:28 +0000622 (Slots[0] << 14) | (Slots[1] << 20) | (Slots[2] << 26));
Reid Spencerad89bd62004-07-25 18:07:36 +0000623}
624
625void BytecodeWriter::outputInstruction(const Instruction &I) {
Reid Spencer3da59db2006-11-27 01:05:10 +0000626 assert(I.getOpcode() < 57 && "Opcode too big???");
Reid Spencerad89bd62004-07-25 18:07:36 +0000627 unsigned Opcode = I.getOpcode();
628 unsigned NumOperands = I.getNumOperands();
629
Chris Lattner38287bd2005-05-06 06:13:34 +0000630 // Encode 'tail call' as 61, 'volatile load' as 62, and 'volatile store' as
631 // 63.
Chris Lattnerdee199f2005-05-06 22:34:01 +0000632 if (const CallInst *CI = dyn_cast<CallInst>(&I)) {
633 if (CI->getCallingConv() == CallingConv::C) {
634 if (CI->isTailCall())
635 Opcode = 61; // CCC + Tail Call
636 else
637 ; // Opcode = Instruction::Call
638 } else if (CI->getCallingConv() == CallingConv::Fast) {
639 if (CI->isTailCall())
640 Opcode = 59; // FastCC + TailCall
641 else
642 Opcode = 60; // FastCC + Not Tail Call
643 } else {
644 Opcode = 58; // Call escape sequence.
645 }
Chris Lattnerdee199f2005-05-06 22:34:01 +0000646 } else if (isa<LoadInst>(I) && cast<LoadInst>(I).isVolatile()) {
Reid Spencerad89bd62004-07-25 18:07:36 +0000647 Opcode = 62;
Chris Lattnerdee199f2005-05-06 22:34:01 +0000648 } else if (isa<StoreInst>(I) && cast<StoreInst>(I).isVolatile()) {
Reid Spencerad89bd62004-07-25 18:07:36 +0000649 Opcode = 63;
Chris Lattnerdee199f2005-05-06 22:34:01 +0000650 }
Reid Spencerad89bd62004-07-25 18:07:36 +0000651
652 // Figure out which type to encode with the instruction. Typically we want
653 // the type of the first parameter, as opposed to the type of the instruction
654 // (for example, with setcc, we always know it returns bool, but the type of
655 // the first param is actually interesting). But if we have no arguments
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000656 // we take the type of the instruction itself.
Reid Spencerad89bd62004-07-25 18:07:36 +0000657 //
658 const Type *Ty;
659 switch (I.getOpcode()) {
660 case Instruction::Select:
661 case Instruction::Malloc:
662 case Instruction::Alloca:
663 Ty = I.getType(); // These ALWAYS want to encode the return type
664 break;
665 case Instruction::Store:
666 Ty = I.getOperand(1)->getType(); // Encode the pointer type...
667 assert(isa<PointerType>(Ty) && "Store to nonpointer type!?!?");
668 break;
669 default: // Otherwise use the default behavior...
670 Ty = NumOperands ? I.getOperand(0)->getType() : I.getType();
671 break;
672 }
673
674 unsigned Type;
675 int Slot = Table.getSlot(Ty);
676 assert(Slot != -1 && "Type not available!!?!");
677 Type = (unsigned)Slot;
678
679 // Varargs calls and invokes are encoded entirely different from any other
680 // instructions.
681 if (const CallInst *CI = dyn_cast<CallInst>(&I)){
682 const PointerType *Ty =cast<PointerType>(CI->getCalledValue()->getType());
683 if (cast<FunctionType>(Ty->getElementType())->isVarArg()) {
684 outputInstrVarArgsCall(CI, Opcode, Table, Type);
685 return;
686 }
687 } else if (const InvokeInst *II = dyn_cast<InvokeInst>(&I)) {
688 const PointerType *Ty =cast<PointerType>(II->getCalledValue()->getType());
689 if (cast<FunctionType>(Ty->getElementType())->isVarArg()) {
690 outputInstrVarArgsCall(II, Opcode, Table, Type);
691 return;
692 }
693 }
694
695 if (NumOperands <= 3) {
696 // Make sure that we take the type number into consideration. We don't want
697 // to overflow the field size for the instruction format we select.
698 //
699 unsigned MaxOpSlot = Type;
700 unsigned Slots[3]; Slots[0] = (1 << 12)-1; // Marker to signify 0 operands
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000701
Reid Spencerad89bd62004-07-25 18:07:36 +0000702 for (unsigned i = 0; i != NumOperands; ++i) {
703 int slot = Table.getSlot(I.getOperand(i));
704 assert(slot != -1 && "Broken bytecode!");
705 if (unsigned(slot) > MaxOpSlot) MaxOpSlot = unsigned(slot);
706 Slots[i] = unsigned(slot);
707 }
708
709 // Handle the special cases for various instructions...
710 if (isa<CastInst>(I) || isa<VAArgInst>(I)) {
711 // Cast has to encode the destination type as the second argument in the
712 // packet, or else we won't know what type to cast to!
713 Slots[1] = Table.getSlot(I.getType());
714 assert(Slots[1] != ~0U && "Cast return type unknown?");
715 if (Slots[1] > MaxOpSlot) MaxOpSlot = Slots[1];
716 NumOperands++;
Chris Lattner42ba6b42005-11-05 22:08:14 +0000717 } else if (const AllocationInst *AI = dyn_cast<AllocationInst>(&I)) {
718 assert(NumOperands == 1 && "Bogus allocation!");
719 if (AI->getAlignment()) {
720 Slots[1] = Log2_32(AI->getAlignment())+1;
721 if (Slots[1] > MaxOpSlot) MaxOpSlot = Slots[1];
722 NumOperands = 2;
723 }
Reid Spencerc8dab492006-12-03 06:28:54 +0000724 } else if (isa<ICmpInst>(I) || isa<FCmpInst>(I)) {
725 // We need to encode the compare instruction's predicate as the third
726 // operand. Its not really a slot, but we don't want to break the
727 // instruction format for these instructions.
728 NumOperands++;
729 assert(NumOperands == 3 && "CmpInst with wrong number of operands?");
730 Slots[2] = unsigned(cast<CmpInst>(&I)->getPredicate());
731 if (Slots[2] > MaxOpSlot)
732 MaxOpSlot = Slots[2];
Reid Spencerad89bd62004-07-25 18:07:36 +0000733 } else if (const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(&I)) {
734 // We need to encode the type of sequential type indices into their slot #
735 unsigned Idx = 1;
736 for (gep_type_iterator I = gep_type_begin(GEP), E = gep_type_end(GEP);
737 I != E; ++I, ++Idx)
738 if (isa<SequentialType>(*I)) {
Reid Spencera54b7cb2007-01-12 07:05:14 +0000739 // These should be either 32-bits or 64-bits, however, with bit
740 // accurate types we just distinguish between less than or equal to
741 // 32-bits or greater than 32-bits.
Reid Spencer790366b2007-01-13 00:10:02 +0000742 unsigned BitWidth =
743 cast<IntegerType>(GEP->getOperand(Idx)->getType())->getBitWidth();
744 assert(BitWidth == 32 || BitWidth == 64 &&
745 "Invalid bitwidth for GEP index");
746 unsigned IdxId = BitWidth == 32 ? 0 : 1;
Reid Spencer88cfda22006-12-31 05:44:24 +0000747 Slots[Idx] = (Slots[Idx] << 1) | IdxId;
Reid Spencerad89bd62004-07-25 18:07:36 +0000748 if (Slots[Idx] > MaxOpSlot) MaxOpSlot = Slots[Idx];
749 }
Chris Lattnerdee199f2005-05-06 22:34:01 +0000750 } else if (Opcode == 58) {
751 // If this is the escape sequence for call, emit the tailcall/cc info.
752 const CallInst &CI = cast<CallInst>(I);
753 ++NumOperands;
Chris Lattnerebf8e6c2006-05-19 21:57:37 +0000754 if (NumOperands <= 3) {
755 Slots[NumOperands-1] =
756 (CI.getCallingConv() << 1)|unsigned(CI.isTailCall());
Chris Lattnerdee199f2005-05-06 22:34:01 +0000757 if (Slots[NumOperands-1] > MaxOpSlot)
758 MaxOpSlot = Slots[NumOperands-1];
759 }
Reid Spencer3da59db2006-11-27 01:05:10 +0000760 } else if (isa<InvokeInst>(I)) {
Chris Lattnerdee199f2005-05-06 22:34:01 +0000761 // Invoke escape seq has at least 4 operands to encode.
762 ++NumOperands;
Reid Spencerad89bd62004-07-25 18:07:36 +0000763 }
764
765 // Decide which instruction encoding to use. This is determined primarily
766 // by the number of operands, and secondarily by whether or not the max
767 // operand will fit into the instruction encoding. More operands == fewer
768 // bits per operand.
769 //
770 switch (NumOperands) {
771 case 0:
772 case 1:
773 if (MaxOpSlot < (1 << 12)-1) { // -1 because we use 4095 to indicate 0 ops
774 outputInstructionFormat1(&I, Opcode, Slots, Type);
775 return;
776 }
777 break;
778
779 case 2:
780 if (MaxOpSlot < (1 << 8)) {
781 outputInstructionFormat2(&I, Opcode, Slots, Type);
782 return;
783 }
784 break;
785
786 case 3:
787 if (MaxOpSlot < (1 << 6)) {
788 outputInstructionFormat3(&I, Opcode, Slots, Type);
789 return;
790 }
791 break;
792 default:
793 break;
794 }
795 }
796
797 // If we weren't handled before here, we either have a large number of
798 // operands or a large operand index that we are referring to.
799 outputInstructionFormat0(&I, Opcode, Table, Type);
800}
801
802//===----------------------------------------------------------------------===//
803//=== Block Output ===//
804//===----------------------------------------------------------------------===//
805
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000806BytecodeWriter::BytecodeWriter(std::vector<unsigned char> &o, const Module *M)
Reid Spencer798ff642004-05-26 07:37:11 +0000807 : Out(o), Table(M) {
Chris Lattner00950542001-06-06 20:29:01 +0000808
Chris Lattner83bb3d22004-01-14 23:36:54 +0000809 // Emit the signature...
Chris Lattnerc847f7c2006-07-28 22:07:54 +0000810 static const unsigned char *Sig = (const unsigned char*)"llvm";
Reid Spencerad89bd62004-07-25 18:07:36 +0000811 output_data(Sig, Sig+4);
Chris Lattner00950542001-06-06 20:29:01 +0000812
813 // Emit the top level CLASS block.
Reid Spencerad89bd62004-07-25 18:07:36 +0000814 BytecodeBlock ModuleBlock(BytecodeFormat::ModuleBlockID, *this, false, true);
Chris Lattner00950542001-06-06 20:29:01 +0000815
Reid Spenceraacc35a2007-01-26 08:10:24 +0000816 // Output the version identifier
817 output_vbr(BCVersionNum);
Chris Lattner00950542001-06-06 20:29:01 +0000818
Reid Spencercb3595c2004-07-04 11:45:47 +0000819 // The Global type plane comes first
Chris Lattner186a1f72003-03-19 20:56:46 +0000820 {
Chris Lattnerc847f7c2006-07-28 22:07:54 +0000821 BytecodeBlock CPool(BytecodeFormat::GlobalTypePlaneBlockID, *this);
822 outputTypes(Type::FirstDerivedTyID);
Chris Lattner186a1f72003-03-19 20:56:46 +0000823 }
Chris Lattner00950542001-06-06 20:29:01 +0000824
Chris Lattner186a1f72003-03-19 20:56:46 +0000825 // The ModuleInfoBlock follows directly after the type information
Chris Lattnere8fdde12001-09-07 16:39:41 +0000826 outputModuleInfoBlock(M);
827
Chris Lattner186a1f72003-03-19 20:56:46 +0000828 // Output module level constants, used for global variable initializers
829 outputConstants(false);
830
Chris Lattnerb5794002002-04-07 22:49:37 +0000831 // Do the whole module now! Process each function at a time...
Chris Lattner0b12b5f2002-06-25 16:13:21 +0000832 for (Module::const_iterator I = M->begin(), E = M->end(); I != E; ++I)
Chris Lattner186a1f72003-03-19 20:56:46 +0000833 outputFunction(I);
Chris Lattnere8fdde12001-09-07 16:39:41 +0000834
Reid Spencer78d033e2007-01-06 07:24:44 +0000835 // Output the symbole table for types
836 outputTypeSymbolTable(M->getTypeSymbolTable());
837
838 // Output the symbol table for values
839 outputValueSymbolTable(M->getValueSymbolTable());
Chris Lattner00950542001-06-06 20:29:01 +0000840}
841
Chris Lattnerf9d71782004-10-14 01:46:07 +0000842void BytecodeWriter::outputTypes(unsigned TypeNum) {
Reid Spencercb3595c2004-07-04 11:45:47 +0000843 // Write the type plane for types first because earlier planes (e.g. for a
844 // primitive type like float) may have constants constructed using types
845 // coming later (e.g., via getelementptr from a pointer type). The type
846 // plane is needed before types can be fwd or bkwd referenced.
847 const std::vector<const Type*>& Types = Table.getTypes();
848 assert(!Types.empty() && "No types at all?");
849 assert(TypeNum <= Types.size() && "Invalid TypeNo index");
850
851 unsigned NumEntries = Types.size() - TypeNum;
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000852
Reid Spencercb3595c2004-07-04 11:45:47 +0000853 // Output type header: [num entries]
Reid Spencerad89bd62004-07-25 18:07:36 +0000854 output_vbr(NumEntries);
Reid Spencercb3595c2004-07-04 11:45:47 +0000855
856 for (unsigned i = TypeNum; i < TypeNum+NumEntries; ++i)
857 outputType(Types[i]);
858}
859
Vikram S. Advea7dac3d2002-07-14 23:07:51 +0000860// Helper function for outputConstants().
861// Writes out all the constants in the plane Plane starting at entry StartNo.
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000862//
Vikram S. Advea7dac3d2002-07-14 23:07:51 +0000863void BytecodeWriter::outputConstantsInPlane(const std::vector<const Value*>
864 &Plane, unsigned StartNo) {
865 unsigned ValNo = StartNo;
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000866
Chris Lattner83bb3d22004-01-14 23:36:54 +0000867 // Scan through and ignore function arguments, global values, and constant
868 // strings.
869 for (; ValNo < Plane.size() &&
870 (isa<Argument>(Plane[ValNo]) || isa<GlobalValue>(Plane[ValNo]) ||
871 (isa<ConstantArray>(Plane[ValNo]) &&
872 cast<ConstantArray>(Plane[ValNo])->isString())); ValNo++)
Vikram S. Advea7dac3d2002-07-14 23:07:51 +0000873 /*empty*/;
874
875 unsigned NC = ValNo; // Number of constants
Chris Lattner3bc5a602006-01-25 23:08:15 +0000876 for (; NC < Plane.size() && (isa<Constant>(Plane[NC]) ||
877 isa<InlineAsm>(Plane[NC])); NC++)
Vikram S. Advea7dac3d2002-07-14 23:07:51 +0000878 /*empty*/;
879 NC -= ValNo; // Convert from index into count
880 if (NC == 0) return; // Skip empty type planes...
881
Chris Lattnerd6942d72004-01-14 16:54:21 +0000882 // FIXME: Most slabs only have 1 or 2 entries! We should encode this much
883 // more compactly.
884
Reid Spencerb83eb642006-10-20 07:07:24 +0000885 // Put out type header: [num entries][type id number]
Vikram S. Advea7dac3d2002-07-14 23:07:51 +0000886 //
Reid Spencerad89bd62004-07-25 18:07:36 +0000887 output_vbr(NC);
Vikram S. Advea7dac3d2002-07-14 23:07:51 +0000888
Reid Spencerb83eb642006-10-20 07:07:24 +0000889 // Put out the Type ID Number...
Alkis Evlogimenos60596382003-10-17 02:02:40 +0000890 int Slot = Table.getSlot(Plane.front()->getType());
Vikram S. Advea7dac3d2002-07-14 23:07:51 +0000891 assert (Slot != -1 && "Type in constant pool but not in function!!");
Reid Spencerad89bd62004-07-25 18:07:36 +0000892 output_typeid((unsigned)Slot);
Vikram S. Advea7dac3d2002-07-14 23:07:51 +0000893
Vikram S. Advea7dac3d2002-07-14 23:07:51 +0000894 for (unsigned i = ValNo; i < ValNo+NC; ++i) {
895 const Value *V = Plane[i];
Chris Lattner3bc5a602006-01-25 23:08:15 +0000896 if (const Constant *C = dyn_cast<Constant>(V))
Reid Spencere0125b62004-07-18 00:16:21 +0000897 outputConstant(C);
Chris Lattner3bc5a602006-01-25 23:08:15 +0000898 else
899 outputInlineAsm(cast<InlineAsm>(V));
Vikram S. Advea7dac3d2002-07-14 23:07:51 +0000900 }
901}
902
Chris Lattner9e60d8d2005-05-05 22:21:19 +0000903static inline bool hasNullValue(const Type *Ty) {
904 return Ty != Type::LabelTy && Ty != Type::VoidTy && !isa<OpaqueType>(Ty);
Chris Lattner80b97342004-01-17 23:25:43 +0000905}
906
Chris Lattner79df7c02002-03-26 18:01:55 +0000907void BytecodeWriter::outputConstants(bool isFunction) {
Reid Spencerad89bd62004-07-25 18:07:36 +0000908 BytecodeBlock CPool(BytecodeFormat::ConstantPoolBlockID, *this,
Chris Lattner0baa0af2004-01-15 21:06:57 +0000909 true /* Elide block if empty */);
Chris Lattner00950542001-06-06 20:29:01 +0000910
911 unsigned NumPlanes = Table.getNumPlanes();
Chris Lattnerf69315b2003-05-22 18:35:38 +0000912
Reid Spencere0125b62004-07-18 00:16:21 +0000913 if (isFunction)
914 // Output the type plane before any constants!
Chris Lattnera79e7cc2004-10-16 18:18:16 +0000915 outputTypes(Table.getModuleTypeLevel());
Reid Spencere0125b62004-07-18 00:16:21 +0000916 else
Chris Lattnerf9d71782004-10-14 01:46:07 +0000917 // Output module-level string constants before any other constants.
Chris Lattner83bb3d22004-01-14 23:36:54 +0000918 outputConstantStrings();
919
Reid Spencercb3595c2004-07-04 11:45:47 +0000920 for (unsigned pno = 0; pno != NumPlanes; pno++) {
921 const std::vector<const Value*> &Plane = Table.getPlane(pno);
922 if (!Plane.empty()) { // Skip empty type planes...
923 unsigned ValNo = 0;
924 if (isFunction) // Don't re-emit module constants
Reid Spencer0852c802004-07-04 11:46:15 +0000925 ValNo += Table.getModuleLevel(pno);
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000926
Chris Lattner9e60d8d2005-05-05 22:21:19 +0000927 if (hasNullValue(Plane[0]->getType())) {
Reid Spencer0852c802004-07-04 11:46:15 +0000928 // Skip zero initializer
929 if (ValNo == 0)
930 ValNo = 1;
Chris Lattnerf69315b2003-05-22 18:35:38 +0000931 }
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000932
Reid Spencercb3595c2004-07-04 11:45:47 +0000933 // Write out constants in the plane
934 outputConstantsInPlane(Plane, ValNo);
Chris Lattnerf69315b2003-05-22 18:35:38 +0000935 }
Reid Spencercb3595c2004-07-04 11:45:47 +0000936 }
Chris Lattner00950542001-06-06 20:29:01 +0000937}
938
Chris Lattner6b252422003-10-16 18:28:50 +0000939static unsigned getEncodedLinkage(const GlobalValue *GV) {
940 switch (GV->getLinkage()) {
941 default: assert(0 && "Invalid linkage!");
Anton Korobeynikovb74ed072006-09-14 18:23:27 +0000942 case GlobalValue::ExternalLinkage: return 0;
943 case GlobalValue::WeakLinkage: return 1;
944 case GlobalValue::AppendingLinkage: return 2;
945 case GlobalValue::InternalLinkage: return 3;
946 case GlobalValue::LinkOnceLinkage: return 4;
947 case GlobalValue::DLLImportLinkage: return 5;
948 case GlobalValue::DLLExportLinkage: return 6;
949 case GlobalValue::ExternalWeakLinkage: return 7;
Chris Lattner6b252422003-10-16 18:28:50 +0000950 }
951}
952
Anton Korobeynikov7f705592007-01-12 19:20:47 +0000953static unsigned getEncodedVisibility(const GlobalValue *GV) {
954 switch (GV->getVisibility()) {
955 default: assert(0 && "Invalid visibility!");
956 case GlobalValue::DefaultVisibility: return 0;
957 case GlobalValue::HiddenVisibility: return 1;
958 }
959}
960
Chris Lattner00950542001-06-06 20:29:01 +0000961void BytecodeWriter::outputModuleInfoBlock(const Module *M) {
Reid Spencerad89bd62004-07-25 18:07:36 +0000962 BytecodeBlock ModuleInfoBlock(BytecodeFormat::ModuleGlobalInfoBlockID, *this);
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000963
Chris Lattner404cddf2005-11-12 01:33:40 +0000964 // Give numbers to sections as we encounter them.
965 unsigned SectionIDCounter = 0;
966 std::vector<std::string> SectionNames;
967 std::map<std::string, unsigned> SectionID;
968
Chris Lattner70cc3392001-09-10 07:58:01 +0000969 // Output the types for the global variables in the module...
Chris Lattner28caccf2005-05-06 20:27:03 +0000970 for (Module::const_global_iterator I = M->global_begin(),
Chris Lattner8eb52dd2005-11-06 07:11:04 +0000971 End = M->global_end(); I != End; ++I) {
Alkis Evlogimenos60596382003-10-17 02:02:40 +0000972 int Slot = Table.getSlot(I->getType());
Chris Lattner70cc3392001-09-10 07:58:01 +0000973 assert(Slot != -1 && "Module global vars is broken!");
Chris Lattnerd70684f2001-09-18 04:01:05 +0000974
Chris Lattner8eb52dd2005-11-06 07:11:04 +0000975 assert((I->hasInitializer() || !I->hasInternalLinkage()) &&
976 "Global must have an initializer or have external linkage!");
977
Chris Lattner22482a12003-10-18 06:30:21 +0000978 // Fields: bit0 = isConstant, bit1 = hasInitializer, bit2-4=Linkage,
Chris Lattner8eb52dd2005-11-06 07:11:04 +0000979 // bit5+ = Slot # for type.
Anton Korobeynikov7f705592007-01-12 19:20:47 +0000980 bool HasExtensionWord = (I->getAlignment() != 0) ||
981 I->hasSection() ||
982 (I->getVisibility() != GlobalValue::DefaultVisibility);
Chris Lattner8eb52dd2005-11-06 07:11:04 +0000983
984 // If we need to use the extension byte, set linkage=3(internal) and
985 // initializer = 0 (impossible!).
986 if (!HasExtensionWord) {
987 unsigned oSlot = ((unsigned)Slot << 5) | (getEncodedLinkage(I) << 2) |
988 (I->hasInitializer() << 1) | (unsigned)I->isConstant();
989 output_vbr(oSlot);
Anton Korobeynikovb74ed072006-09-14 18:23:27 +0000990 } else {
Chris Lattner8eb52dd2005-11-06 07:11:04 +0000991 unsigned oSlot = ((unsigned)Slot << 5) | (3 << 2) |
992 (0 << 1) | (unsigned)I->isConstant();
993 output_vbr(oSlot);
994
995 // The extension word has this format: bit 0 = has initializer, bit 1-3 =
Anton Korobeynikov7f705592007-01-12 19:20:47 +0000996 // linkage, bit 4-8 = alignment (log2), bit 9 = has SectionID,
997 // bits 10-12 = visibility, bits 13+ = future use.
Jeff Cohenba0ffcc2005-11-12 01:01:50 +0000998 unsigned ExtWord = (unsigned)I->hasInitializer() |
999 (getEncodedLinkage(I) << 1) |
Chris Lattner404cddf2005-11-12 01:33:40 +00001000 ((Log2_32(I->getAlignment())+1) << 4) |
Anton Korobeynikov7f705592007-01-12 19:20:47 +00001001 ((unsigned)I->hasSection() << 9) |
1002 (getEncodedVisibility(I) << 10);
Chris Lattner8eb52dd2005-11-06 07:11:04 +00001003 output_vbr(ExtWord);
Chris Lattner404cddf2005-11-12 01:33:40 +00001004 if (I->hasSection()) {
1005 // Give section names unique ID's.
1006 unsigned &Entry = SectionID[I->getSection()];
1007 if (Entry == 0) {
1008 Entry = ++SectionIDCounter;
1009 SectionNames.push_back(I->getSection());
1010 }
1011 output_vbr(Entry);
1012 }
Chris Lattner8eb52dd2005-11-06 07:11:04 +00001013 }
Chris Lattnerd70684f2001-09-18 04:01:05 +00001014
Chris Lattner1b98c5c2001-10-13 06:48:38 +00001015 // If we have an initializer, output it now.
Chris Lattner0b12b5f2002-06-25 16:13:21 +00001016 if (I->hasInitializer()) {
Alkis Evlogimenos60596382003-10-17 02:02:40 +00001017 Slot = Table.getSlot((Value*)I->getInitializer());
Chris Lattnerd70684f2001-09-18 04:01:05 +00001018 assert(Slot != -1 && "No slot for global var initializer!");
Reid Spencerad89bd62004-07-25 18:07:36 +00001019 output_vbr((unsigned)Slot);
Chris Lattnerd70684f2001-09-18 04:01:05 +00001020 }
Chris Lattner70cc3392001-09-10 07:58:01 +00001021 }
Reid Spencerad89bd62004-07-25 18:07:36 +00001022 output_typeid((unsigned)Table.getSlot(Type::VoidTy));
Chris Lattner70cc3392001-09-10 07:58:01 +00001023
Chris Lattnera79e7cc2004-10-16 18:18:16 +00001024 // Output the types of the functions in this module.
Chris Lattner7fc9fe32001-06-27 23:41:11 +00001025 for (Module::const_iterator I = M->begin(), End = M->end(); I != End; ++I) {
Alkis Evlogimenos60596382003-10-17 02:02:40 +00001026 int Slot = Table.getSlot(I->getType());
Chris Lattnera79e7cc2004-10-16 18:18:16 +00001027 assert(Slot != -1 && "Module slot calculator is broken!");
Chris Lattner00950542001-06-06 20:29:01 +00001028 assert(Slot >= Type::FirstDerivedTyID && "Derived type not in range!");
Chris Lattnere73bd452005-11-06 07:43:39 +00001029 assert(((Slot << 6) >> 6) == Slot && "Slot # too big!");
Chris Lattner54b369e2005-11-06 07:46:13 +00001030 unsigned CC = I->getCallingConv()+1;
1031 unsigned ID = (Slot << 5) | (CC & 15);
Chris Lattner479ffeb2005-05-06 20:42:57 +00001032
Chris Lattnerd6e431f2004-11-15 22:39:49 +00001033 if (I->isExternal()) // If external, we don't have an FunctionInfo block.
1034 ID |= 1 << 4;
Chris Lattnere73bd452005-11-06 07:43:39 +00001035
Anton Korobeynikovb74ed072006-09-14 18:23:27 +00001036 if (I->getAlignment() || I->hasSection() || (CC & ~15) != 0 ||
1037 (I->isExternal() && I->hasDLLImportLinkage()) ||
1038 (I->isExternal() && I->hasExternalWeakLinkage())
1039 )
Chris Lattnere73bd452005-11-06 07:43:39 +00001040 ID |= 1 << 31; // Do we need an extension word?
1041
Chris Lattnera79e7cc2004-10-16 18:18:16 +00001042 output_vbr(ID);
Chris Lattnere73bd452005-11-06 07:43:39 +00001043
1044 if (ID & (1 << 31)) {
1045 // Extension byte: bits 0-4 = alignment, bits 5-9 = top nibble of calling
Anton Korobeynikovb74ed072006-09-14 18:23:27 +00001046 // convention, bit 10 = hasSectionID., bits 11-12 = external linkage type
1047 unsigned extLinkage = 0;
1048
1049 if (I->isExternal()) {
1050 if (I->hasDLLImportLinkage()) {
1051 extLinkage = 1;
1052 } else if (I->hasExternalWeakLinkage()) {
1053 extLinkage = 2;
1054 }
1055 }
1056
Chris Lattner404cddf2005-11-12 01:33:40 +00001057 ID = (Log2_32(I->getAlignment())+1) | ((CC >> 4) << 5) |
Anton Korobeynikovb74ed072006-09-14 18:23:27 +00001058 (I->hasSection() << 10) |
1059 ((extLinkage & 3) << 11);
Chris Lattnere73bd452005-11-06 07:43:39 +00001060 output_vbr(ID);
Chris Lattner404cddf2005-11-12 01:33:40 +00001061
1062 // Give section names unique ID's.
1063 if (I->hasSection()) {
1064 unsigned &Entry = SectionID[I->getSection()];
1065 if (Entry == 0) {
1066 Entry = ++SectionIDCounter;
1067 SectionNames.push_back(I->getSection());
1068 }
1069 output_vbr(Entry);
1070 }
Chris Lattnere73bd452005-11-06 07:43:39 +00001071 }
Chris Lattner00950542001-06-06 20:29:01 +00001072 }
Chris Lattnera79e7cc2004-10-16 18:18:16 +00001073 output_vbr((unsigned)Table.getSlot(Type::VoidTy) << 5);
Reid Spencerad89bd62004-07-25 18:07:36 +00001074
Chris Lattnera79e7cc2004-10-16 18:18:16 +00001075 // Emit the list of dependent libraries for the Module.
Reid Spencer5ac88122004-07-25 21:32:02 +00001076 Module::lib_iterator LI = M->lib_begin();
1077 Module::lib_iterator LE = M->lib_end();
Chris Lattnera79e7cc2004-10-16 18:18:16 +00001078 output_vbr(unsigned(LE - LI)); // Emit the number of dependent libraries.
1079 for (; LI != LE; ++LI)
Reid Spencer38d54be2004-08-17 07:45:14 +00001080 output(*LI);
Reid Spencerad89bd62004-07-25 18:07:36 +00001081
1082 // Output the target triple from the module
Reid Spencer38d54be2004-08-17 07:45:14 +00001083 output(M->getTargetTriple());
Reid Spenceraacc35a2007-01-26 08:10:24 +00001084
1085 // Output the data layout from the module
1086 output(M->getDataLayout());
Chris Lattner404cddf2005-11-12 01:33:40 +00001087
1088 // Emit the table of section names.
1089 output_vbr((unsigned)SectionNames.size());
1090 for (unsigned i = 0, e = SectionNames.size(); i != e; ++i)
1091 output(SectionNames[i]);
Chris Lattner7e6db762006-01-23 23:43:17 +00001092
1093 // Output the inline asm string.
Chris Lattner66316012006-01-24 04:14:29 +00001094 output(M->getModuleInlineAsm());
Chris Lattner00950542001-06-06 20:29:01 +00001095}
1096
Chris Lattnercf3e67f2004-01-18 21:08:52 +00001097void BytecodeWriter::outputInstructions(const Function *F) {
Reid Spencerad89bd62004-07-25 18:07:36 +00001098 BytecodeBlock ILBlock(BytecodeFormat::InstructionListBlockID, *this);
Chris Lattnercf3e67f2004-01-18 21:08:52 +00001099 for (Function::const_iterator BB = F->begin(), E = F->end(); BB != E; ++BB)
1100 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I!=E; ++I)
1101 outputInstruction(*I);
Chris Lattnercf3e67f2004-01-18 21:08:52 +00001102}
1103
Chris Lattner186a1f72003-03-19 20:56:46 +00001104void BytecodeWriter::outputFunction(const Function *F) {
Chris Lattnerfd7f8fe2004-11-15 21:56:33 +00001105 // If this is an external function, there is nothing else to emit!
1106 if (F->isExternal()) return;
1107
Chris Lattnerd6e431f2004-11-15 22:39:49 +00001108 BytecodeBlock FunctionBlock(BytecodeFormat::FunctionBlockID, *this);
Anton Korobeynikov7f705592007-01-12 19:20:47 +00001109 unsigned rWord = (getEncodedVisibility(F) << 16) | getEncodedLinkage(F);
1110 output_vbr(rWord);
Chris Lattnerd6e431f2004-11-15 22:39:49 +00001111
Chris Lattnercf3e67f2004-01-18 21:08:52 +00001112 // Get slot information about the function...
1113 Table.incorporateFunction(F);
1114
1115 if (Table.getCompactionTable().empty()) {
1116 // Output information about the constants in the function if the compaction
1117 // table is not being used.
Chris Lattnere8fdde12001-09-07 16:39:41 +00001118 outputConstants(true);
Chris Lattnercf3e67f2004-01-18 21:08:52 +00001119 } else {
1120 // Otherwise, emit the compaction table.
1121 outputCompactionTable();
Chris Lattnere8fdde12001-09-07 16:39:41 +00001122 }
Misha Brukman23c6d2c2005-04-21 21:48:46 +00001123
Chris Lattnercf3e67f2004-01-18 21:08:52 +00001124 // Output all of the instructions in the body of the function
1125 outputInstructions(F);
Misha Brukman23c6d2c2005-04-21 21:48:46 +00001126
Chris Lattnercf3e67f2004-01-18 21:08:52 +00001127 // If needed, output the symbol table for the function...
Reid Spencer78d033e2007-01-06 07:24:44 +00001128 outputValueSymbolTable(F->getValueSymbolTable());
Misha Brukman23c6d2c2005-04-21 21:48:46 +00001129
Chris Lattnercf3e67f2004-01-18 21:08:52 +00001130 Table.purgeFunction();
1131}
1132
1133void BytecodeWriter::outputCompactionTablePlane(unsigned PlaneNo,
1134 const std::vector<const Value*> &Plane,
1135 unsigned StartNo) {
1136 unsigned End = Table.getModuleLevel(PlaneNo);
Chris Lattner52f86d62004-01-20 00:54:06 +00001137 if (Plane.empty() || StartNo == End || End == 0) return; // Nothing to emit
Chris Lattnercf3e67f2004-01-18 21:08:52 +00001138 assert(StartNo < End && "Cannot emit negative range!");
1139 assert(StartNo < Plane.size() && End <= Plane.size());
1140
Chris Lattnercf3e67f2004-01-18 21:08:52 +00001141 // Do not emit the null initializer!
Reid Spencercb3595c2004-07-04 11:45:47 +00001142 ++StartNo;
Chris Lattnercf3e67f2004-01-18 21:08:52 +00001143
Chris Lattner24102432004-01-18 22:35:34 +00001144 // Figure out which encoding to use. By far the most common case we have is
1145 // to emit 0-2 entries in a compaction table plane.
1146 switch (End-StartNo) {
1147 case 0: // Avoid emitting two vbr's if possible.
1148 case 1:
1149 case 2:
Reid Spencerad89bd62004-07-25 18:07:36 +00001150 output_vbr((PlaneNo << 2) | End-StartNo);
Chris Lattner24102432004-01-18 22:35:34 +00001151 break;
1152 default:
1153 // Output the number of things.
Reid Spencerad89bd62004-07-25 18:07:36 +00001154 output_vbr((unsigned(End-StartNo) << 2) | 3);
1155 output_typeid(PlaneNo); // Emit the type plane this is
Chris Lattner24102432004-01-18 22:35:34 +00001156 break;
1157 }
1158
Chris Lattnercf3e67f2004-01-18 21:08:52 +00001159 for (unsigned i = StartNo; i != End; ++i)
Reid Spencerad89bd62004-07-25 18:07:36 +00001160 output_vbr(Table.getGlobalSlot(Plane[i]));
Chris Lattnercf3e67f2004-01-18 21:08:52 +00001161}
1162
Reid Spencercb3595c2004-07-04 11:45:47 +00001163void BytecodeWriter::outputCompactionTypes(unsigned StartNo) {
1164 // Get the compaction type table from the slot calculator
1165 const std::vector<const Type*> &CTypes = Table.getCompactionTypes();
1166
1167 // The compaction types may have been uncompactified back to the
1168 // global types. If so, we just write an empty table
Chris Lattnerc847f7c2006-07-28 22:07:54 +00001169 if (CTypes.size() == 0) {
Reid Spencerad89bd62004-07-25 18:07:36 +00001170 output_vbr(0U);
Reid Spencercb3595c2004-07-04 11:45:47 +00001171 return;
1172 }
1173
1174 assert(CTypes.size() >= StartNo && "Invalid compaction types start index");
1175
1176 // Determine how many types to write
1177 unsigned NumTypes = CTypes.size() - StartNo;
1178
1179 // Output the number of types.
Reid Spencerad89bd62004-07-25 18:07:36 +00001180 output_vbr(NumTypes);
Reid Spencercb3595c2004-07-04 11:45:47 +00001181
1182 for (unsigned i = StartNo; i < StartNo+NumTypes; ++i)
Reid Spencerad89bd62004-07-25 18:07:36 +00001183 output_typeid(Table.getGlobalSlot(CTypes[i]));
Reid Spencercb3595c2004-07-04 11:45:47 +00001184}
1185
Chris Lattnercf3e67f2004-01-18 21:08:52 +00001186void BytecodeWriter::outputCompactionTable() {
Reid Spencer0033c182004-08-27 00:38:44 +00001187 // Avoid writing the compaction table at all if there is no content.
1188 if (Table.getCompactionTypes().size() >= Type::FirstDerivedTyID ||
1189 (!Table.CompactionTableIsEmpty())) {
Misha Brukman23c6d2c2005-04-21 21:48:46 +00001190 BytecodeBlock CTB(BytecodeFormat::CompactionTableBlockID, *this,
Reid Spencer0033c182004-08-27 00:38:44 +00001191 true/*ElideIfEmpty*/);
Chris Lattnerf9d71782004-10-14 01:46:07 +00001192 const std::vector<std::vector<const Value*> > &CT =
1193 Table.getCompactionTable();
Misha Brukman23c6d2c2005-04-21 21:48:46 +00001194
Reid Spencer0033c182004-08-27 00:38:44 +00001195 // First things first, emit the type compaction table if there is one.
1196 outputCompactionTypes(Type::FirstDerivedTyID);
Chris Lattnercf3e67f2004-01-18 21:08:52 +00001197
Reid Spencer0033c182004-08-27 00:38:44 +00001198 for (unsigned i = 0, e = CT.size(); i != e; ++i)
1199 outputCompactionTablePlane(i, CT[i], 0);
1200 }
Chris Lattner00950542001-06-06 20:29:01 +00001201}
1202
Reid Spencer78d033e2007-01-06 07:24:44 +00001203void BytecodeWriter::outputTypeSymbolTable(const TypeSymbolTable &TST) {
1204 // Do not output the block for an empty symbol table, it just wastes
Chris Lattner737d3cd2004-01-10 19:56:59 +00001205 // space!
Reid Spencer78d033e2007-01-06 07:24:44 +00001206 if (TST.empty()) return;
Chris Lattner737d3cd2004-01-10 19:56:59 +00001207
Reid Spencer78d033e2007-01-06 07:24:44 +00001208 // Create a header for the symbol table
1209 BytecodeBlock SymTabBlock(BytecodeFormat::TypeSymbolTableBlockID, *this,
Chris Lattnerf9d71782004-10-14 01:46:07 +00001210 true/*ElideIfEmpty*/);
Misha Brukman23c6d2c2005-04-21 21:48:46 +00001211 // Write the number of types
Reid Spencer78d033e2007-01-06 07:24:44 +00001212 output_vbr(TST.size());
Reid Spencer250c4182004-08-17 02:59:02 +00001213
1214 // Write each of the types
Reid Spencer78d033e2007-01-06 07:24:44 +00001215 for (TypeSymbolTable::const_iterator TI = TST.begin(), TE = TST.end();
1216 TI != TE; ++TI) {
Reid Spencer250c4182004-08-17 02:59:02 +00001217 // Symtab entry:[def slot #][name]
Reid Spencerad89bd62004-07-25 18:07:36 +00001218 output_typeid((unsigned)Table.getSlot(TI->second));
Misha Brukman23c6d2c2005-04-21 21:48:46 +00001219 output(TI->first);
Reid Spencer94f2df22004-05-25 17:29:59 +00001220 }
Reid Spencer78d033e2007-01-06 07:24:44 +00001221}
1222
1223void BytecodeWriter::outputValueSymbolTable(const SymbolTable &MST) {
1224 // Do not output the Bytecode block for an empty symbol table, it just wastes
1225 // space!
1226 if (MST.isEmpty()) return;
1227
1228 BytecodeBlock SymTabBlock(BytecodeFormat::ValueSymbolTableBlockID, *this,
1229 true/*ElideIfEmpty*/);
Reid Spencer94f2df22004-05-25 17:29:59 +00001230
1231 // Now do each of the type planes in order.
Misha Brukman23c6d2c2005-04-21 21:48:46 +00001232 for (SymbolTable::plane_const_iterator PI = MST.plane_begin(),
Reid Spencer94f2df22004-05-25 17:29:59 +00001233 PE = MST.plane_end(); PI != PE; ++PI) {
1234 SymbolTable::value_const_iterator I = MST.value_begin(PI->first);
1235 SymbolTable::value_const_iterator End = MST.value_end(PI->first);
Chris Lattner00950542001-06-06 20:29:01 +00001236 int Slot;
Misha Brukman23c6d2c2005-04-21 21:48:46 +00001237
Chris Lattner00950542001-06-06 20:29:01 +00001238 if (I == End) continue; // Don't mess with an absent type...
1239
Reid Spencer250c4182004-08-17 02:59:02 +00001240 // Write the number of values in this plane
Chris Lattner001d16a2005-03-07 02:59:36 +00001241 output_vbr((unsigned)PI->second.size());
Chris Lattner00950542001-06-06 20:29:01 +00001242
Reid Spencer250c4182004-08-17 02:59:02 +00001243 // Write the slot number of the type for this plane
Reid Spencer94f2df22004-05-25 17:29:59 +00001244 Slot = Table.getSlot(PI->first);
Chris Lattner00950542001-06-06 20:29:01 +00001245 assert(Slot != -1 && "Type in symtab, but not in table!");
Reid Spencerad89bd62004-07-25 18:07:36 +00001246 output_typeid((unsigned)Slot);
Chris Lattner00950542001-06-06 20:29:01 +00001247
Reid Spencer250c4182004-08-17 02:59:02 +00001248 // Write each of the values in this plane
Chris Lattner7fc9fe32001-06-27 23:41:11 +00001249 for (; I != End; ++I) {
Chris Lattner00950542001-06-06 20:29:01 +00001250 // Symtab entry: [def slot #][name]
Alkis Evlogimenos60596382003-10-17 02:02:40 +00001251 Slot = Table.getSlot(I->second);
Chris Lattnere8fdde12001-09-07 16:39:41 +00001252 assert(Slot != -1 && "Value in symtab but has no slot number!!");
Reid Spencerad89bd62004-07-25 18:07:36 +00001253 output_vbr((unsigned)Slot);
Reid Spencer38d54be2004-08-17 07:45:14 +00001254 output(I->first);
Chris Lattner00950542001-06-06 20:29:01 +00001255 }
1256 }
1257}
1258
Bill Wendlinge8156192006-12-07 01:30:32 +00001259void llvm::WriteBytecodeToFile(const Module *M, OStream &Out,
Chris Lattnerc847f7c2006-07-28 22:07:54 +00001260 bool compress) {
Reid Spencerad89bd62004-07-25 18:07:36 +00001261 assert(M && "You can't write a null module!!");
Chris Lattner00950542001-06-06 20:29:01 +00001262
Reid Spencer32f55532006-06-07 23:18:34 +00001263 // Make sure that std::cout is put into binary mode for systems
1264 // that care.
Bill Wendlinge8156192006-12-07 01:30:32 +00001265 if (Out == cout)
Reid Spencer32f55532006-06-07 23:18:34 +00001266 sys::Program::ChangeStdoutToBinary();
1267
Reid Spencer17f52c52004-11-06 23:17:23 +00001268 // Create a vector of unsigned char for the bytecode output. We
1269 // reserve 256KBytes of space in the vector so that we avoid doing
1270 // lots of little allocations. 256KBytes is sufficient for a large
1271 // proportion of the bytecode files we will encounter. Larger files
1272 // will be automatically doubled in size as needed (std::vector
1273 // behavior).
Reid Spencerad89bd62004-07-25 18:07:36 +00001274 std::vector<unsigned char> Buffer;
Reid Spencer17f52c52004-11-06 23:17:23 +00001275 Buffer.reserve(256 * 1024);
Chris Lattner00950542001-06-06 20:29:01 +00001276
Reid Spencer17f52c52004-11-06 23:17:23 +00001277 // The BytecodeWriter populates Buffer for us.
Reid Spencerad89bd62004-07-25 18:07:36 +00001278 BytecodeWriter BCW(Buffer, M);
Chris Lattner00950542001-06-06 20:29:01 +00001279
Reid Spencer17f52c52004-11-06 23:17:23 +00001280 // Keep track of how much we've written
Chris Lattnerce6ef112002-07-26 18:40:14 +00001281 BytesWritten += Buffer.size();
1282
Reid Spencer17f52c52004-11-06 23:17:23 +00001283 // Determine start and end points of the Buffer
Reid Spencer83296f52004-11-07 18:17:38 +00001284 const unsigned char *FirstByte = &Buffer.front();
Reid Spencer17f52c52004-11-06 23:17:23 +00001285
1286 // If we're supposed to compress this mess ...
1287 if (compress) {
1288
1289 // We signal compression by using an alternate magic number for the
Reid Spencer83296f52004-11-07 18:17:38 +00001290 // file. The compressed bytecode file's magic number is "llvc" instead
Misha Brukman23c6d2c2005-04-21 21:48:46 +00001291 // of "llvm".
Reid Spencer83296f52004-11-07 18:17:38 +00001292 char compressed_magic[4];
1293 compressed_magic[0] = 'l';
1294 compressed_magic[1] = 'l';
1295 compressed_magic[2] = 'v';
1296 compressed_magic[3] = 'c';
Reid Spencer17f52c52004-11-06 23:17:23 +00001297
Bill Wendling68fe61d2006-11-29 00:19:40 +00001298 Out.stream()->write(compressed_magic,4);
Reid Spencer17f52c52004-11-06 23:17:23 +00001299
Reid Spencera70d84d2004-11-14 22:01:41 +00001300 // Compress everything after the magic number (which we altered)
Reid Spencer3ed469c2006-11-02 20:25:50 +00001301 Compressor::compressToStream(
Reid Spencer17f52c52004-11-06 23:17:23 +00001302 (char*)(FirstByte+4), // Skip the magic number
1303 Buffer.size()-4, // Skip the magic number
Bill Wendling68fe61d2006-11-29 00:19:40 +00001304 *Out.stream() // Where to write compressed data
Reid Spencer17f52c52004-11-06 23:17:23 +00001305 );
1306
Reid Spencer17f52c52004-11-06 23:17:23 +00001307 } else {
1308
1309 // We're not compressing, so just write the entire block.
Bill Wendling68fe61d2006-11-29 00:19:40 +00001310 Out.stream()->write((char*)FirstByte, Buffer.size());
Chris Lattnere8fdde12001-09-07 16:39:41 +00001311 }
Reid Spencer17f52c52004-11-06 23:17:23 +00001312
1313 // make sure it hits disk now
Bill Wendling68fe61d2006-11-29 00:19:40 +00001314 Out.stream()->flush();
Chris Lattner00950542001-06-06 20:29:01 +00001315}