blob: 58cc13a1414e97dba588c7786b7c5016ba8815cf [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 Spencerad89bd62004-07-25 18:07:36 +000030#include "llvm/Support/GetElementPtrTypeIterator.h"
Reid Spencer17f52c52004-11-06 23:17:23 +000031#include "llvm/Support/Compressor.h"
Jim Laskeycb6682f2005-08-17 19:34:49 +000032#include "llvm/Support/MathExtras.h"
Bill Wendling68fe61d2006-11-29 00:19:40 +000033#include "llvm/Support/Streams.h"
Reid Spencer32f55532006-06-07 23:18:34 +000034#include "llvm/System/Program.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000035#include "llvm/ADT/STLExtras.h"
36#include "llvm/ADT/Statistic.h"
Chris Lattner32abce62004-01-10 19:10:01 +000037#include <cstring>
Chris Lattner00950542001-06-06 20:29:01 +000038#include <algorithm>
Chris Lattner44f549b2004-01-10 18:49:43 +000039using namespace llvm;
Brian Gaeked0fde302003-11-11 22:41:34 +000040
Reid Spencer38d54be2004-08-17 07:45:14 +000041/// This value needs to be incremented every time the bytecode format changes
42/// so that the reader can distinguish which format of the bytecode file has
43/// been written.
44/// @brief The bytecode version number
Reid Spencer6996feb2006-11-08 21:27:54 +000045const unsigned BCVersionNum = 7;
Reid Spencer38d54be2004-08-17 07:45:14 +000046
Chris Lattner635cd932002-07-23 19:56:44 +000047static RegisterPass<WriteBytecodePass> X("emitbytecode", "Bytecode Writer");
48
Chris Lattner1c560ad2006-12-19 23:16:47 +000049STATISTIC(BytesWritten, "Number of bytecode bytes written");
Chris Lattner635cd932002-07-23 19:56:44 +000050
Reid Spencerad89bd62004-07-25 18:07:36 +000051//===----------------------------------------------------------------------===//
52//=== Output Primitives ===//
53//===----------------------------------------------------------------------===//
54
55// output - If a position is specified, it must be in the valid portion of the
Misha Brukman23c6d2c2005-04-21 21:48:46 +000056// string... note that this should be inlined always so only the relevant IF
Reid Spencerad89bd62004-07-25 18:07:36 +000057// body should be included.
58inline void BytecodeWriter::output(unsigned i, int pos) {
59 if (pos == -1) { // Be endian clean, little endian is our friend
Misha Brukman23c6d2c2005-04-21 21:48:46 +000060 Out.push_back((unsigned char)i);
Reid Spencerad89bd62004-07-25 18:07:36 +000061 Out.push_back((unsigned char)(i >> 8));
62 Out.push_back((unsigned char)(i >> 16));
63 Out.push_back((unsigned char)(i >> 24));
64 } else {
65 Out[pos ] = (unsigned char)i;
66 Out[pos+1] = (unsigned char)(i >> 8);
67 Out[pos+2] = (unsigned char)(i >> 16);
68 Out[pos+3] = (unsigned char)(i >> 24);
69 }
70}
71
72inline void BytecodeWriter::output(int i) {
73 output((unsigned)i);
74}
75
76/// output_vbr - Output an unsigned value, by using the least number of bytes
77/// possible. This is useful because many of our "infinite" values are really
78/// very small most of the time; but can be large a few times.
Misha Brukman23c6d2c2005-04-21 21:48:46 +000079/// Data format used: If you read a byte with the high bit set, use the low
80/// seven bits as data and then read another byte.
Reid Spencerad89bd62004-07-25 18:07:36 +000081inline void BytecodeWriter::output_vbr(uint64_t i) {
82 while (1) {
83 if (i < 0x80) { // done?
84 Out.push_back((unsigned char)i); // We know the high bit is clear...
85 return;
86 }
Misha Brukman23c6d2c2005-04-21 21:48:46 +000087
Reid Spencerad89bd62004-07-25 18:07:36 +000088 // Nope, we are bigger than a character, output the next 7 bits and set the
89 // high bit to say that there is more coming...
90 Out.push_back(0x80 | ((unsigned char)i & 0x7F));
91 i >>= 7; // Shift out 7 bits now...
92 }
93}
94
95inline void BytecodeWriter::output_vbr(unsigned i) {
96 while (1) {
97 if (i < 0x80) { // done?
98 Out.push_back((unsigned char)i); // We know the high bit is clear...
99 return;
100 }
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000101
Reid Spencerad89bd62004-07-25 18:07:36 +0000102 // Nope, we are bigger than a character, output the next 7 bits and set the
103 // high bit to say that there is more coming...
104 Out.push_back(0x80 | ((unsigned char)i & 0x7F));
105 i >>= 7; // Shift out 7 bits now...
106 }
107}
108
109inline void BytecodeWriter::output_typeid(unsigned i) {
110 if (i <= 0x00FFFFFF)
111 this->output_vbr(i);
112 else {
113 this->output_vbr(0x00FFFFFF);
114 this->output_vbr(i);
115 }
116}
117
118inline void BytecodeWriter::output_vbr(int64_t i) {
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000119 if (i < 0)
Reid Spencerad89bd62004-07-25 18:07:36 +0000120 output_vbr(((uint64_t)(-i) << 1) | 1); // Set low order sign bit...
121 else
122 output_vbr((uint64_t)i << 1); // Low order bit is clear.
123}
124
125
126inline void BytecodeWriter::output_vbr(int i) {
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000127 if (i < 0)
Reid Spencerad89bd62004-07-25 18:07:36 +0000128 output_vbr(((unsigned)(-i) << 1) | 1); // Set low order sign bit...
129 else
130 output_vbr((unsigned)i << 1); // Low order bit is clear.
131}
132
Reid Spencer38d54be2004-08-17 07:45:14 +0000133inline void BytecodeWriter::output(const std::string &s) {
Reid Spencerad89bd62004-07-25 18:07:36 +0000134 unsigned Len = s.length();
Chris Lattnerc847f7c2006-07-28 22:07:54 +0000135 output_vbr(Len); // Strings may have an arbitrary length.
Reid Spencerad89bd62004-07-25 18:07:36 +0000136 Out.insert(Out.end(), s.begin(), s.end());
Reid Spencerad89bd62004-07-25 18:07:36 +0000137}
138
139inline void BytecodeWriter::output_data(const void *Ptr, const void *End) {
140 Out.insert(Out.end(), (const unsigned char*)Ptr, (const unsigned char*)End);
141}
142
143inline void BytecodeWriter::output_float(float& FloatVal) {
144 /// FIXME: This isn't optimal, it has size problems on some platforms
145 /// where FP is not IEEE.
Jim Laskeycb6682f2005-08-17 19:34:49 +0000146 uint32_t i = FloatToBits(FloatVal);
Chris Lattnerc847f7c2006-07-28 22:07:54 +0000147 Out.push_back( static_cast<unsigned char>( (i ) & 0xFF));
148 Out.push_back( static_cast<unsigned char>( (i >> 8 ) & 0xFF));
Jim Laskeycb6682f2005-08-17 19:34:49 +0000149 Out.push_back( static_cast<unsigned char>( (i >> 16) & 0xFF));
150 Out.push_back( static_cast<unsigned char>( (i >> 24) & 0xFF));
Reid Spencerad89bd62004-07-25 18:07:36 +0000151}
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.
Jim Laskeycb6682f2005-08-17 19:34:49 +0000156 uint64_t i = DoubleToBits(DoubleVal);
Chris Lattnerc847f7c2006-07-28 22:07:54 +0000157 Out.push_back( static_cast<unsigned char>( (i ) & 0xFF));
158 Out.push_back( static_cast<unsigned char>( (i >> 8 ) & 0xFF));
Jim Laskeycb6682f2005-08-17 19:34:49 +0000159 Out.push_back( static_cast<unsigned char>( (i >> 16) & 0xFF));
160 Out.push_back( static_cast<unsigned char>( (i >> 24) & 0xFF));
161 Out.push_back( static_cast<unsigned char>( (i >> 32) & 0xFF));
162 Out.push_back( static_cast<unsigned char>( (i >> 40) & 0xFF));
163 Out.push_back( static_cast<unsigned char>( (i >> 48) & 0xFF));
164 Out.push_back( static_cast<unsigned char>( (i >> 56) & 0xFF));
Reid Spencerad89bd62004-07-25 18:07:36 +0000165}
166
Chris Lattnerc76ea432005-11-12 18:34:09 +0000167inline BytecodeBlock::BytecodeBlock(unsigned ID, BytecodeWriter &w,
168 bool elideIfEmpty, bool hasLongFormat)
Reid Spencerad89bd62004-07-25 18:07:36 +0000169 : Id(ID), Writer(w), ElideIfEmpty(elideIfEmpty), HasLongFormat(hasLongFormat){
170
171 if (HasLongFormat) {
172 w.output(ID);
173 w.output(0U); // For length in long format
174 } else {
175 w.output(0U); /// Place holder for ID and length for this block
176 }
177 Loc = w.size();
178}
179
Chris Lattnerb0bf6642004-10-14 01:35:17 +0000180inline BytecodeBlock::~BytecodeBlock() { // Do backpatch when block goes out
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000181 // of scope...
Reid Spencerad89bd62004-07-25 18:07:36 +0000182 if (Loc == Writer.size() && ElideIfEmpty) {
183 // If the block is empty, and we are allowed to, do not emit the block at
184 // all!
185 Writer.resize(Writer.size()-(HasLongFormat?8:4));
186 return;
187 }
188
Reid Spencerad89bd62004-07-25 18:07:36 +0000189 if (HasLongFormat)
190 Writer.output(unsigned(Writer.size()-Loc), int(Loc-4));
191 else
192 Writer.output(unsigned(Writer.size()-Loc) << 5 | (Id & 0x1F), int(Loc-4));
Reid Spencerad89bd62004-07-25 18:07:36 +0000193}
194
195//===----------------------------------------------------------------------===//
196//=== Constant Output ===//
197//===----------------------------------------------------------------------===//
198
199void BytecodeWriter::outputType(const Type *T) {
Andrew Lenharth38ecbf12006-12-08 18:06:16 +0000200 const StructType* STy = dyn_cast<StructType>(T);
201 if(STy && STy->isPacked())
202 output_vbr((unsigned)Type::BC_ONLY_PackedStructTyID);
203 else
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);
Reid Spencer88cfda22006-12-31 05:44:24 +0000217 output_vbr(unsigned(MT->getParamAttrs(0)));
Reid Spencerad89bd62004-07-25 18:07:36 +0000218
219 // Output the number of arguments to function (+1 if varargs):
220 output_vbr((unsigned)MT->getNumParams()+MT->isVarArg());
221
222 // Output all of the arguments...
223 FunctionType::param_iterator I = MT->param_begin();
Reid Spencer88cfda22006-12-31 05:44:24 +0000224 unsigned Idx = 1;
Reid Spencerad89bd62004-07-25 18:07:36 +0000225 for (; I != MT->param_end(); ++I) {
226 Slot = Table.getSlot(*I);
227 assert(Slot != -1 && "Type used but not available!!");
228 output_typeid((unsigned)Slot);
Reid Spencer88cfda22006-12-31 05:44:24 +0000229 output_vbr(unsigned(MT->getParamAttrs(Idx)));
230 Idx++;
Reid Spencerad89bd62004-07-25 18:07:36 +0000231 }
232
233 // Terminate list with VoidTy if we are a varargs function...
234 if (MT->isVarArg())
235 output_typeid((unsigned)Type::VoidTyID);
236 break;
237 }
238
239 case Type::ArrayTyID: {
240 const ArrayType *AT = cast<ArrayType>(T);
241 int Slot = Table.getSlot(AT->getElementType());
242 assert(Slot != -1 && "Type used but not available!!");
243 output_typeid((unsigned)Slot);
Reid Spencerad89bd62004-07-25 18:07:36 +0000244 output_vbr(AT->getNumElements());
245 break;
246 }
247
Brian Gaeke715c90b2004-08-20 06:00:58 +0000248 case Type::PackedTyID: {
249 const PackedType *PT = cast<PackedType>(T);
250 int Slot = Table.getSlot(PT->getElementType());
251 assert(Slot != -1 && "Type used but not available!!");
252 output_typeid((unsigned)Slot);
253 output_vbr(PT->getNumElements());
254 break;
255 }
256
Reid Spencerad89bd62004-07-25 18:07:36 +0000257 case Type::StructTyID: {
258 const StructType *ST = cast<StructType>(T);
Reid Spencerad89bd62004-07-25 18:07:36 +0000259 // Output all of the element types...
260 for (StructType::element_iterator I = ST->element_begin(),
261 E = ST->element_end(); I != E; ++I) {
262 int Slot = Table.getSlot(*I);
263 assert(Slot != -1 && "Type used but not available!!");
264 output_typeid((unsigned)Slot);
265 }
266
267 // Terminate list with VoidTy
268 output_typeid((unsigned)Type::VoidTyID);
269 break;
270 }
271
272 case Type::PointerTyID: {
273 const PointerType *PT = cast<PointerType>(T);
274 int Slot = Table.getSlot(PT->getElementType());
275 assert(Slot != -1 && "Type used but not available!!");
276 output_typeid((unsigned)Slot);
277 break;
278 }
279
Chris Lattnerb0bf6642004-10-14 01:35:17 +0000280 case Type::OpaqueTyID:
Reid Spencerad89bd62004-07-25 18:07:36 +0000281 // No need to emit anything, just the count of opaque types is enough.
282 break;
Reid Spencerad89bd62004-07-25 18:07:36 +0000283
Reid Spencerad89bd62004-07-25 18:07:36 +0000284 default:
Bill Wendlinge8156192006-12-07 01:30:32 +0000285 cerr << __FILE__ << ":" << __LINE__ << ": Don't know how to serialize"
286 << " Type '" << T->getDescription() << "'\n";
Reid Spencerad89bd62004-07-25 18:07:36 +0000287 break;
288 }
289}
290
291void BytecodeWriter::outputConstant(const Constant *CPV) {
292 assert((CPV->getType()->isPrimitiveType() || !CPV->isNullValue()) &&
293 "Shouldn't output null constants!");
294
295 // We must check for a ConstantExpr before switching by type because
296 // a ConstantExpr can be of any type, and has no explicit value.
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000297 //
Reid Spencerad89bd62004-07-25 18:07:36 +0000298 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CPV)) {
299 // FIXME: Encoding of constant exprs could be much more compact!
300 assert(CE->getNumOperands() > 0 && "ConstantExpr with 0 operands");
Reid Spencer3da59db2006-11-27 01:05:10 +0000301 assert(CE->getNumOperands() != 1 || CE->isCast());
Chris Lattnera79e7cc2004-10-16 18:18:16 +0000302 output_vbr(1+CE->getNumOperands()); // flags as an expr
Reid Spencerb83eb642006-10-20 07:07:24 +0000303 output_vbr(CE->getOpcode()); // Put out the CE op code
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000304
Reid Spencerad89bd62004-07-25 18:07:36 +0000305 for (User::const_op_iterator OI = CE->op_begin(); OI != CE->op_end(); ++OI){
306 int Slot = Table.getSlot(*OI);
307 assert(Slot != -1 && "Unknown constant used in ConstantExpr!!");
308 output_vbr((unsigned)Slot);
309 Slot = Table.getSlot((*OI)->getType());
310 output_typeid((unsigned)Slot);
311 }
Reid Spencer595b4772006-12-04 05:23:49 +0000312 if (CE->isCompare())
313 output_vbr((unsigned)CE->getPredicate());
Reid Spencerad89bd62004-07-25 18:07:36 +0000314 return;
Chris Lattnera79e7cc2004-10-16 18:18:16 +0000315 } else if (isa<UndefValue>(CPV)) {
316 output_vbr(1U); // 1 -> UndefValue constant.
317 return;
Reid Spencerad89bd62004-07-25 18:07:36 +0000318 } else {
Reid Spencerb83eb642006-10-20 07:07:24 +0000319 output_vbr(0U); // flag as not a ConstantExpr (i.e. 0 operands)
Reid Spencerad89bd62004-07-25 18:07:36 +0000320 }
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000321
Reid Spencerad89bd62004-07-25 18:07:36 +0000322 switch (CPV->getType()->getTypeID()) {
323 case Type::BoolTyID: // Boolean Types
324 if (cast<ConstantBool>(CPV)->getValue())
325 output_vbr(1U);
326 else
327 output_vbr(0U);
328 break;
329
Reid Spencer88cfda22006-12-31 05:44:24 +0000330 case Type::Int8TyID: // Unsigned integer types...
331 case Type::Int16TyID:
332 case Type::Int32TyID:
333 case Type::Int64TyID:
Reid Spencerb83eb642006-10-20 07:07:24 +0000334 output_vbr(cast<ConstantInt>(CPV)->getZExtValue());
Reid Spencerad89bd62004-07-25 18:07:36 +0000335 break;
336
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)) {
486 unsigned IdxId;
487 switch (I->getOperand(Idx)->getType()->getTypeID()) {
488 default: assert(0 && "Unknown index type!");
Reid Spencer88cfda22006-12-31 05:44:24 +0000489 case Type::Int32TyID: IdxId = 0; break;
490 case Type::Int64TyID: IdxId = 1; break;
Reid Spencerad89bd62004-07-25 18:07:36 +0000491 }
Reid Spencer88cfda22006-12-31 05:44:24 +0000492 Slot = (Slot << 1) | IdxId;
Reid Spencerad89bd62004-07-25 18:07:36 +0000493 }
494 output_vbr(unsigned(Slot));
495 }
496 }
Reid Spencerad89bd62004-07-25 18:07:36 +0000497}
498
499
500// outputInstrVarArgsCall - Output the absurdly annoying varargs function calls.
501// This are more annoying than most because the signature of the call does not
502// tell us anything about the types of the arguments in the varargs portion.
503// Because of this, we encode (as type 0) all of the argument types explicitly
504// before the argument value. This really sucks, but you shouldn't be using
505// varargs functions in your code! *death to printf*!
506//
507// Format: [opcode] [type] [numargs] [arg0] [arg1] ... [arg<numargs-1>]
508//
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000509void BytecodeWriter::outputInstrVarArgsCall(const Instruction *I,
510 unsigned Opcode,
511 const SlotCalculator &Table,
512 unsigned Type) {
Reid Spencerad89bd62004-07-25 18:07:36 +0000513 assert(isa<CallInst>(I) || isa<InvokeInst>(I));
514 // Opcode must have top two bits clear...
515 output_vbr(Opcode << 2); // Instruction Opcode ID
516 output_typeid(Type); // Result type (varargs type)
517
518 const PointerType *PTy = cast<PointerType>(I->getOperand(0)->getType());
519 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
520 unsigned NumParams = FTy->getNumParams();
521
522 unsigned NumFixedOperands;
523 if (isa<CallInst>(I)) {
524 // Output an operand for the callee and each fixed argument, then two for
525 // each variable argument.
526 NumFixedOperands = 1+NumParams;
527 } else {
528 assert(isa<InvokeInst>(I) && "Not call or invoke??");
529 // Output an operand for the callee and destinations, then two for each
530 // variable argument.
531 NumFixedOperands = 3+NumParams;
532 }
Reid Spencer3da59db2006-11-27 01:05:10 +0000533 output_vbr(2 * I->getNumOperands()-NumFixedOperands +
534 unsigned(Opcode == 58 || isa<InvokeInst>(I)));
Reid Spencerad89bd62004-07-25 18:07:36 +0000535
536 // The type for the function has already been emitted in the type field of the
537 // instruction. Just emit the slot # now.
538 for (unsigned i = 0; i != NumFixedOperands; ++i) {
539 int Slot = Table.getSlot(I->getOperand(i));
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000540 assert(Slot >= 0 && "No slot number for value!?!?");
Reid Spencerad89bd62004-07-25 18:07:36 +0000541 output_vbr((unsigned)Slot);
542 }
543
544 for (unsigned i = NumFixedOperands, e = I->getNumOperands(); i != e; ++i) {
545 // Output Arg Type ID
546 int Slot = Table.getSlot(I->getOperand(i)->getType());
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000547 assert(Slot >= 0 && "No slot number for value!?!?");
Reid Spencerad89bd62004-07-25 18:07:36 +0000548 output_typeid((unsigned)Slot);
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000549
Reid Spencerad89bd62004-07-25 18:07:36 +0000550 // Output arg ID itself
551 Slot = Table.getSlot(I->getOperand(i));
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000552 assert(Slot >= 0 && "No slot number for value!?!?");
Reid Spencerad89bd62004-07-25 18:07:36 +0000553 output_vbr((unsigned)Slot);
554 }
Chris Lattnera65371e2006-05-26 18:42:34 +0000555
Reid Spencer3da59db2006-11-27 01:05:10 +0000556 if (isa<InvokeInst>(I)) {
557 // Emit the tail call/calling conv for invoke instructions
558 output_vbr(cast<InvokeInst>(I)->getCallingConv());
559 } else if (Opcode == 58) {
Chris Lattnera65371e2006-05-26 18:42:34 +0000560 const CallInst *CI = cast<CallInst>(I);
561 output_vbr((CI->getCallingConv() << 1) | unsigned(CI->isTailCall()));
Chris Lattnera65371e2006-05-26 18:42:34 +0000562 }
Reid Spencerad89bd62004-07-25 18:07:36 +0000563}
564
565
566// outputInstructionFormat1 - Output one operand instructions, knowing that no
567// operand index is >= 2^12.
568//
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000569inline void BytecodeWriter::outputInstructionFormat1(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 1.
576 // 07-02: Opcode
577 // 19-08: Resulting type plane
578 // 31-20: Operand #1 (if set to (2^12-1), then zero operands)
579 //
Chris Lattnerf9d71782004-10-14 01:46:07 +0000580 output(1 | (Opcode << 2) | (Type << 8) | (Slots[0] << 20));
Reid Spencerad89bd62004-07-25 18:07:36 +0000581}
582
583
584// outputInstructionFormat2 - Output two operand instructions, knowing that no
585// operand index is >= 2^8.
586//
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000587inline void BytecodeWriter::outputInstructionFormat2(const Instruction *I,
588 unsigned Opcode,
589 unsigned *Slots,
590 unsigned Type) {
Reid Spencerad89bd62004-07-25 18:07:36 +0000591 // bits Instruction format:
592 // --------------------------
593 // 01-00: Opcode type, fixed to 2.
594 // 07-02: Opcode
595 // 15-08: Resulting type plane
596 // 23-16: Operand #1
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000597 // 31-24: Operand #2
Reid Spencerad89bd62004-07-25 18:07:36 +0000598 //
Chris Lattnerf9d71782004-10-14 01:46:07 +0000599 output(2 | (Opcode << 2) | (Type << 8) | (Slots[0] << 16) | (Slots[1] << 24));
Reid Spencerad89bd62004-07-25 18:07:36 +0000600}
601
602
603// outputInstructionFormat3 - Output three operand instructions, knowing that no
604// operand index is >= 2^6.
605//
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000606inline void BytecodeWriter::outputInstructionFormat3(const Instruction *I,
Reid Spencerad89bd62004-07-25 18:07:36 +0000607 unsigned Opcode,
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000608 unsigned *Slots,
609 unsigned Type) {
Reid Spencerad89bd62004-07-25 18:07:36 +0000610 // bits Instruction format:
611 // --------------------------
612 // 01-00: Opcode type, fixed to 3.
613 // 07-02: Opcode
614 // 13-08: Resulting type plane
615 // 19-14: Operand #1
616 // 25-20: Operand #2
617 // 31-26: Operand #3
618 //
Chris Lattnerf9d71782004-10-14 01:46:07 +0000619 output(3 | (Opcode << 2) | (Type << 8) |
Chris Lattner84d1ced2004-10-14 01:57:28 +0000620 (Slots[0] << 14) | (Slots[1] << 20) | (Slots[2] << 26));
Reid Spencerad89bd62004-07-25 18:07:36 +0000621}
622
623void BytecodeWriter::outputInstruction(const Instruction &I) {
Reid Spencer3da59db2006-11-27 01:05:10 +0000624 assert(I.getOpcode() < 57 && "Opcode too big???");
Reid Spencerad89bd62004-07-25 18:07:36 +0000625 unsigned Opcode = I.getOpcode();
626 unsigned NumOperands = I.getNumOperands();
627
Chris Lattner38287bd2005-05-06 06:13:34 +0000628 // Encode 'tail call' as 61, 'volatile load' as 62, and 'volatile store' as
629 // 63.
Chris Lattnerdee199f2005-05-06 22:34:01 +0000630 if (const CallInst *CI = dyn_cast<CallInst>(&I)) {
631 if (CI->getCallingConv() == CallingConv::C) {
632 if (CI->isTailCall())
633 Opcode = 61; // CCC + Tail Call
634 else
635 ; // Opcode = Instruction::Call
636 } else if (CI->getCallingConv() == CallingConv::Fast) {
637 if (CI->isTailCall())
638 Opcode = 59; // FastCC + TailCall
639 else
640 Opcode = 60; // FastCC + Not Tail Call
641 } else {
642 Opcode = 58; // Call escape sequence.
643 }
Chris Lattnerdee199f2005-05-06 22:34:01 +0000644 } else if (isa<LoadInst>(I) && cast<LoadInst>(I).isVolatile()) {
Reid Spencerad89bd62004-07-25 18:07:36 +0000645 Opcode = 62;
Chris Lattnerdee199f2005-05-06 22:34:01 +0000646 } else if (isa<StoreInst>(I) && cast<StoreInst>(I).isVolatile()) {
Reid Spencerad89bd62004-07-25 18:07:36 +0000647 Opcode = 63;
Chris Lattnerdee199f2005-05-06 22:34:01 +0000648 }
Reid Spencerad89bd62004-07-25 18:07:36 +0000649
650 // Figure out which type to encode with the instruction. Typically we want
651 // the type of the first parameter, as opposed to the type of the instruction
652 // (for example, with setcc, we always know it returns bool, but the type of
653 // the first param is actually interesting). But if we have no arguments
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000654 // we take the type of the instruction itself.
Reid Spencerad89bd62004-07-25 18:07:36 +0000655 //
656 const Type *Ty;
657 switch (I.getOpcode()) {
658 case Instruction::Select:
659 case Instruction::Malloc:
660 case Instruction::Alloca:
661 Ty = I.getType(); // These ALWAYS want to encode the return type
662 break;
663 case Instruction::Store:
664 Ty = I.getOperand(1)->getType(); // Encode the pointer type...
665 assert(isa<PointerType>(Ty) && "Store to nonpointer type!?!?");
666 break;
667 default: // Otherwise use the default behavior...
668 Ty = NumOperands ? I.getOperand(0)->getType() : I.getType();
669 break;
670 }
671
672 unsigned Type;
673 int Slot = Table.getSlot(Ty);
674 assert(Slot != -1 && "Type not available!!?!");
675 Type = (unsigned)Slot;
676
677 // Varargs calls and invokes are encoded entirely different from any other
678 // instructions.
679 if (const CallInst *CI = dyn_cast<CallInst>(&I)){
680 const PointerType *Ty =cast<PointerType>(CI->getCalledValue()->getType());
681 if (cast<FunctionType>(Ty->getElementType())->isVarArg()) {
682 outputInstrVarArgsCall(CI, Opcode, Table, Type);
683 return;
684 }
685 } else if (const InvokeInst *II = dyn_cast<InvokeInst>(&I)) {
686 const PointerType *Ty =cast<PointerType>(II->getCalledValue()->getType());
687 if (cast<FunctionType>(Ty->getElementType())->isVarArg()) {
688 outputInstrVarArgsCall(II, Opcode, Table, Type);
689 return;
690 }
691 }
692
693 if (NumOperands <= 3) {
694 // Make sure that we take the type number into consideration. We don't want
695 // to overflow the field size for the instruction format we select.
696 //
697 unsigned MaxOpSlot = Type;
698 unsigned Slots[3]; Slots[0] = (1 << 12)-1; // Marker to signify 0 operands
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000699
Reid Spencerad89bd62004-07-25 18:07:36 +0000700 for (unsigned i = 0; i != NumOperands; ++i) {
701 int slot = Table.getSlot(I.getOperand(i));
702 assert(slot != -1 && "Broken bytecode!");
703 if (unsigned(slot) > MaxOpSlot) MaxOpSlot = unsigned(slot);
704 Slots[i] = unsigned(slot);
705 }
706
707 // Handle the special cases for various instructions...
708 if (isa<CastInst>(I) || isa<VAArgInst>(I)) {
709 // Cast has to encode the destination type as the second argument in the
710 // packet, or else we won't know what type to cast to!
711 Slots[1] = Table.getSlot(I.getType());
712 assert(Slots[1] != ~0U && "Cast return type unknown?");
713 if (Slots[1] > MaxOpSlot) MaxOpSlot = Slots[1];
714 NumOperands++;
Chris Lattner42ba6b42005-11-05 22:08:14 +0000715 } else if (const AllocationInst *AI = dyn_cast<AllocationInst>(&I)) {
716 assert(NumOperands == 1 && "Bogus allocation!");
717 if (AI->getAlignment()) {
718 Slots[1] = Log2_32(AI->getAlignment())+1;
719 if (Slots[1] > MaxOpSlot) MaxOpSlot = Slots[1];
720 NumOperands = 2;
721 }
Reid Spencerc8dab492006-12-03 06:28:54 +0000722 } else if (isa<ICmpInst>(I) || isa<FCmpInst>(I)) {
723 // We need to encode the compare instruction's predicate as the third
724 // operand. Its not really a slot, but we don't want to break the
725 // instruction format for these instructions.
726 NumOperands++;
727 assert(NumOperands == 3 && "CmpInst with wrong number of operands?");
728 Slots[2] = unsigned(cast<CmpInst>(&I)->getPredicate());
729 if (Slots[2] > MaxOpSlot)
730 MaxOpSlot = Slots[2];
Reid Spencerad89bd62004-07-25 18:07:36 +0000731 } else if (const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(&I)) {
732 // We need to encode the type of sequential type indices into their slot #
733 unsigned Idx = 1;
734 for (gep_type_iterator I = gep_type_begin(GEP), E = gep_type_end(GEP);
735 I != E; ++I, ++Idx)
736 if (isa<SequentialType>(*I)) {
737 unsigned IdxId;
738 switch (GEP->getOperand(Idx)->getType()->getTypeID()) {
739 default: assert(0 && "Unknown index type!");
Reid Spencer88cfda22006-12-31 05:44:24 +0000740 case Type::Int32TyID: IdxId = 0; break;
741 case Type::Int64TyID: IdxId = 1; break;
Reid Spencerad89bd62004-07-25 18:07:36 +0000742 }
Reid Spencer88cfda22006-12-31 05:44:24 +0000743 Slots[Idx] = (Slots[Idx] << 1) | IdxId;
Reid Spencerad89bd62004-07-25 18:07:36 +0000744 if (Slots[Idx] > MaxOpSlot) MaxOpSlot = Slots[Idx];
745 }
Chris Lattnerdee199f2005-05-06 22:34:01 +0000746 } else if (Opcode == 58) {
747 // If this is the escape sequence for call, emit the tailcall/cc info.
748 const CallInst &CI = cast<CallInst>(I);
749 ++NumOperands;
Chris Lattnerebf8e6c2006-05-19 21:57:37 +0000750 if (NumOperands <= 3) {
751 Slots[NumOperands-1] =
752 (CI.getCallingConv() << 1)|unsigned(CI.isTailCall());
Chris Lattnerdee199f2005-05-06 22:34:01 +0000753 if (Slots[NumOperands-1] > MaxOpSlot)
754 MaxOpSlot = Slots[NumOperands-1];
755 }
Reid Spencer3da59db2006-11-27 01:05:10 +0000756 } else if (isa<InvokeInst>(I)) {
Chris Lattnerdee199f2005-05-06 22:34:01 +0000757 // Invoke escape seq has at least 4 operands to encode.
758 ++NumOperands;
Reid Spencerad89bd62004-07-25 18:07:36 +0000759 }
760
761 // Decide which instruction encoding to use. This is determined primarily
762 // by the number of operands, and secondarily by whether or not the max
763 // operand will fit into the instruction encoding. More operands == fewer
764 // bits per operand.
765 //
766 switch (NumOperands) {
767 case 0:
768 case 1:
769 if (MaxOpSlot < (1 << 12)-1) { // -1 because we use 4095 to indicate 0 ops
770 outputInstructionFormat1(&I, Opcode, Slots, Type);
771 return;
772 }
773 break;
774
775 case 2:
776 if (MaxOpSlot < (1 << 8)) {
777 outputInstructionFormat2(&I, Opcode, Slots, Type);
778 return;
779 }
780 break;
781
782 case 3:
783 if (MaxOpSlot < (1 << 6)) {
784 outputInstructionFormat3(&I, Opcode, Slots, Type);
785 return;
786 }
787 break;
788 default:
789 break;
790 }
791 }
792
793 // If we weren't handled before here, we either have a large number of
794 // operands or a large operand index that we are referring to.
795 outputInstructionFormat0(&I, Opcode, Table, Type);
796}
797
798//===----------------------------------------------------------------------===//
799//=== Block Output ===//
800//===----------------------------------------------------------------------===//
801
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000802BytecodeWriter::BytecodeWriter(std::vector<unsigned char> &o, const Module *M)
Reid Spencer798ff642004-05-26 07:37:11 +0000803 : Out(o), Table(M) {
Chris Lattner00950542001-06-06 20:29:01 +0000804
Chris Lattner83bb3d22004-01-14 23:36:54 +0000805 // Emit the signature...
Chris Lattnerc847f7c2006-07-28 22:07:54 +0000806 static const unsigned char *Sig = (const unsigned char*)"llvm";
Reid Spencerad89bd62004-07-25 18:07:36 +0000807 output_data(Sig, Sig+4);
Chris Lattner00950542001-06-06 20:29:01 +0000808
809 // Emit the top level CLASS block.
Reid Spencerad89bd62004-07-25 18:07:36 +0000810 BytecodeBlock ModuleBlock(BytecodeFormat::ModuleBlockID, *this, false, true);
Chris Lattner00950542001-06-06 20:29:01 +0000811
Chris Lattnerd445c6b2003-08-24 13:47:36 +0000812 bool isBigEndian = M->getEndianness() == Module::BigEndian;
813 bool hasLongPointers = M->getPointerSize() == Module::Pointer64;
814 bool hasNoEndianness = M->getEndianness() == Module::AnyEndianness;
815 bool hasNoPointerSize = M->getPointerSize() == Module::AnyPointerSize;
Chris Lattner186a1f72003-03-19 20:56:46 +0000816
Chris Lattnera79e7cc2004-10-16 18:18:16 +0000817 // Output the version identifier and other information.
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000818 unsigned Version = (BCVersionNum << 4) |
Reid Spencer38d54be2004-08-17 07:45:14 +0000819 (unsigned)isBigEndian | (hasLongPointers << 1) |
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000820 (hasNoEndianness << 2) |
Reid Spencer38d54be2004-08-17 07:45:14 +0000821 (hasNoPointerSize << 3);
Reid Spencerad89bd62004-07-25 18:07:36 +0000822 output_vbr(Version);
Chris Lattner00950542001-06-06 20:29:01 +0000823
Reid Spencercb3595c2004-07-04 11:45:47 +0000824 // The Global type plane comes first
Chris Lattner186a1f72003-03-19 20:56:46 +0000825 {
Chris Lattnerc847f7c2006-07-28 22:07:54 +0000826 BytecodeBlock CPool(BytecodeFormat::GlobalTypePlaneBlockID, *this);
827 outputTypes(Type::FirstDerivedTyID);
Chris Lattner186a1f72003-03-19 20:56:46 +0000828 }
Chris Lattner00950542001-06-06 20:29:01 +0000829
Chris Lattner186a1f72003-03-19 20:56:46 +0000830 // The ModuleInfoBlock follows directly after the type information
Chris Lattnere8fdde12001-09-07 16:39:41 +0000831 outputModuleInfoBlock(M);
832
Chris Lattner186a1f72003-03-19 20:56:46 +0000833 // Output module level constants, used for global variable initializers
834 outputConstants(false);
835
Chris Lattnerb5794002002-04-07 22:49:37 +0000836 // Do the whole module now! Process each function at a time...
Chris Lattner0b12b5f2002-06-25 16:13:21 +0000837 for (Module::const_iterator I = M->begin(), E = M->end(); I != E; ++I)
Chris Lattner186a1f72003-03-19 20:56:46 +0000838 outputFunction(I);
Chris Lattnere8fdde12001-09-07 16:39:41 +0000839
840 // If needed, output the symbol table for the module...
Chris Lattner6e6026b2002-11-20 18:36:02 +0000841 outputSymbolTable(M->getSymbolTable());
Chris Lattner00950542001-06-06 20:29:01 +0000842}
843
Chris Lattnerf9d71782004-10-14 01:46:07 +0000844void BytecodeWriter::outputTypes(unsigned TypeNum) {
Reid Spencercb3595c2004-07-04 11:45:47 +0000845 // Write the type plane for types first because earlier planes (e.g. for a
846 // primitive type like float) may have constants constructed using types
847 // coming later (e.g., via getelementptr from a pointer type). The type
848 // plane is needed before types can be fwd or bkwd referenced.
849 const std::vector<const Type*>& Types = Table.getTypes();
850 assert(!Types.empty() && "No types at all?");
851 assert(TypeNum <= Types.size() && "Invalid TypeNo index");
852
853 unsigned NumEntries = Types.size() - TypeNum;
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000854
Reid Spencercb3595c2004-07-04 11:45:47 +0000855 // Output type header: [num entries]
Reid Spencerad89bd62004-07-25 18:07:36 +0000856 output_vbr(NumEntries);
Reid Spencercb3595c2004-07-04 11:45:47 +0000857
858 for (unsigned i = TypeNum; i < TypeNum+NumEntries; ++i)
859 outputType(Types[i]);
860}
861
Vikram S. Advea7dac3d2002-07-14 23:07:51 +0000862// Helper function for outputConstants().
863// Writes out all the constants in the plane Plane starting at entry StartNo.
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000864//
Vikram S. Advea7dac3d2002-07-14 23:07:51 +0000865void BytecodeWriter::outputConstantsInPlane(const std::vector<const Value*>
866 &Plane, unsigned StartNo) {
867 unsigned ValNo = StartNo;
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000868
Chris Lattner83bb3d22004-01-14 23:36:54 +0000869 // Scan through and ignore function arguments, global values, and constant
870 // strings.
871 for (; ValNo < Plane.size() &&
872 (isa<Argument>(Plane[ValNo]) || isa<GlobalValue>(Plane[ValNo]) ||
873 (isa<ConstantArray>(Plane[ValNo]) &&
874 cast<ConstantArray>(Plane[ValNo])->isString())); ValNo++)
Vikram S. Advea7dac3d2002-07-14 23:07:51 +0000875 /*empty*/;
876
877 unsigned NC = ValNo; // Number of constants
Chris Lattner3bc5a602006-01-25 23:08:15 +0000878 for (; NC < Plane.size() && (isa<Constant>(Plane[NC]) ||
879 isa<InlineAsm>(Plane[NC])); NC++)
Vikram S. Advea7dac3d2002-07-14 23:07:51 +0000880 /*empty*/;
881 NC -= ValNo; // Convert from index into count
882 if (NC == 0) return; // Skip empty type planes...
883
Chris Lattnerd6942d72004-01-14 16:54:21 +0000884 // FIXME: Most slabs only have 1 or 2 entries! We should encode this much
885 // more compactly.
886
Reid Spencerb83eb642006-10-20 07:07:24 +0000887 // Put out type header: [num entries][type id number]
Vikram S. Advea7dac3d2002-07-14 23:07:51 +0000888 //
Reid Spencerad89bd62004-07-25 18:07:36 +0000889 output_vbr(NC);
Vikram S. Advea7dac3d2002-07-14 23:07:51 +0000890
Reid Spencerb83eb642006-10-20 07:07:24 +0000891 // Put out the Type ID Number...
Alkis Evlogimenos60596382003-10-17 02:02:40 +0000892 int Slot = Table.getSlot(Plane.front()->getType());
Vikram S. Advea7dac3d2002-07-14 23:07:51 +0000893 assert (Slot != -1 && "Type in constant pool but not in function!!");
Reid Spencerad89bd62004-07-25 18:07:36 +0000894 output_typeid((unsigned)Slot);
Vikram S. Advea7dac3d2002-07-14 23:07:51 +0000895
Vikram S. Advea7dac3d2002-07-14 23:07:51 +0000896 for (unsigned i = ValNo; i < ValNo+NC; ++i) {
897 const Value *V = Plane[i];
Chris Lattner3bc5a602006-01-25 23:08:15 +0000898 if (const Constant *C = dyn_cast<Constant>(V))
Reid Spencere0125b62004-07-18 00:16:21 +0000899 outputConstant(C);
Chris Lattner3bc5a602006-01-25 23:08:15 +0000900 else
901 outputInlineAsm(cast<InlineAsm>(V));
Vikram S. Advea7dac3d2002-07-14 23:07:51 +0000902 }
903}
904
Chris Lattner9e60d8d2005-05-05 22:21:19 +0000905static inline bool hasNullValue(const Type *Ty) {
906 return Ty != Type::LabelTy && Ty != Type::VoidTy && !isa<OpaqueType>(Ty);
Chris Lattner80b97342004-01-17 23:25:43 +0000907}
908
Chris Lattner79df7c02002-03-26 18:01:55 +0000909void BytecodeWriter::outputConstants(bool isFunction) {
Reid Spencerad89bd62004-07-25 18:07:36 +0000910 BytecodeBlock CPool(BytecodeFormat::ConstantPoolBlockID, *this,
Chris Lattner0baa0af2004-01-15 21:06:57 +0000911 true /* Elide block if empty */);
Chris Lattner00950542001-06-06 20:29:01 +0000912
913 unsigned NumPlanes = Table.getNumPlanes();
Chris Lattnerf69315b2003-05-22 18:35:38 +0000914
Reid Spencere0125b62004-07-18 00:16:21 +0000915 if (isFunction)
916 // Output the type plane before any constants!
Chris Lattnera79e7cc2004-10-16 18:18:16 +0000917 outputTypes(Table.getModuleTypeLevel());
Reid Spencere0125b62004-07-18 00:16:21 +0000918 else
Chris Lattnerf9d71782004-10-14 01:46:07 +0000919 // Output module-level string constants before any other constants.
Chris Lattner83bb3d22004-01-14 23:36:54 +0000920 outputConstantStrings();
921
Reid Spencercb3595c2004-07-04 11:45:47 +0000922 for (unsigned pno = 0; pno != NumPlanes; pno++) {
923 const std::vector<const Value*> &Plane = Table.getPlane(pno);
924 if (!Plane.empty()) { // Skip empty type planes...
925 unsigned ValNo = 0;
926 if (isFunction) // Don't re-emit module constants
Reid Spencer0852c802004-07-04 11:46:15 +0000927 ValNo += Table.getModuleLevel(pno);
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000928
Chris Lattner9e60d8d2005-05-05 22:21:19 +0000929 if (hasNullValue(Plane[0]->getType())) {
Reid Spencer0852c802004-07-04 11:46:15 +0000930 // Skip zero initializer
931 if (ValNo == 0)
932 ValNo = 1;
Chris Lattnerf69315b2003-05-22 18:35:38 +0000933 }
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000934
Reid Spencercb3595c2004-07-04 11:45:47 +0000935 // Write out constants in the plane
936 outputConstantsInPlane(Plane, ValNo);
Chris Lattnerf69315b2003-05-22 18:35:38 +0000937 }
Reid Spencercb3595c2004-07-04 11:45:47 +0000938 }
Chris Lattner00950542001-06-06 20:29:01 +0000939}
940
Chris Lattner6b252422003-10-16 18:28:50 +0000941static unsigned getEncodedLinkage(const GlobalValue *GV) {
942 switch (GV->getLinkage()) {
943 default: assert(0 && "Invalid linkage!");
Anton Korobeynikovb74ed072006-09-14 18:23:27 +0000944 case GlobalValue::ExternalLinkage: return 0;
945 case GlobalValue::WeakLinkage: return 1;
946 case GlobalValue::AppendingLinkage: return 2;
947 case GlobalValue::InternalLinkage: return 3;
948 case GlobalValue::LinkOnceLinkage: return 4;
949 case GlobalValue::DLLImportLinkage: return 5;
950 case GlobalValue::DLLExportLinkage: return 6;
951 case GlobalValue::ExternalWeakLinkage: return 7;
Chris Lattner6b252422003-10-16 18:28:50 +0000952 }
953}
954
Chris Lattner00950542001-06-06 20:29:01 +0000955void BytecodeWriter::outputModuleInfoBlock(const Module *M) {
Reid Spencerad89bd62004-07-25 18:07:36 +0000956 BytecodeBlock ModuleInfoBlock(BytecodeFormat::ModuleGlobalInfoBlockID, *this);
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000957
Chris Lattner404cddf2005-11-12 01:33:40 +0000958 // Give numbers to sections as we encounter them.
959 unsigned SectionIDCounter = 0;
960 std::vector<std::string> SectionNames;
961 std::map<std::string, unsigned> SectionID;
962
Chris Lattner70cc3392001-09-10 07:58:01 +0000963 // Output the types for the global variables in the module...
Chris Lattner28caccf2005-05-06 20:27:03 +0000964 for (Module::const_global_iterator I = M->global_begin(),
Chris Lattner8eb52dd2005-11-06 07:11:04 +0000965 End = M->global_end(); I != End; ++I) {
Alkis Evlogimenos60596382003-10-17 02:02:40 +0000966 int Slot = Table.getSlot(I->getType());
Chris Lattner70cc3392001-09-10 07:58:01 +0000967 assert(Slot != -1 && "Module global vars is broken!");
Chris Lattnerd70684f2001-09-18 04:01:05 +0000968
Chris Lattner8eb52dd2005-11-06 07:11:04 +0000969 assert((I->hasInitializer() || !I->hasInternalLinkage()) &&
970 "Global must have an initializer or have external linkage!");
971
Chris Lattner22482a12003-10-18 06:30:21 +0000972 // Fields: bit0 = isConstant, bit1 = hasInitializer, bit2-4=Linkage,
Chris Lattner8eb52dd2005-11-06 07:11:04 +0000973 // bit5+ = Slot # for type.
Chris Lattner404cddf2005-11-12 01:33:40 +0000974 bool HasExtensionWord = (I->getAlignment() != 0) || I->hasSection();
Chris Lattner8eb52dd2005-11-06 07:11:04 +0000975
976 // If we need to use the extension byte, set linkage=3(internal) and
977 // initializer = 0 (impossible!).
978 if (!HasExtensionWord) {
979 unsigned oSlot = ((unsigned)Slot << 5) | (getEncodedLinkage(I) << 2) |
980 (I->hasInitializer() << 1) | (unsigned)I->isConstant();
981 output_vbr(oSlot);
Anton Korobeynikovb74ed072006-09-14 18:23:27 +0000982 } else {
Chris Lattner8eb52dd2005-11-06 07:11:04 +0000983 unsigned oSlot = ((unsigned)Slot << 5) | (3 << 2) |
984 (0 << 1) | (unsigned)I->isConstant();
985 output_vbr(oSlot);
986
987 // The extension word has this format: bit 0 = has initializer, bit 1-3 =
Chris Lattner404cddf2005-11-12 01:33:40 +0000988 // linkage, bit 4-8 = alignment (log2), bit 9 = has SectionID,
989 // bits 10+ = future use.
Jeff Cohenba0ffcc2005-11-12 01:01:50 +0000990 unsigned ExtWord = (unsigned)I->hasInitializer() |
991 (getEncodedLinkage(I) << 1) |
Chris Lattner404cddf2005-11-12 01:33:40 +0000992 ((Log2_32(I->getAlignment())+1) << 4) |
993 ((unsigned)I->hasSection() << 9);
Chris Lattner8eb52dd2005-11-06 07:11:04 +0000994 output_vbr(ExtWord);
Chris Lattner404cddf2005-11-12 01:33:40 +0000995 if (I->hasSection()) {
996 // Give section names unique ID's.
997 unsigned &Entry = SectionID[I->getSection()];
998 if (Entry == 0) {
999 Entry = ++SectionIDCounter;
1000 SectionNames.push_back(I->getSection());
1001 }
1002 output_vbr(Entry);
1003 }
Chris Lattner8eb52dd2005-11-06 07:11:04 +00001004 }
Chris Lattnerd70684f2001-09-18 04:01:05 +00001005
Chris Lattner1b98c5c2001-10-13 06:48:38 +00001006 // If we have an initializer, output it now.
Chris Lattner0b12b5f2002-06-25 16:13:21 +00001007 if (I->hasInitializer()) {
Alkis Evlogimenos60596382003-10-17 02:02:40 +00001008 Slot = Table.getSlot((Value*)I->getInitializer());
Chris Lattnerd70684f2001-09-18 04:01:05 +00001009 assert(Slot != -1 && "No slot for global var initializer!");
Reid Spencerad89bd62004-07-25 18:07:36 +00001010 output_vbr((unsigned)Slot);
Chris Lattnerd70684f2001-09-18 04:01:05 +00001011 }
Chris Lattner70cc3392001-09-10 07:58:01 +00001012 }
Reid Spencerad89bd62004-07-25 18:07:36 +00001013 output_typeid((unsigned)Table.getSlot(Type::VoidTy));
Chris Lattner70cc3392001-09-10 07:58:01 +00001014
Chris Lattnera79e7cc2004-10-16 18:18:16 +00001015 // Output the types of the functions in this module.
Chris Lattner7fc9fe32001-06-27 23:41:11 +00001016 for (Module::const_iterator I = M->begin(), End = M->end(); I != End; ++I) {
Alkis Evlogimenos60596382003-10-17 02:02:40 +00001017 int Slot = Table.getSlot(I->getType());
Chris Lattnera79e7cc2004-10-16 18:18:16 +00001018 assert(Slot != -1 && "Module slot calculator is broken!");
Chris Lattner00950542001-06-06 20:29:01 +00001019 assert(Slot >= Type::FirstDerivedTyID && "Derived type not in range!");
Chris Lattnere73bd452005-11-06 07:43:39 +00001020 assert(((Slot << 6) >> 6) == Slot && "Slot # too big!");
Chris Lattner54b369e2005-11-06 07:46:13 +00001021 unsigned CC = I->getCallingConv()+1;
1022 unsigned ID = (Slot << 5) | (CC & 15);
Chris Lattner479ffeb2005-05-06 20:42:57 +00001023
Chris Lattnerd6e431f2004-11-15 22:39:49 +00001024 if (I->isExternal()) // If external, we don't have an FunctionInfo block.
1025 ID |= 1 << 4;
Chris Lattnere73bd452005-11-06 07:43:39 +00001026
Anton Korobeynikovb74ed072006-09-14 18:23:27 +00001027 if (I->getAlignment() || I->hasSection() || (CC & ~15) != 0 ||
1028 (I->isExternal() && I->hasDLLImportLinkage()) ||
1029 (I->isExternal() && I->hasExternalWeakLinkage())
1030 )
Chris Lattnere73bd452005-11-06 07:43:39 +00001031 ID |= 1 << 31; // Do we need an extension word?
1032
Chris Lattnera79e7cc2004-10-16 18:18:16 +00001033 output_vbr(ID);
Chris Lattnere73bd452005-11-06 07:43:39 +00001034
1035 if (ID & (1 << 31)) {
1036 // Extension byte: bits 0-4 = alignment, bits 5-9 = top nibble of calling
Anton Korobeynikovb74ed072006-09-14 18:23:27 +00001037 // convention, bit 10 = hasSectionID., bits 11-12 = external linkage type
1038 unsigned extLinkage = 0;
1039
1040 if (I->isExternal()) {
1041 if (I->hasDLLImportLinkage()) {
1042 extLinkage = 1;
1043 } else if (I->hasExternalWeakLinkage()) {
1044 extLinkage = 2;
1045 }
1046 }
1047
Chris Lattner404cddf2005-11-12 01:33:40 +00001048 ID = (Log2_32(I->getAlignment())+1) | ((CC >> 4) << 5) |
Anton Korobeynikovb74ed072006-09-14 18:23:27 +00001049 (I->hasSection() << 10) |
1050 ((extLinkage & 3) << 11);
Chris Lattnere73bd452005-11-06 07:43:39 +00001051 output_vbr(ID);
Chris Lattner404cddf2005-11-12 01:33:40 +00001052
1053 // Give section names unique ID's.
1054 if (I->hasSection()) {
1055 unsigned &Entry = SectionID[I->getSection()];
1056 if (Entry == 0) {
1057 Entry = ++SectionIDCounter;
1058 SectionNames.push_back(I->getSection());
1059 }
1060 output_vbr(Entry);
1061 }
Chris Lattnere73bd452005-11-06 07:43:39 +00001062 }
Chris Lattner00950542001-06-06 20:29:01 +00001063 }
Chris Lattnera79e7cc2004-10-16 18:18:16 +00001064 output_vbr((unsigned)Table.getSlot(Type::VoidTy) << 5);
Reid Spencerad89bd62004-07-25 18:07:36 +00001065
Chris Lattnera79e7cc2004-10-16 18:18:16 +00001066 // Emit the list of dependent libraries for the Module.
Reid Spencer5ac88122004-07-25 21:32:02 +00001067 Module::lib_iterator LI = M->lib_begin();
1068 Module::lib_iterator LE = M->lib_end();
Chris Lattnera79e7cc2004-10-16 18:18:16 +00001069 output_vbr(unsigned(LE - LI)); // Emit the number of dependent libraries.
1070 for (; LI != LE; ++LI)
Reid Spencer38d54be2004-08-17 07:45:14 +00001071 output(*LI);
Reid Spencerad89bd62004-07-25 18:07:36 +00001072
1073 // Output the target triple from the module
Reid Spencer38d54be2004-08-17 07:45:14 +00001074 output(M->getTargetTriple());
Chris Lattner404cddf2005-11-12 01:33:40 +00001075
1076 // Emit the table of section names.
1077 output_vbr((unsigned)SectionNames.size());
1078 for (unsigned i = 0, e = SectionNames.size(); i != e; ++i)
1079 output(SectionNames[i]);
Chris Lattner7e6db762006-01-23 23:43:17 +00001080
1081 // Output the inline asm string.
Chris Lattner66316012006-01-24 04:14:29 +00001082 output(M->getModuleInlineAsm());
Chris Lattner00950542001-06-06 20:29:01 +00001083}
1084
Chris Lattnercf3e67f2004-01-18 21:08:52 +00001085void BytecodeWriter::outputInstructions(const Function *F) {
Reid Spencerad89bd62004-07-25 18:07:36 +00001086 BytecodeBlock ILBlock(BytecodeFormat::InstructionListBlockID, *this);
Chris Lattnercf3e67f2004-01-18 21:08:52 +00001087 for (Function::const_iterator BB = F->begin(), E = F->end(); BB != E; ++BB)
1088 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I!=E; ++I)
1089 outputInstruction(*I);
Chris Lattnercf3e67f2004-01-18 21:08:52 +00001090}
1091
Chris Lattner186a1f72003-03-19 20:56:46 +00001092void BytecodeWriter::outputFunction(const Function *F) {
Chris Lattnerfd7f8fe2004-11-15 21:56:33 +00001093 // If this is an external function, there is nothing else to emit!
1094 if (F->isExternal()) return;
1095
Chris Lattnerd6e431f2004-11-15 22:39:49 +00001096 BytecodeBlock FunctionBlock(BytecodeFormat::FunctionBlockID, *this);
1097 output_vbr(getEncodedLinkage(F));
1098
Chris Lattnercf3e67f2004-01-18 21:08:52 +00001099 // Get slot information about the function...
1100 Table.incorporateFunction(F);
1101
1102 if (Table.getCompactionTable().empty()) {
1103 // Output information about the constants in the function if the compaction
1104 // table is not being used.
Chris Lattnere8fdde12001-09-07 16:39:41 +00001105 outputConstants(true);
Chris Lattnercf3e67f2004-01-18 21:08:52 +00001106 } else {
1107 // Otherwise, emit the compaction table.
1108 outputCompactionTable();
Chris Lattnere8fdde12001-09-07 16:39:41 +00001109 }
Misha Brukman23c6d2c2005-04-21 21:48:46 +00001110
Chris Lattnercf3e67f2004-01-18 21:08:52 +00001111 // Output all of the instructions in the body of the function
1112 outputInstructions(F);
Misha Brukman23c6d2c2005-04-21 21:48:46 +00001113
Chris Lattnercf3e67f2004-01-18 21:08:52 +00001114 // If needed, output the symbol table for the function...
1115 outputSymbolTable(F->getSymbolTable());
Misha Brukman23c6d2c2005-04-21 21:48:46 +00001116
Chris Lattnercf3e67f2004-01-18 21:08:52 +00001117 Table.purgeFunction();
1118}
1119
1120void BytecodeWriter::outputCompactionTablePlane(unsigned PlaneNo,
1121 const std::vector<const Value*> &Plane,
1122 unsigned StartNo) {
1123 unsigned End = Table.getModuleLevel(PlaneNo);
Chris Lattner52f86d62004-01-20 00:54:06 +00001124 if (Plane.empty() || StartNo == End || End == 0) return; // Nothing to emit
Chris Lattnercf3e67f2004-01-18 21:08:52 +00001125 assert(StartNo < End && "Cannot emit negative range!");
1126 assert(StartNo < Plane.size() && End <= Plane.size());
1127
Chris Lattnercf3e67f2004-01-18 21:08:52 +00001128 // Do not emit the null initializer!
Reid Spencercb3595c2004-07-04 11:45:47 +00001129 ++StartNo;
Chris Lattnercf3e67f2004-01-18 21:08:52 +00001130
Chris Lattner24102432004-01-18 22:35:34 +00001131 // Figure out which encoding to use. By far the most common case we have is
1132 // to emit 0-2 entries in a compaction table plane.
1133 switch (End-StartNo) {
1134 case 0: // Avoid emitting two vbr's if possible.
1135 case 1:
1136 case 2:
Reid Spencerad89bd62004-07-25 18:07:36 +00001137 output_vbr((PlaneNo << 2) | End-StartNo);
Chris Lattner24102432004-01-18 22:35:34 +00001138 break;
1139 default:
1140 // Output the number of things.
Reid Spencerad89bd62004-07-25 18:07:36 +00001141 output_vbr((unsigned(End-StartNo) << 2) | 3);
1142 output_typeid(PlaneNo); // Emit the type plane this is
Chris Lattner24102432004-01-18 22:35:34 +00001143 break;
1144 }
1145
Chris Lattnercf3e67f2004-01-18 21:08:52 +00001146 for (unsigned i = StartNo; i != End; ++i)
Reid Spencerad89bd62004-07-25 18:07:36 +00001147 output_vbr(Table.getGlobalSlot(Plane[i]));
Chris Lattnercf3e67f2004-01-18 21:08:52 +00001148}
1149
Reid Spencercb3595c2004-07-04 11:45:47 +00001150void BytecodeWriter::outputCompactionTypes(unsigned StartNo) {
1151 // Get the compaction type table from the slot calculator
1152 const std::vector<const Type*> &CTypes = Table.getCompactionTypes();
1153
1154 // The compaction types may have been uncompactified back to the
1155 // global types. If so, we just write an empty table
Chris Lattnerc847f7c2006-07-28 22:07:54 +00001156 if (CTypes.size() == 0) {
Reid Spencerad89bd62004-07-25 18:07:36 +00001157 output_vbr(0U);
Reid Spencercb3595c2004-07-04 11:45:47 +00001158 return;
1159 }
1160
1161 assert(CTypes.size() >= StartNo && "Invalid compaction types start index");
1162
1163 // Determine how many types to write
1164 unsigned NumTypes = CTypes.size() - StartNo;
1165
1166 // Output the number of types.
Reid Spencerad89bd62004-07-25 18:07:36 +00001167 output_vbr(NumTypes);
Reid Spencercb3595c2004-07-04 11:45:47 +00001168
1169 for (unsigned i = StartNo; i < StartNo+NumTypes; ++i)
Reid Spencerad89bd62004-07-25 18:07:36 +00001170 output_typeid(Table.getGlobalSlot(CTypes[i]));
Reid Spencercb3595c2004-07-04 11:45:47 +00001171}
1172
Chris Lattnercf3e67f2004-01-18 21:08:52 +00001173void BytecodeWriter::outputCompactionTable() {
Reid Spencer0033c182004-08-27 00:38:44 +00001174 // Avoid writing the compaction table at all if there is no content.
1175 if (Table.getCompactionTypes().size() >= Type::FirstDerivedTyID ||
1176 (!Table.CompactionTableIsEmpty())) {
Misha Brukman23c6d2c2005-04-21 21:48:46 +00001177 BytecodeBlock CTB(BytecodeFormat::CompactionTableBlockID, *this,
Reid Spencer0033c182004-08-27 00:38:44 +00001178 true/*ElideIfEmpty*/);
Chris Lattnerf9d71782004-10-14 01:46:07 +00001179 const std::vector<std::vector<const Value*> > &CT =
1180 Table.getCompactionTable();
Misha Brukman23c6d2c2005-04-21 21:48:46 +00001181
Reid Spencer0033c182004-08-27 00:38:44 +00001182 // First things first, emit the type compaction table if there is one.
1183 outputCompactionTypes(Type::FirstDerivedTyID);
Chris Lattnercf3e67f2004-01-18 21:08:52 +00001184
Reid Spencer0033c182004-08-27 00:38:44 +00001185 for (unsigned i = 0, e = CT.size(); i != e; ++i)
1186 outputCompactionTablePlane(i, CT[i], 0);
1187 }
Chris Lattner00950542001-06-06 20:29:01 +00001188}
1189
Chris Lattner00950542001-06-06 20:29:01 +00001190void BytecodeWriter::outputSymbolTable(const SymbolTable &MST) {
Chris Lattner737d3cd2004-01-10 19:56:59 +00001191 // Do not output the Bytecode block for an empty symbol table, it just wastes
1192 // space!
Chris Lattnerf9d71782004-10-14 01:46:07 +00001193 if (MST.isEmpty()) return;
Chris Lattner737d3cd2004-01-10 19:56:59 +00001194
Reid Spencerad89bd62004-07-25 18:07:36 +00001195 BytecodeBlock SymTabBlock(BytecodeFormat::SymbolTableBlockID, *this,
Chris Lattnerf9d71782004-10-14 01:46:07 +00001196 true/*ElideIfEmpty*/);
Chris Lattner00950542001-06-06 20:29:01 +00001197
Misha Brukman23c6d2c2005-04-21 21:48:46 +00001198 // Write the number of types
Reid Spencerad89bd62004-07-25 18:07:36 +00001199 output_vbr(MST.num_types());
Reid Spencer250c4182004-08-17 02:59:02 +00001200
1201 // Write each of the types
Reid Spencer94f2df22004-05-25 17:29:59 +00001202 for (SymbolTable::type_const_iterator TI = MST.type_begin(),
Chris Lattnerc847f7c2006-07-28 22:07:54 +00001203 TE = MST.type_end(); TI != TE; ++TI) {
Reid Spencer250c4182004-08-17 02:59:02 +00001204 // Symtab entry:[def slot #][name]
Reid Spencerad89bd62004-07-25 18:07:36 +00001205 output_typeid((unsigned)Table.getSlot(TI->second));
Misha Brukman23c6d2c2005-04-21 21:48:46 +00001206 output(TI->first);
Reid Spencer94f2df22004-05-25 17:29:59 +00001207 }
1208
1209 // Now do each of the type planes in order.
Misha Brukman23c6d2c2005-04-21 21:48:46 +00001210 for (SymbolTable::plane_const_iterator PI = MST.plane_begin(),
Reid Spencer94f2df22004-05-25 17:29:59 +00001211 PE = MST.plane_end(); PI != PE; ++PI) {
1212 SymbolTable::value_const_iterator I = MST.value_begin(PI->first);
1213 SymbolTable::value_const_iterator End = MST.value_end(PI->first);
Chris Lattner00950542001-06-06 20:29:01 +00001214 int Slot;
Misha Brukman23c6d2c2005-04-21 21:48:46 +00001215
Chris Lattner00950542001-06-06 20:29:01 +00001216 if (I == End) continue; // Don't mess with an absent type...
1217
Reid Spencer250c4182004-08-17 02:59:02 +00001218 // Write the number of values in this plane
Chris Lattner001d16a2005-03-07 02:59:36 +00001219 output_vbr((unsigned)PI->second.size());
Chris Lattner00950542001-06-06 20:29:01 +00001220
Reid Spencer250c4182004-08-17 02:59:02 +00001221 // Write the slot number of the type for this plane
Reid Spencer94f2df22004-05-25 17:29:59 +00001222 Slot = Table.getSlot(PI->first);
Chris Lattner00950542001-06-06 20:29:01 +00001223 assert(Slot != -1 && "Type in symtab, but not in table!");
Reid Spencerad89bd62004-07-25 18:07:36 +00001224 output_typeid((unsigned)Slot);
Chris Lattner00950542001-06-06 20:29:01 +00001225
Reid Spencer250c4182004-08-17 02:59:02 +00001226 // Write each of the values in this plane
Chris Lattner7fc9fe32001-06-27 23:41:11 +00001227 for (; I != End; ++I) {
Chris Lattner00950542001-06-06 20:29:01 +00001228 // Symtab entry: [def slot #][name]
Alkis Evlogimenos60596382003-10-17 02:02:40 +00001229 Slot = Table.getSlot(I->second);
Chris Lattnere8fdde12001-09-07 16:39:41 +00001230 assert(Slot != -1 && "Value in symtab but has no slot number!!");
Reid Spencerad89bd62004-07-25 18:07:36 +00001231 output_vbr((unsigned)Slot);
Reid Spencer38d54be2004-08-17 07:45:14 +00001232 output(I->first);
Chris Lattner00950542001-06-06 20:29:01 +00001233 }
1234 }
1235}
1236
Bill Wendlinge8156192006-12-07 01:30:32 +00001237void llvm::WriteBytecodeToFile(const Module *M, OStream &Out,
Chris Lattnerc847f7c2006-07-28 22:07:54 +00001238 bool compress) {
Reid Spencerad89bd62004-07-25 18:07:36 +00001239 assert(M && "You can't write a null module!!");
Chris Lattner00950542001-06-06 20:29:01 +00001240
Reid Spencer32f55532006-06-07 23:18:34 +00001241 // Make sure that std::cout is put into binary mode for systems
1242 // that care.
Bill Wendlinge8156192006-12-07 01:30:32 +00001243 if (Out == cout)
Reid Spencer32f55532006-06-07 23:18:34 +00001244 sys::Program::ChangeStdoutToBinary();
1245
Reid Spencer17f52c52004-11-06 23:17:23 +00001246 // Create a vector of unsigned char for the bytecode output. We
1247 // reserve 256KBytes of space in the vector so that we avoid doing
1248 // lots of little allocations. 256KBytes is sufficient for a large
1249 // proportion of the bytecode files we will encounter. Larger files
1250 // will be automatically doubled in size as needed (std::vector
1251 // behavior).
Reid Spencerad89bd62004-07-25 18:07:36 +00001252 std::vector<unsigned char> Buffer;
Reid Spencer17f52c52004-11-06 23:17:23 +00001253 Buffer.reserve(256 * 1024);
Chris Lattner00950542001-06-06 20:29:01 +00001254
Reid Spencer17f52c52004-11-06 23:17:23 +00001255 // The BytecodeWriter populates Buffer for us.
Reid Spencerad89bd62004-07-25 18:07:36 +00001256 BytecodeWriter BCW(Buffer, M);
Chris Lattner00950542001-06-06 20:29:01 +00001257
Reid Spencer17f52c52004-11-06 23:17:23 +00001258 // Keep track of how much we've written
Chris Lattnerce6ef112002-07-26 18:40:14 +00001259 BytesWritten += Buffer.size();
1260
Reid Spencer17f52c52004-11-06 23:17:23 +00001261 // Determine start and end points of the Buffer
Reid Spencer83296f52004-11-07 18:17:38 +00001262 const unsigned char *FirstByte = &Buffer.front();
Reid Spencer17f52c52004-11-06 23:17:23 +00001263
1264 // If we're supposed to compress this mess ...
1265 if (compress) {
1266
1267 // We signal compression by using an alternate magic number for the
Reid Spencer83296f52004-11-07 18:17:38 +00001268 // file. The compressed bytecode file's magic number is "llvc" instead
Misha Brukman23c6d2c2005-04-21 21:48:46 +00001269 // of "llvm".
Reid Spencer83296f52004-11-07 18:17:38 +00001270 char compressed_magic[4];
1271 compressed_magic[0] = 'l';
1272 compressed_magic[1] = 'l';
1273 compressed_magic[2] = 'v';
1274 compressed_magic[3] = 'c';
Reid Spencer17f52c52004-11-06 23:17:23 +00001275
Bill Wendling68fe61d2006-11-29 00:19:40 +00001276 Out.stream()->write(compressed_magic,4);
Reid Spencer17f52c52004-11-06 23:17:23 +00001277
Reid Spencera70d84d2004-11-14 22:01:41 +00001278 // Compress everything after the magic number (which we altered)
Reid Spencer3ed469c2006-11-02 20:25:50 +00001279 Compressor::compressToStream(
Reid Spencer17f52c52004-11-06 23:17:23 +00001280 (char*)(FirstByte+4), // Skip the magic number
1281 Buffer.size()-4, // Skip the magic number
Bill Wendling68fe61d2006-11-29 00:19:40 +00001282 *Out.stream() // Where to write compressed data
Reid Spencer17f52c52004-11-06 23:17:23 +00001283 );
1284
Reid Spencer17f52c52004-11-06 23:17:23 +00001285 } else {
1286
1287 // We're not compressing, so just write the entire block.
Bill Wendling68fe61d2006-11-29 00:19:40 +00001288 Out.stream()->write((char*)FirstByte, Buffer.size());
Chris Lattnere8fdde12001-09-07 16:39:41 +00001289 }
Reid Spencer17f52c52004-11-06 23:17:23 +00001290
1291 // make sure it hits disk now
Bill Wendling68fe61d2006-11-29 00:19:40 +00001292 Out.stream()->flush();
Chris Lattner00950542001-06-06 20:29:01 +00001293}