blob: f2ded65b0722fd631c2944c3c4c9dc02ffbbfc1f [file] [log] [blame]
Chris Lattner14999342004-01-10 19:07:06 +00001//===-- Writer.cpp - Library for writing LLVM bytecode files --------------===//
Misha Brukman23c6d2c2005-04-21 21:48:46 +00002//
John Criswellb576c942003-10-20 19:43:21 +00003// The LLVM Compiler Infrastructure
4//
5// This file was developed by the LLVM research group and is distributed under
6// the University of Illinois Open Source License. See LICENSE.TXT for details.
Misha Brukman23c6d2c2005-04-21 21:48:46 +00007//
John Criswellb576c942003-10-20 19:43:21 +00008//===----------------------------------------------------------------------===//
Chris Lattner00950542001-06-06 20:29:01 +00009//
10// This library implements the functionality defined in llvm/Bytecode/Writer.h
11//
Chris Lattner00950542001-06-06 20:29:01 +000012// Note that this file uses an unusual technique of outputting all the bytecode
Reid Spencerad89bd62004-07-25 18:07:36 +000013// to a vector of unsigned char, then copies the vector to an ostream. The
Chris Lattner00950542001-06-06 20:29:01 +000014// reason for this is that we must do "seeking" in the stream to do back-
15// patching, and some very important ostreams that we want to support (like
16// pipes) do not support seeking. :( :( :(
17//
Chris Lattner00950542001-06-06 20:29:01 +000018//===----------------------------------------------------------------------===//
19
20#include "WriterInternals.h"
Chris Lattner635cd932002-07-23 19:56:44 +000021#include "llvm/Bytecode/WriteBytecodePass.h"
Chris Lattnerdee199f2005-05-06 22:34:01 +000022#include "llvm/CallingConv.h"
Chris Lattner83bb3d22004-01-14 23:36:54 +000023#include "llvm/Constants.h"
24#include "llvm/DerivedTypes.h"
Chris Lattner3bc5a602006-01-25 23:08:15 +000025#include "llvm/InlineAsm.h"
Reid Spencerad89bd62004-07-25 18:07:36 +000026#include "llvm/Instructions.h"
Chris Lattner00950542001-06-06 20:29:01 +000027#include "llvm/Module.h"
Chris Lattner00950542001-06-06 20:29:01 +000028#include "llvm/SymbolTable.h"
Reid Spencerad89bd62004-07-25 18:07:36 +000029#include "llvm/Support/GetElementPtrTypeIterator.h"
Reid Spencer17f52c52004-11-06 23:17:23 +000030#include "llvm/Support/Compressor.h"
Jim Laskeycb6682f2005-08-17 19:34:49 +000031#include "llvm/Support/MathExtras.h"
Reid Spencer32f55532006-06-07 23:18:34 +000032#include "llvm/System/Program.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000033#include "llvm/ADT/STLExtras.h"
34#include "llvm/ADT/Statistic.h"
Chris Lattner32abce62004-01-10 19:10:01 +000035#include <cstring>
Chris Lattner00950542001-06-06 20:29:01 +000036#include <algorithm>
Chris Lattner44f549b2004-01-10 18:49:43 +000037using namespace llvm;
Brian Gaeked0fde302003-11-11 22:41:34 +000038
Reid Spencer38d54be2004-08-17 07:45:14 +000039/// This value needs to be incremented every time the bytecode format changes
40/// so that the reader can distinguish which format of the bytecode file has
41/// been written.
42/// @brief The bytecode version number
Reid Spencer6996feb2006-11-08 21:27:54 +000043const unsigned BCVersionNum = 7;
Reid Spencer38d54be2004-08-17 07:45:14 +000044
Chris Lattner635cd932002-07-23 19:56:44 +000045static RegisterPass<WriteBytecodePass> X("emitbytecode", "Bytecode Writer");
46
Misha Brukman23c6d2c2005-04-21 21:48:46 +000047static Statistic<>
Chris Lattnera92f6962002-10-01 22:38:41 +000048BytesWritten("bytecodewriter", "Number of bytecode bytes written");
Chris Lattner635cd932002-07-23 19:56:44 +000049
Reid Spencerad89bd62004-07-25 18:07:36 +000050//===----------------------------------------------------------------------===//
51//=== Output Primitives ===//
52//===----------------------------------------------------------------------===//
53
54// output - If a position is specified, it must be in the valid portion of the
Misha Brukman23c6d2c2005-04-21 21:48:46 +000055// string... note that this should be inlined always so only the relevant IF
Reid Spencerad89bd62004-07-25 18:07:36 +000056// body should be included.
57inline void BytecodeWriter::output(unsigned i, int pos) {
58 if (pos == -1) { // Be endian clean, little endian is our friend
Misha Brukman23c6d2c2005-04-21 21:48:46 +000059 Out.push_back((unsigned char)i);
Reid Spencerad89bd62004-07-25 18:07:36 +000060 Out.push_back((unsigned char)(i >> 8));
61 Out.push_back((unsigned char)(i >> 16));
62 Out.push_back((unsigned char)(i >> 24));
63 } else {
64 Out[pos ] = (unsigned char)i;
65 Out[pos+1] = (unsigned char)(i >> 8);
66 Out[pos+2] = (unsigned char)(i >> 16);
67 Out[pos+3] = (unsigned char)(i >> 24);
68 }
69}
70
71inline void BytecodeWriter::output(int i) {
72 output((unsigned)i);
73}
74
75/// output_vbr - Output an unsigned value, by using the least number of bytes
76/// possible. This is useful because many of our "infinite" values are really
77/// very small most of the time; but can be large a few times.
Misha Brukman23c6d2c2005-04-21 21:48:46 +000078/// Data format used: If you read a byte with the high bit set, use the low
79/// seven bits as data and then read another byte.
Reid Spencerad89bd62004-07-25 18:07:36 +000080inline void BytecodeWriter::output_vbr(uint64_t i) {
81 while (1) {
82 if (i < 0x80) { // done?
83 Out.push_back((unsigned char)i); // We know the high bit is clear...
84 return;
85 }
Misha Brukman23c6d2c2005-04-21 21:48:46 +000086
Reid Spencerad89bd62004-07-25 18:07:36 +000087 // Nope, we are bigger than a character, output the next 7 bits and set the
88 // high bit to say that there is more coming...
89 Out.push_back(0x80 | ((unsigned char)i & 0x7F));
90 i >>= 7; // Shift out 7 bits now...
91 }
92}
93
94inline void BytecodeWriter::output_vbr(unsigned i) {
95 while (1) {
96 if (i < 0x80) { // done?
97 Out.push_back((unsigned char)i); // We know the high bit is clear...
98 return;
99 }
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000100
Reid Spencerad89bd62004-07-25 18:07:36 +0000101 // Nope, we are bigger than a character, output the next 7 bits and set the
102 // high bit to say that there is more coming...
103 Out.push_back(0x80 | ((unsigned char)i & 0x7F));
104 i >>= 7; // Shift out 7 bits now...
105 }
106}
107
108inline void BytecodeWriter::output_typeid(unsigned i) {
109 if (i <= 0x00FFFFFF)
110 this->output_vbr(i);
111 else {
112 this->output_vbr(0x00FFFFFF);
113 this->output_vbr(i);
114 }
115}
116
117inline void BytecodeWriter::output_vbr(int64_t i) {
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000118 if (i < 0)
Reid Spencerad89bd62004-07-25 18:07:36 +0000119 output_vbr(((uint64_t)(-i) << 1) | 1); // Set low order sign bit...
120 else
121 output_vbr((uint64_t)i << 1); // Low order bit is clear.
122}
123
124
125inline void BytecodeWriter::output_vbr(int i) {
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000126 if (i < 0)
Reid Spencerad89bd62004-07-25 18:07:36 +0000127 output_vbr(((unsigned)(-i) << 1) | 1); // Set low order sign bit...
128 else
129 output_vbr((unsigned)i << 1); // Low order bit is clear.
130}
131
Reid Spencer38d54be2004-08-17 07:45:14 +0000132inline void BytecodeWriter::output(const std::string &s) {
Reid Spencerad89bd62004-07-25 18:07:36 +0000133 unsigned Len = s.length();
Chris Lattnerc847f7c2006-07-28 22:07:54 +0000134 output_vbr(Len); // Strings may have an arbitrary length.
Reid Spencerad89bd62004-07-25 18:07:36 +0000135 Out.insert(Out.end(), s.begin(), s.end());
Reid Spencerad89bd62004-07-25 18:07:36 +0000136}
137
138inline void BytecodeWriter::output_data(const void *Ptr, const void *End) {
139 Out.insert(Out.end(), (const unsigned char*)Ptr, (const unsigned char*)End);
140}
141
142inline void BytecodeWriter::output_float(float& FloatVal) {
143 /// FIXME: This isn't optimal, it has size problems on some platforms
144 /// where FP is not IEEE.
Jim Laskeycb6682f2005-08-17 19:34:49 +0000145 uint32_t i = FloatToBits(FloatVal);
Chris Lattnerc847f7c2006-07-28 22:07:54 +0000146 Out.push_back( static_cast<unsigned char>( (i ) & 0xFF));
147 Out.push_back( static_cast<unsigned char>( (i >> 8 ) & 0xFF));
Jim Laskeycb6682f2005-08-17 19:34:49 +0000148 Out.push_back( static_cast<unsigned char>( (i >> 16) & 0xFF));
149 Out.push_back( static_cast<unsigned char>( (i >> 24) & 0xFF));
Reid Spencerad89bd62004-07-25 18:07:36 +0000150}
151
152inline void BytecodeWriter::output_double(double& DoubleVal) {
153 /// FIXME: This isn't optimal, it has size problems on some platforms
154 /// where FP is not IEEE.
Jim Laskeycb6682f2005-08-17 19:34:49 +0000155 uint64_t i = DoubleToBits(DoubleVal);
Chris Lattnerc847f7c2006-07-28 22:07:54 +0000156 Out.push_back( static_cast<unsigned char>( (i ) & 0xFF));
157 Out.push_back( static_cast<unsigned char>( (i >> 8 ) & 0xFF));
Jim Laskeycb6682f2005-08-17 19:34:49 +0000158 Out.push_back( static_cast<unsigned char>( (i >> 16) & 0xFF));
159 Out.push_back( static_cast<unsigned char>( (i >> 24) & 0xFF));
160 Out.push_back( static_cast<unsigned char>( (i >> 32) & 0xFF));
161 Out.push_back( static_cast<unsigned char>( (i >> 40) & 0xFF));
162 Out.push_back( static_cast<unsigned char>( (i >> 48) & 0xFF));
163 Out.push_back( static_cast<unsigned char>( (i >> 56) & 0xFF));
Reid Spencerad89bd62004-07-25 18:07:36 +0000164}
165
Chris Lattnerc76ea432005-11-12 18:34:09 +0000166inline BytecodeBlock::BytecodeBlock(unsigned ID, BytecodeWriter &w,
167 bool elideIfEmpty, bool hasLongFormat)
Reid Spencerad89bd62004-07-25 18:07:36 +0000168 : Id(ID), Writer(w), ElideIfEmpty(elideIfEmpty), HasLongFormat(hasLongFormat){
169
170 if (HasLongFormat) {
171 w.output(ID);
172 w.output(0U); // For length in long format
173 } else {
174 w.output(0U); /// Place holder for ID and length for this block
175 }
176 Loc = w.size();
177}
178
Chris Lattnerb0bf6642004-10-14 01:35:17 +0000179inline BytecodeBlock::~BytecodeBlock() { // Do backpatch when block goes out
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000180 // of scope...
Reid Spencerad89bd62004-07-25 18:07:36 +0000181 if (Loc == Writer.size() && ElideIfEmpty) {
182 // If the block is empty, and we are allowed to, do not emit the block at
183 // all!
184 Writer.resize(Writer.size()-(HasLongFormat?8:4));
185 return;
186 }
187
Reid Spencerad89bd62004-07-25 18:07:36 +0000188 if (HasLongFormat)
189 Writer.output(unsigned(Writer.size()-Loc), int(Loc-4));
190 else
191 Writer.output(unsigned(Writer.size()-Loc) << 5 | (Id & 0x1F), int(Loc-4));
Reid Spencerad89bd62004-07-25 18:07:36 +0000192}
193
194//===----------------------------------------------------------------------===//
195//=== Constant Output ===//
196//===----------------------------------------------------------------------===//
197
198void BytecodeWriter::outputType(const Type *T) {
199 output_vbr((unsigned)T->getTypeID());
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000200
Reid Spencerad89bd62004-07-25 18:07:36 +0000201 // That's all there is to handling primitive types...
202 if (T->isPrimitiveType()) {
203 return; // We might do this if we alias a prim type: %x = type int
204 }
205
206 switch (T->getTypeID()) { // Handle derived types now.
207 case Type::FunctionTyID: {
208 const FunctionType *MT = cast<FunctionType>(T);
209 int Slot = Table.getSlot(MT->getReturnType());
210 assert(Slot != -1 && "Type used but not available!!");
211 output_typeid((unsigned)Slot);
212
213 // Output the number of arguments to function (+1 if varargs):
214 output_vbr((unsigned)MT->getNumParams()+MT->isVarArg());
215
216 // Output all of the arguments...
217 FunctionType::param_iterator I = MT->param_begin();
218 for (; I != MT->param_end(); ++I) {
219 Slot = Table.getSlot(*I);
220 assert(Slot != -1 && "Type used but not available!!");
221 output_typeid((unsigned)Slot);
222 }
223
224 // Terminate list with VoidTy if we are a varargs function...
225 if (MT->isVarArg())
226 output_typeid((unsigned)Type::VoidTyID);
227 break;
228 }
229
230 case Type::ArrayTyID: {
231 const ArrayType *AT = cast<ArrayType>(T);
232 int Slot = Table.getSlot(AT->getElementType());
233 assert(Slot != -1 && "Type used but not available!!");
234 output_typeid((unsigned)Slot);
Reid Spencerad89bd62004-07-25 18:07:36 +0000235 output_vbr(AT->getNumElements());
236 break;
237 }
238
Brian Gaeke715c90b2004-08-20 06:00:58 +0000239 case Type::PackedTyID: {
240 const PackedType *PT = cast<PackedType>(T);
241 int Slot = Table.getSlot(PT->getElementType());
242 assert(Slot != -1 && "Type used but not available!!");
243 output_typeid((unsigned)Slot);
244 output_vbr(PT->getNumElements());
245 break;
246 }
247
248
Reid Spencerad89bd62004-07-25 18:07:36 +0000249 case Type::StructTyID: {
250 const StructType *ST = cast<StructType>(T);
251
252 // Output all of the element types...
253 for (StructType::element_iterator I = ST->element_begin(),
254 E = ST->element_end(); I != E; ++I) {
255 int Slot = Table.getSlot(*I);
256 assert(Slot != -1 && "Type used but not available!!");
257 output_typeid((unsigned)Slot);
258 }
259
260 // Terminate list with VoidTy
261 output_typeid((unsigned)Type::VoidTyID);
262 break;
263 }
264
265 case Type::PointerTyID: {
266 const PointerType *PT = cast<PointerType>(T);
267 int Slot = Table.getSlot(PT->getElementType());
268 assert(Slot != -1 && "Type used but not available!!");
269 output_typeid((unsigned)Slot);
270 break;
271 }
272
Chris Lattnerb0bf6642004-10-14 01:35:17 +0000273 case Type::OpaqueTyID:
Reid Spencerad89bd62004-07-25 18:07:36 +0000274 // No need to emit anything, just the count of opaque types is enough.
275 break;
Reid Spencerad89bd62004-07-25 18:07:36 +0000276
Reid Spencerad89bd62004-07-25 18:07:36 +0000277 default:
278 std::cerr << __FILE__ << ":" << __LINE__ << ": Don't know how to serialize"
279 << " Type '" << T->getDescription() << "'\n";
280 break;
281 }
282}
283
284void BytecodeWriter::outputConstant(const Constant *CPV) {
285 assert((CPV->getType()->isPrimitiveType() || !CPV->isNullValue()) &&
286 "Shouldn't output null constants!");
287
288 // We must check for a ConstantExpr before switching by type because
289 // a ConstantExpr can be of any type, and has no explicit value.
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000290 //
Reid Spencerad89bd62004-07-25 18:07:36 +0000291 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CPV)) {
292 // FIXME: Encoding of constant exprs could be much more compact!
293 assert(CE->getNumOperands() > 0 && "ConstantExpr with 0 operands");
Reid Spencer3da59db2006-11-27 01:05:10 +0000294 assert(CE->getNumOperands() != 1 || CE->isCast());
Chris Lattnera79e7cc2004-10-16 18:18:16 +0000295 output_vbr(1+CE->getNumOperands()); // flags as an expr
Reid Spencerb83eb642006-10-20 07:07:24 +0000296 output_vbr(CE->getOpcode()); // Put out the CE op code
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000297
Reid Spencerad89bd62004-07-25 18:07:36 +0000298 for (User::const_op_iterator OI = CE->op_begin(); OI != CE->op_end(); ++OI){
299 int Slot = Table.getSlot(*OI);
300 assert(Slot != -1 && "Unknown constant used in ConstantExpr!!");
301 output_vbr((unsigned)Slot);
302 Slot = Table.getSlot((*OI)->getType());
303 output_typeid((unsigned)Slot);
304 }
305 return;
Chris Lattnera79e7cc2004-10-16 18:18:16 +0000306 } else if (isa<UndefValue>(CPV)) {
307 output_vbr(1U); // 1 -> UndefValue constant.
308 return;
Reid Spencerad89bd62004-07-25 18:07:36 +0000309 } else {
Reid Spencerb83eb642006-10-20 07:07:24 +0000310 output_vbr(0U); // flag as not a ConstantExpr (i.e. 0 operands)
Reid Spencerad89bd62004-07-25 18:07:36 +0000311 }
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000312
Reid Spencerad89bd62004-07-25 18:07:36 +0000313 switch (CPV->getType()->getTypeID()) {
314 case Type::BoolTyID: // Boolean Types
315 if (cast<ConstantBool>(CPV)->getValue())
316 output_vbr(1U);
317 else
318 output_vbr(0U);
319 break;
320
321 case Type::UByteTyID: // Unsigned integer types...
322 case Type::UShortTyID:
323 case Type::UIntTyID:
324 case Type::ULongTyID:
Reid Spencerb83eb642006-10-20 07:07:24 +0000325 output_vbr(cast<ConstantInt>(CPV)->getZExtValue());
Reid Spencerad89bd62004-07-25 18:07:36 +0000326 break;
327
328 case Type::SByteTyID: // Signed integer types...
329 case Type::ShortTyID:
330 case Type::IntTyID:
331 case Type::LongTyID:
Reid Spencerb83eb642006-10-20 07:07:24 +0000332 output_vbr(cast<ConstantInt>(CPV)->getSExtValue());
Reid Spencerad89bd62004-07-25 18:07:36 +0000333 break;
334
335 case Type::ArrayTyID: {
336 const ConstantArray *CPA = cast<ConstantArray>(CPV);
337 assert(!CPA->isString() && "Constant strings should be handled specially!");
338
Alkis Evlogimenos15876bb2004-08-04 08:44:43 +0000339 for (unsigned i = 0, e = CPA->getNumOperands(); i != e; ++i) {
Reid Spencerad89bd62004-07-25 18:07:36 +0000340 int Slot = Table.getSlot(CPA->getOperand(i));
341 assert(Slot != -1 && "Constant used but not available!!");
342 output_vbr((unsigned)Slot);
343 }
344 break;
345 }
346
Brian Gaeke715c90b2004-08-20 06:00:58 +0000347 case Type::PackedTyID: {
348 const ConstantPacked *CP = cast<ConstantPacked>(CPV);
349
350 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i) {
351 int Slot = Table.getSlot(CP->getOperand(i));
352 assert(Slot != -1 && "Constant used but not available!!");
353 output_vbr((unsigned)Slot);
354 }
355 break;
356 }
357
Reid Spencerad89bd62004-07-25 18:07:36 +0000358 case Type::StructTyID: {
359 const ConstantStruct *CPS = cast<ConstantStruct>(CPV);
Reid Spencerad89bd62004-07-25 18:07:36 +0000360
Alkis Evlogimenos15876bb2004-08-04 08:44:43 +0000361 for (unsigned i = 0, e = CPS->getNumOperands(); i != e; ++i) {
362 int Slot = Table.getSlot(CPS->getOperand(i));
Reid Spencerad89bd62004-07-25 18:07:36 +0000363 assert(Slot != -1 && "Constant used but not available!!");
364 output_vbr((unsigned)Slot);
365 }
366 break;
367 }
368
369 case Type::PointerTyID:
370 assert(0 && "No non-null, non-constant-expr constants allowed!");
371 abort();
372
373 case Type::FloatTyID: { // Floating point types...
374 float Tmp = (float)cast<ConstantFP>(CPV)->getValue();
375 output_float(Tmp);
376 break;
377 }
378 case Type::DoubleTyID: {
379 double Tmp = cast<ConstantFP>(CPV)->getValue();
380 output_double(Tmp);
381 break;
382 }
383
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000384 case Type::VoidTyID:
Reid Spencerad89bd62004-07-25 18:07:36 +0000385 case Type::LabelTyID:
386 default:
387 std::cerr << __FILE__ << ":" << __LINE__ << ": Don't know how to serialize"
388 << " type '" << *CPV->getType() << "'\n";
389 break;
390 }
391 return;
392}
393
Chris Lattner3bc5a602006-01-25 23:08:15 +0000394/// outputInlineAsm - InlineAsm's get emitted to the constant pool, so they can
395/// be shared by multiple uses.
396void BytecodeWriter::outputInlineAsm(const InlineAsm *IA) {
397 // Output a marker, so we know when we have one one parsing the constant pool.
398 // Note that this encoding is 5 bytes: not very efficient for a marker. Since
399 // unique inline asms are rare, this should hardly matter.
400 output_vbr(~0U);
401
402 output(IA->getAsmString());
403 output(IA->getConstraintString());
404 output_vbr(unsigned(IA->hasSideEffects()));
405}
406
Reid Spencerad89bd62004-07-25 18:07:36 +0000407void BytecodeWriter::outputConstantStrings() {
408 SlotCalculator::string_iterator I = Table.string_begin();
409 SlotCalculator::string_iterator E = Table.string_end();
410 if (I == E) return; // No strings to emit
411
412 // If we have != 0 strings to emit, output them now. Strings are emitted into
413 // the 'void' type plane.
414 output_vbr(unsigned(E-I));
415 output_typeid(Type::VoidTyID);
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000416
Reid Spencerad89bd62004-07-25 18:07:36 +0000417 // Emit all of the strings.
418 for (I = Table.string_begin(); I != E; ++I) {
419 const ConstantArray *Str = *I;
420 int Slot = Table.getSlot(Str->getType());
421 assert(Slot != -1 && "Constant string of unknown type?");
422 output_typeid((unsigned)Slot);
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000423
Reid Spencerad89bd62004-07-25 18:07:36 +0000424 // Now that we emitted the type (which indicates the size of the string),
425 // emit all of the characters.
426 std::string Val = Str->getAsString();
427 output_data(Val.c_str(), Val.c_str()+Val.size());
428 }
429}
430
431//===----------------------------------------------------------------------===//
432//=== Instruction Output ===//
433//===----------------------------------------------------------------------===//
Reid Spencerad89bd62004-07-25 18:07:36 +0000434
Chris Lattnerda895d62005-02-27 06:18:25 +0000435// outputInstructionFormat0 - Output those weird instructions that have a large
Chris Lattnerdee199f2005-05-06 22:34:01 +0000436// number of operands or have large operands themselves.
Reid Spencerad89bd62004-07-25 18:07:36 +0000437//
438// Format: [opcode] [type] [numargs] [arg0] [arg1] ... [arg<numargs-1>]
439//
Chris Lattnerf9d71782004-10-14 01:46:07 +0000440void BytecodeWriter::outputInstructionFormat0(const Instruction *I,
441 unsigned Opcode,
442 const SlotCalculator &Table,
443 unsigned Type) {
Reid Spencerad89bd62004-07-25 18:07:36 +0000444 // Opcode must have top two bits clear...
445 output_vbr(Opcode << 2); // Instruction Opcode ID
446 output_typeid(Type); // Result type
447
448 unsigned NumArgs = I->getNumOperands();
Reid Spencer3da59db2006-11-27 01:05:10 +0000449 output_vbr(NumArgs + (isa<CastInst>(I) || isa<InvokeInst>(I) ||
450 isa<VAArgInst>(I) || Opcode == 58));
Reid Spencerad89bd62004-07-25 18:07:36 +0000451
452 if (!isa<GetElementPtrInst>(&I)) {
453 for (unsigned i = 0; i < NumArgs; ++i) {
454 int Slot = Table.getSlot(I->getOperand(i));
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000455 assert(Slot >= 0 && "No slot number for value!?!?");
Reid Spencerad89bd62004-07-25 18:07:36 +0000456 output_vbr((unsigned)Slot);
457 }
458
459 if (isa<CastInst>(I) || isa<VAArgInst>(I)) {
460 int Slot = Table.getSlot(I->getType());
461 assert(Slot != -1 && "Cast return type unknown?");
462 output_typeid((unsigned)Slot);
Reid Spencer3da59db2006-11-27 01:05:10 +0000463 } else if (isa<InvokeInst>(I)) {
Chris Lattnerdee199f2005-05-06 22:34:01 +0000464 output_vbr(cast<InvokeInst>(I)->getCallingConv());
465 } else if (Opcode == 58) { // Call escape sequence
466 output_vbr((cast<CallInst>(I)->getCallingConv() << 1) |
Jeff Cohen39cef602005-05-07 02:44:04 +0000467 unsigned(cast<CallInst>(I)->isTailCall()));
Reid Spencerad89bd62004-07-25 18:07:36 +0000468 }
Reid Spencerad89bd62004-07-25 18:07:36 +0000469 } else {
470 int Slot = Table.getSlot(I->getOperand(0));
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000471 assert(Slot >= 0 && "No slot number for value!?!?");
Reid Spencerad89bd62004-07-25 18:07:36 +0000472 output_vbr(unsigned(Slot));
473
474 // We need to encode the type of sequential type indices into their slot #
475 unsigned Idx = 1;
476 for (gep_type_iterator TI = gep_type_begin(I), E = gep_type_end(I);
477 Idx != NumArgs; ++TI, ++Idx) {
478 Slot = Table.getSlot(I->getOperand(Idx));
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000479 assert(Slot >= 0 && "No slot number for value!?!?");
480
Reid Spencerad89bd62004-07-25 18:07:36 +0000481 if (isa<SequentialType>(*TI)) {
482 unsigned IdxId;
483 switch (I->getOperand(Idx)->getType()->getTypeID()) {
484 default: assert(0 && "Unknown index type!");
485 case Type::UIntTyID: IdxId = 0; break;
486 case Type::IntTyID: IdxId = 1; break;
487 case Type::ULongTyID: IdxId = 2; break;
488 case Type::LongTyID: IdxId = 3; break;
489 }
490 Slot = (Slot << 2) | IdxId;
491 }
492 output_vbr(unsigned(Slot));
493 }
494 }
Reid Spencerad89bd62004-07-25 18:07:36 +0000495}
496
497
498// outputInstrVarArgsCall - Output the absurdly annoying varargs function calls.
499// This are more annoying than most because the signature of the call does not
500// tell us anything about the types of the arguments in the varargs portion.
501// Because of this, we encode (as type 0) all of the argument types explicitly
502// before the argument value. This really sucks, but you shouldn't be using
503// varargs functions in your code! *death to printf*!
504//
505// Format: [opcode] [type] [numargs] [arg0] [arg1] ... [arg<numargs-1>]
506//
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000507void BytecodeWriter::outputInstrVarArgsCall(const Instruction *I,
508 unsigned Opcode,
509 const SlotCalculator &Table,
510 unsigned Type) {
Reid Spencerad89bd62004-07-25 18:07:36 +0000511 assert(isa<CallInst>(I) || isa<InvokeInst>(I));
512 // Opcode must have top two bits clear...
513 output_vbr(Opcode << 2); // Instruction Opcode ID
514 output_typeid(Type); // Result type (varargs type)
515
516 const PointerType *PTy = cast<PointerType>(I->getOperand(0)->getType());
517 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
518 unsigned NumParams = FTy->getNumParams();
519
520 unsigned NumFixedOperands;
521 if (isa<CallInst>(I)) {
522 // Output an operand for the callee and each fixed argument, then two for
523 // each variable argument.
524 NumFixedOperands = 1+NumParams;
525 } else {
526 assert(isa<InvokeInst>(I) && "Not call or invoke??");
527 // Output an operand for the callee and destinations, then two for each
528 // variable argument.
529 NumFixedOperands = 3+NumParams;
530 }
Reid Spencer3da59db2006-11-27 01:05:10 +0000531 output_vbr(2 * I->getNumOperands()-NumFixedOperands +
532 unsigned(Opcode == 58 || isa<InvokeInst>(I)));
Reid Spencerad89bd62004-07-25 18:07:36 +0000533
534 // The type for the function has already been emitted in the type field of the
535 // instruction. Just emit the slot # now.
536 for (unsigned i = 0; i != NumFixedOperands; ++i) {
537 int Slot = Table.getSlot(I->getOperand(i));
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000538 assert(Slot >= 0 && "No slot number for value!?!?");
Reid Spencerad89bd62004-07-25 18:07:36 +0000539 output_vbr((unsigned)Slot);
540 }
541
542 for (unsigned i = NumFixedOperands, e = I->getNumOperands(); i != e; ++i) {
543 // Output Arg Type ID
544 int Slot = Table.getSlot(I->getOperand(i)->getType());
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000545 assert(Slot >= 0 && "No slot number for value!?!?");
Reid Spencerad89bd62004-07-25 18:07:36 +0000546 output_typeid((unsigned)Slot);
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000547
Reid Spencerad89bd62004-07-25 18:07:36 +0000548 // Output arg ID itself
549 Slot = Table.getSlot(I->getOperand(i));
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000550 assert(Slot >= 0 && "No slot number for value!?!?");
Reid Spencerad89bd62004-07-25 18:07:36 +0000551 output_vbr((unsigned)Slot);
552 }
Chris Lattnera65371e2006-05-26 18:42:34 +0000553
Reid Spencer3da59db2006-11-27 01:05:10 +0000554 if (isa<InvokeInst>(I)) {
555 // Emit the tail call/calling conv for invoke instructions
556 output_vbr(cast<InvokeInst>(I)->getCallingConv());
557 } else if (Opcode == 58) {
Chris Lattnera65371e2006-05-26 18:42:34 +0000558 const CallInst *CI = cast<CallInst>(I);
559 output_vbr((CI->getCallingConv() << 1) | unsigned(CI->isTailCall()));
Chris Lattnera65371e2006-05-26 18:42:34 +0000560 }
Reid Spencerad89bd62004-07-25 18:07:36 +0000561}
562
563
564// outputInstructionFormat1 - Output one operand instructions, knowing that no
565// operand index is >= 2^12.
566//
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000567inline void BytecodeWriter::outputInstructionFormat1(const Instruction *I,
568 unsigned Opcode,
569 unsigned *Slots,
570 unsigned Type) {
Reid Spencerad89bd62004-07-25 18:07:36 +0000571 // bits Instruction format:
572 // --------------------------
573 // 01-00: Opcode type, fixed to 1.
574 // 07-02: Opcode
575 // 19-08: Resulting type plane
576 // 31-20: Operand #1 (if set to (2^12-1), then zero operands)
577 //
Chris Lattnerf9d71782004-10-14 01:46:07 +0000578 output(1 | (Opcode << 2) | (Type << 8) | (Slots[0] << 20));
Reid Spencerad89bd62004-07-25 18:07:36 +0000579}
580
581
582// outputInstructionFormat2 - Output two operand instructions, knowing that no
583// operand index is >= 2^8.
584//
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000585inline void BytecodeWriter::outputInstructionFormat2(const Instruction *I,
586 unsigned Opcode,
587 unsigned *Slots,
588 unsigned Type) {
Reid Spencerad89bd62004-07-25 18:07:36 +0000589 // bits Instruction format:
590 // --------------------------
591 // 01-00: Opcode type, fixed to 2.
592 // 07-02: Opcode
593 // 15-08: Resulting type plane
594 // 23-16: Operand #1
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000595 // 31-24: Operand #2
Reid Spencerad89bd62004-07-25 18:07:36 +0000596 //
Chris Lattnerf9d71782004-10-14 01:46:07 +0000597 output(2 | (Opcode << 2) | (Type << 8) | (Slots[0] << 16) | (Slots[1] << 24));
Reid Spencerad89bd62004-07-25 18:07:36 +0000598}
599
600
601// outputInstructionFormat3 - Output three operand instructions, knowing that no
602// operand index is >= 2^6.
603//
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000604inline void BytecodeWriter::outputInstructionFormat3(const Instruction *I,
Reid Spencerad89bd62004-07-25 18:07:36 +0000605 unsigned Opcode,
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000606 unsigned *Slots,
607 unsigned Type) {
Reid Spencerad89bd62004-07-25 18:07:36 +0000608 // bits Instruction format:
609 // --------------------------
610 // 01-00: Opcode type, fixed to 3.
611 // 07-02: Opcode
612 // 13-08: Resulting type plane
613 // 19-14: Operand #1
614 // 25-20: Operand #2
615 // 31-26: Operand #3
616 //
Chris Lattnerf9d71782004-10-14 01:46:07 +0000617 output(3 | (Opcode << 2) | (Type << 8) |
Chris Lattner84d1ced2004-10-14 01:57:28 +0000618 (Slots[0] << 14) | (Slots[1] << 20) | (Slots[2] << 26));
Reid Spencerad89bd62004-07-25 18:07:36 +0000619}
620
621void BytecodeWriter::outputInstruction(const Instruction &I) {
Reid Spencer3da59db2006-11-27 01:05:10 +0000622 assert(I.getOpcode() < 57 && "Opcode too big???");
Reid Spencerad89bd62004-07-25 18:07:36 +0000623 unsigned Opcode = I.getOpcode();
624 unsigned NumOperands = I.getNumOperands();
625
Chris Lattner38287bd2005-05-06 06:13:34 +0000626 // Encode 'tail call' as 61, 'volatile load' as 62, and 'volatile store' as
627 // 63.
Chris Lattnerdee199f2005-05-06 22:34:01 +0000628 if (const CallInst *CI = dyn_cast<CallInst>(&I)) {
629 if (CI->getCallingConv() == CallingConv::C) {
630 if (CI->isTailCall())
631 Opcode = 61; // CCC + Tail Call
632 else
633 ; // Opcode = Instruction::Call
634 } else if (CI->getCallingConv() == CallingConv::Fast) {
635 if (CI->isTailCall())
636 Opcode = 59; // FastCC + TailCall
637 else
638 Opcode = 60; // FastCC + Not Tail Call
639 } else {
640 Opcode = 58; // Call escape sequence.
641 }
Chris Lattnerdee199f2005-05-06 22:34:01 +0000642 } else if (isa<LoadInst>(I) && cast<LoadInst>(I).isVolatile()) {
Reid Spencerad89bd62004-07-25 18:07:36 +0000643 Opcode = 62;
Chris Lattnerdee199f2005-05-06 22:34:01 +0000644 } else if (isa<StoreInst>(I) && cast<StoreInst>(I).isVolatile()) {
Reid Spencerad89bd62004-07-25 18:07:36 +0000645 Opcode = 63;
Chris Lattnerdee199f2005-05-06 22:34:01 +0000646 }
Reid Spencerad89bd62004-07-25 18:07:36 +0000647
648 // Figure out which type to encode with the instruction. Typically we want
649 // the type of the first parameter, as opposed to the type of the instruction
650 // (for example, with setcc, we always know it returns bool, but the type of
651 // the first param is actually interesting). But if we have no arguments
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000652 // we take the type of the instruction itself.
Reid Spencerad89bd62004-07-25 18:07:36 +0000653 //
654 const Type *Ty;
655 switch (I.getOpcode()) {
656 case Instruction::Select:
657 case Instruction::Malloc:
658 case Instruction::Alloca:
659 Ty = I.getType(); // These ALWAYS want to encode the return type
660 break;
661 case Instruction::Store:
662 Ty = I.getOperand(1)->getType(); // Encode the pointer type...
663 assert(isa<PointerType>(Ty) && "Store to nonpointer type!?!?");
664 break;
665 default: // Otherwise use the default behavior...
666 Ty = NumOperands ? I.getOperand(0)->getType() : I.getType();
667 break;
668 }
669
670 unsigned Type;
671 int Slot = Table.getSlot(Ty);
672 assert(Slot != -1 && "Type not available!!?!");
673 Type = (unsigned)Slot;
674
675 // Varargs calls and invokes are encoded entirely different from any other
676 // instructions.
677 if (const CallInst *CI = dyn_cast<CallInst>(&I)){
678 const PointerType *Ty =cast<PointerType>(CI->getCalledValue()->getType());
679 if (cast<FunctionType>(Ty->getElementType())->isVarArg()) {
680 outputInstrVarArgsCall(CI, Opcode, Table, Type);
681 return;
682 }
683 } else if (const InvokeInst *II = dyn_cast<InvokeInst>(&I)) {
684 const PointerType *Ty =cast<PointerType>(II->getCalledValue()->getType());
685 if (cast<FunctionType>(Ty->getElementType())->isVarArg()) {
686 outputInstrVarArgsCall(II, Opcode, Table, Type);
687 return;
688 }
689 }
690
691 if (NumOperands <= 3) {
692 // Make sure that we take the type number into consideration. We don't want
693 // to overflow the field size for the instruction format we select.
694 //
695 unsigned MaxOpSlot = Type;
696 unsigned Slots[3]; Slots[0] = (1 << 12)-1; // Marker to signify 0 operands
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000697
Reid Spencerad89bd62004-07-25 18:07:36 +0000698 for (unsigned i = 0; i != NumOperands; ++i) {
699 int slot = Table.getSlot(I.getOperand(i));
700 assert(slot != -1 && "Broken bytecode!");
701 if (unsigned(slot) > MaxOpSlot) MaxOpSlot = unsigned(slot);
702 Slots[i] = unsigned(slot);
703 }
704
705 // Handle the special cases for various instructions...
706 if (isa<CastInst>(I) || isa<VAArgInst>(I)) {
707 // Cast has to encode the destination type as the second argument in the
708 // packet, or else we won't know what type to cast to!
709 Slots[1] = Table.getSlot(I.getType());
710 assert(Slots[1] != ~0U && "Cast return type unknown?");
711 if (Slots[1] > MaxOpSlot) MaxOpSlot = Slots[1];
712 NumOperands++;
Chris Lattner42ba6b42005-11-05 22:08:14 +0000713 } else if (const AllocationInst *AI = dyn_cast<AllocationInst>(&I)) {
714 assert(NumOperands == 1 && "Bogus allocation!");
715 if (AI->getAlignment()) {
716 Slots[1] = Log2_32(AI->getAlignment())+1;
717 if (Slots[1] > MaxOpSlot) MaxOpSlot = Slots[1];
718 NumOperands = 2;
719 }
Reid Spencerad89bd62004-07-25 18:07:36 +0000720 } else if (const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(&I)) {
721 // We need to encode the type of sequential type indices into their slot #
722 unsigned Idx = 1;
723 for (gep_type_iterator I = gep_type_begin(GEP), E = gep_type_end(GEP);
724 I != E; ++I, ++Idx)
725 if (isa<SequentialType>(*I)) {
726 unsigned IdxId;
727 switch (GEP->getOperand(Idx)->getType()->getTypeID()) {
728 default: assert(0 && "Unknown index type!");
729 case Type::UIntTyID: IdxId = 0; break;
730 case Type::IntTyID: IdxId = 1; break;
731 case Type::ULongTyID: IdxId = 2; break;
732 case Type::LongTyID: IdxId = 3; break;
733 }
734 Slots[Idx] = (Slots[Idx] << 2) | IdxId;
735 if (Slots[Idx] > MaxOpSlot) MaxOpSlot = Slots[Idx];
736 }
Chris Lattnerdee199f2005-05-06 22:34:01 +0000737 } else if (Opcode == 58) {
738 // If this is the escape sequence for call, emit the tailcall/cc info.
739 const CallInst &CI = cast<CallInst>(I);
740 ++NumOperands;
Chris Lattnerebf8e6c2006-05-19 21:57:37 +0000741 if (NumOperands <= 3) {
742 Slots[NumOperands-1] =
743 (CI.getCallingConv() << 1)|unsigned(CI.isTailCall());
Chris Lattnerdee199f2005-05-06 22:34:01 +0000744 if (Slots[NumOperands-1] > MaxOpSlot)
745 MaxOpSlot = Slots[NumOperands-1];
746 }
Reid Spencer3da59db2006-11-27 01:05:10 +0000747 } else if (isa<InvokeInst>(I)) {
Chris Lattnerdee199f2005-05-06 22:34:01 +0000748 // Invoke escape seq has at least 4 operands to encode.
749 ++NumOperands;
Reid Spencerad89bd62004-07-25 18:07:36 +0000750 }
751
752 // Decide which instruction encoding to use. This is determined primarily
753 // by the number of operands, and secondarily by whether or not the max
754 // operand will fit into the instruction encoding. More operands == fewer
755 // bits per operand.
756 //
757 switch (NumOperands) {
758 case 0:
759 case 1:
760 if (MaxOpSlot < (1 << 12)-1) { // -1 because we use 4095 to indicate 0 ops
761 outputInstructionFormat1(&I, Opcode, Slots, Type);
762 return;
763 }
764 break;
765
766 case 2:
767 if (MaxOpSlot < (1 << 8)) {
768 outputInstructionFormat2(&I, Opcode, Slots, Type);
769 return;
770 }
771 break;
772
773 case 3:
774 if (MaxOpSlot < (1 << 6)) {
775 outputInstructionFormat3(&I, Opcode, Slots, Type);
776 return;
777 }
778 break;
779 default:
780 break;
781 }
782 }
783
784 // If we weren't handled before here, we either have a large number of
785 // operands or a large operand index that we are referring to.
786 outputInstructionFormat0(&I, Opcode, Table, Type);
787}
788
789//===----------------------------------------------------------------------===//
790//=== Block Output ===//
791//===----------------------------------------------------------------------===//
792
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000793BytecodeWriter::BytecodeWriter(std::vector<unsigned char> &o, const Module *M)
Reid Spencer798ff642004-05-26 07:37:11 +0000794 : Out(o), Table(M) {
Chris Lattner00950542001-06-06 20:29:01 +0000795
Chris Lattner83bb3d22004-01-14 23:36:54 +0000796 // Emit the signature...
Chris Lattnerc847f7c2006-07-28 22:07:54 +0000797 static const unsigned char *Sig = (const unsigned char*)"llvm";
Reid Spencerad89bd62004-07-25 18:07:36 +0000798 output_data(Sig, Sig+4);
Chris Lattner00950542001-06-06 20:29:01 +0000799
800 // Emit the top level CLASS block.
Reid Spencerad89bd62004-07-25 18:07:36 +0000801 BytecodeBlock ModuleBlock(BytecodeFormat::ModuleBlockID, *this, false, true);
Chris Lattner00950542001-06-06 20:29:01 +0000802
Chris Lattnerd445c6b2003-08-24 13:47:36 +0000803 bool isBigEndian = M->getEndianness() == Module::BigEndian;
804 bool hasLongPointers = M->getPointerSize() == Module::Pointer64;
805 bool hasNoEndianness = M->getEndianness() == Module::AnyEndianness;
806 bool hasNoPointerSize = M->getPointerSize() == Module::AnyPointerSize;
Chris Lattner186a1f72003-03-19 20:56:46 +0000807
Chris Lattnera79e7cc2004-10-16 18:18:16 +0000808 // Output the version identifier and other information.
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000809 unsigned Version = (BCVersionNum << 4) |
Reid Spencer38d54be2004-08-17 07:45:14 +0000810 (unsigned)isBigEndian | (hasLongPointers << 1) |
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000811 (hasNoEndianness << 2) |
Reid Spencer38d54be2004-08-17 07:45:14 +0000812 (hasNoPointerSize << 3);
Reid Spencerad89bd62004-07-25 18:07:36 +0000813 output_vbr(Version);
Chris Lattner00950542001-06-06 20:29:01 +0000814
Reid Spencercb3595c2004-07-04 11:45:47 +0000815 // The Global type plane comes first
Chris Lattner186a1f72003-03-19 20:56:46 +0000816 {
Chris Lattnerc847f7c2006-07-28 22:07:54 +0000817 BytecodeBlock CPool(BytecodeFormat::GlobalTypePlaneBlockID, *this);
818 outputTypes(Type::FirstDerivedTyID);
Chris Lattner186a1f72003-03-19 20:56:46 +0000819 }
Chris Lattner00950542001-06-06 20:29:01 +0000820
Chris Lattner186a1f72003-03-19 20:56:46 +0000821 // The ModuleInfoBlock follows directly after the type information
Chris Lattnere8fdde12001-09-07 16:39:41 +0000822 outputModuleInfoBlock(M);
823
Chris Lattner186a1f72003-03-19 20:56:46 +0000824 // Output module level constants, used for global variable initializers
825 outputConstants(false);
826
Chris Lattnerb5794002002-04-07 22:49:37 +0000827 // Do the whole module now! Process each function at a time...
Chris Lattner0b12b5f2002-06-25 16:13:21 +0000828 for (Module::const_iterator I = M->begin(), E = M->end(); I != E; ++I)
Chris Lattner186a1f72003-03-19 20:56:46 +0000829 outputFunction(I);
Chris Lattnere8fdde12001-09-07 16:39:41 +0000830
831 // If needed, output the symbol table for the module...
Chris Lattner6e6026b2002-11-20 18:36:02 +0000832 outputSymbolTable(M->getSymbolTable());
Chris Lattner00950542001-06-06 20:29:01 +0000833}
834
Chris Lattnerf9d71782004-10-14 01:46:07 +0000835void BytecodeWriter::outputTypes(unsigned TypeNum) {
Reid Spencercb3595c2004-07-04 11:45:47 +0000836 // Write the type plane for types first because earlier planes (e.g. for a
837 // primitive type like float) may have constants constructed using types
838 // coming later (e.g., via getelementptr from a pointer type). The type
839 // plane is needed before types can be fwd or bkwd referenced.
840 const std::vector<const Type*>& Types = Table.getTypes();
841 assert(!Types.empty() && "No types at all?");
842 assert(TypeNum <= Types.size() && "Invalid TypeNo index");
843
844 unsigned NumEntries = Types.size() - TypeNum;
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000845
Reid Spencercb3595c2004-07-04 11:45:47 +0000846 // Output type header: [num entries]
Reid Spencerad89bd62004-07-25 18:07:36 +0000847 output_vbr(NumEntries);
Reid Spencercb3595c2004-07-04 11:45:47 +0000848
849 for (unsigned i = TypeNum; i < TypeNum+NumEntries; ++i)
850 outputType(Types[i]);
851}
852
Vikram S. Advea7dac3d2002-07-14 23:07:51 +0000853// Helper function for outputConstants().
854// Writes out all the constants in the plane Plane starting at entry StartNo.
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000855//
Vikram S. Advea7dac3d2002-07-14 23:07:51 +0000856void BytecodeWriter::outputConstantsInPlane(const std::vector<const Value*>
857 &Plane, unsigned StartNo) {
858 unsigned ValNo = StartNo;
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000859
Chris Lattner83bb3d22004-01-14 23:36:54 +0000860 // Scan through and ignore function arguments, global values, and constant
861 // strings.
862 for (; ValNo < Plane.size() &&
863 (isa<Argument>(Plane[ValNo]) || isa<GlobalValue>(Plane[ValNo]) ||
864 (isa<ConstantArray>(Plane[ValNo]) &&
865 cast<ConstantArray>(Plane[ValNo])->isString())); ValNo++)
Vikram S. Advea7dac3d2002-07-14 23:07:51 +0000866 /*empty*/;
867
868 unsigned NC = ValNo; // Number of constants
Chris Lattner3bc5a602006-01-25 23:08:15 +0000869 for (; NC < Plane.size() && (isa<Constant>(Plane[NC]) ||
870 isa<InlineAsm>(Plane[NC])); NC++)
Vikram S. Advea7dac3d2002-07-14 23:07:51 +0000871 /*empty*/;
872 NC -= ValNo; // Convert from index into count
873 if (NC == 0) return; // Skip empty type planes...
874
Chris Lattnerd6942d72004-01-14 16:54:21 +0000875 // FIXME: Most slabs only have 1 or 2 entries! We should encode this much
876 // more compactly.
877
Reid Spencerb83eb642006-10-20 07:07:24 +0000878 // Put out type header: [num entries][type id number]
Vikram S. Advea7dac3d2002-07-14 23:07:51 +0000879 //
Reid Spencerad89bd62004-07-25 18:07:36 +0000880 output_vbr(NC);
Vikram S. Advea7dac3d2002-07-14 23:07:51 +0000881
Reid Spencerb83eb642006-10-20 07:07:24 +0000882 // Put out the Type ID Number...
Alkis Evlogimenos60596382003-10-17 02:02:40 +0000883 int Slot = Table.getSlot(Plane.front()->getType());
Vikram S. Advea7dac3d2002-07-14 23:07:51 +0000884 assert (Slot != -1 && "Type in constant pool but not in function!!");
Reid Spencerad89bd62004-07-25 18:07:36 +0000885 output_typeid((unsigned)Slot);
Vikram S. Advea7dac3d2002-07-14 23:07:51 +0000886
Vikram S. Advea7dac3d2002-07-14 23:07:51 +0000887 for (unsigned i = ValNo; i < ValNo+NC; ++i) {
888 const Value *V = Plane[i];
Chris Lattner3bc5a602006-01-25 23:08:15 +0000889 if (const Constant *C = dyn_cast<Constant>(V))
Reid Spencere0125b62004-07-18 00:16:21 +0000890 outputConstant(C);
Chris Lattner3bc5a602006-01-25 23:08:15 +0000891 else
892 outputInlineAsm(cast<InlineAsm>(V));
Vikram S. Advea7dac3d2002-07-14 23:07:51 +0000893 }
894}
895
Chris Lattner9e60d8d2005-05-05 22:21:19 +0000896static inline bool hasNullValue(const Type *Ty) {
897 return Ty != Type::LabelTy && Ty != Type::VoidTy && !isa<OpaqueType>(Ty);
Chris Lattner80b97342004-01-17 23:25:43 +0000898}
899
Chris Lattner79df7c02002-03-26 18:01:55 +0000900void BytecodeWriter::outputConstants(bool isFunction) {
Reid Spencerad89bd62004-07-25 18:07:36 +0000901 BytecodeBlock CPool(BytecodeFormat::ConstantPoolBlockID, *this,
Chris Lattner0baa0af2004-01-15 21:06:57 +0000902 true /* Elide block if empty */);
Chris Lattner00950542001-06-06 20:29:01 +0000903
904 unsigned NumPlanes = Table.getNumPlanes();
Chris Lattnerf69315b2003-05-22 18:35:38 +0000905
Reid Spencere0125b62004-07-18 00:16:21 +0000906 if (isFunction)
907 // Output the type plane before any constants!
Chris Lattnera79e7cc2004-10-16 18:18:16 +0000908 outputTypes(Table.getModuleTypeLevel());
Reid Spencere0125b62004-07-18 00:16:21 +0000909 else
Chris Lattnerf9d71782004-10-14 01:46:07 +0000910 // Output module-level string constants before any other constants.
Chris Lattner83bb3d22004-01-14 23:36:54 +0000911 outputConstantStrings();
912
Reid Spencercb3595c2004-07-04 11:45:47 +0000913 for (unsigned pno = 0; pno != NumPlanes; pno++) {
914 const std::vector<const Value*> &Plane = Table.getPlane(pno);
915 if (!Plane.empty()) { // Skip empty type planes...
916 unsigned ValNo = 0;
917 if (isFunction) // Don't re-emit module constants
Reid Spencer0852c802004-07-04 11:46:15 +0000918 ValNo += Table.getModuleLevel(pno);
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000919
Chris Lattner9e60d8d2005-05-05 22:21:19 +0000920 if (hasNullValue(Plane[0]->getType())) {
Reid Spencer0852c802004-07-04 11:46:15 +0000921 // Skip zero initializer
922 if (ValNo == 0)
923 ValNo = 1;
Chris Lattnerf69315b2003-05-22 18:35:38 +0000924 }
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000925
Reid Spencercb3595c2004-07-04 11:45:47 +0000926 // Write out constants in the plane
927 outputConstantsInPlane(Plane, ValNo);
Chris Lattnerf69315b2003-05-22 18:35:38 +0000928 }
Reid Spencercb3595c2004-07-04 11:45:47 +0000929 }
Chris Lattner00950542001-06-06 20:29:01 +0000930}
931
Chris Lattner6b252422003-10-16 18:28:50 +0000932static unsigned getEncodedLinkage(const GlobalValue *GV) {
933 switch (GV->getLinkage()) {
934 default: assert(0 && "Invalid linkage!");
Anton Korobeynikovb74ed072006-09-14 18:23:27 +0000935 case GlobalValue::ExternalLinkage: return 0;
936 case GlobalValue::WeakLinkage: return 1;
937 case GlobalValue::AppendingLinkage: return 2;
938 case GlobalValue::InternalLinkage: return 3;
939 case GlobalValue::LinkOnceLinkage: return 4;
940 case GlobalValue::DLLImportLinkage: return 5;
941 case GlobalValue::DLLExportLinkage: return 6;
942 case GlobalValue::ExternalWeakLinkage: return 7;
Chris Lattner6b252422003-10-16 18:28:50 +0000943 }
944}
945
Chris Lattner00950542001-06-06 20:29:01 +0000946void BytecodeWriter::outputModuleInfoBlock(const Module *M) {
Reid Spencerad89bd62004-07-25 18:07:36 +0000947 BytecodeBlock ModuleInfoBlock(BytecodeFormat::ModuleGlobalInfoBlockID, *this);
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000948
Chris Lattner404cddf2005-11-12 01:33:40 +0000949 // Give numbers to sections as we encounter them.
950 unsigned SectionIDCounter = 0;
951 std::vector<std::string> SectionNames;
952 std::map<std::string, unsigned> SectionID;
953
Chris Lattner70cc3392001-09-10 07:58:01 +0000954 // Output the types for the global variables in the module...
Chris Lattner28caccf2005-05-06 20:27:03 +0000955 for (Module::const_global_iterator I = M->global_begin(),
Chris Lattner8eb52dd2005-11-06 07:11:04 +0000956 End = M->global_end(); I != End; ++I) {
Alkis Evlogimenos60596382003-10-17 02:02:40 +0000957 int Slot = Table.getSlot(I->getType());
Chris Lattner70cc3392001-09-10 07:58:01 +0000958 assert(Slot != -1 && "Module global vars is broken!");
Chris Lattnerd70684f2001-09-18 04:01:05 +0000959
Chris Lattner8eb52dd2005-11-06 07:11:04 +0000960 assert((I->hasInitializer() || !I->hasInternalLinkage()) &&
961 "Global must have an initializer or have external linkage!");
962
Chris Lattner22482a12003-10-18 06:30:21 +0000963 // Fields: bit0 = isConstant, bit1 = hasInitializer, bit2-4=Linkage,
Chris Lattner8eb52dd2005-11-06 07:11:04 +0000964 // bit5+ = Slot # for type.
Chris Lattner404cddf2005-11-12 01:33:40 +0000965 bool HasExtensionWord = (I->getAlignment() != 0) || I->hasSection();
Chris Lattner8eb52dd2005-11-06 07:11:04 +0000966
967 // If we need to use the extension byte, set linkage=3(internal) and
968 // initializer = 0 (impossible!).
969 if (!HasExtensionWord) {
970 unsigned oSlot = ((unsigned)Slot << 5) | (getEncodedLinkage(I) << 2) |
971 (I->hasInitializer() << 1) | (unsigned)I->isConstant();
972 output_vbr(oSlot);
Anton Korobeynikovb74ed072006-09-14 18:23:27 +0000973 } else {
Chris Lattner8eb52dd2005-11-06 07:11:04 +0000974 unsigned oSlot = ((unsigned)Slot << 5) | (3 << 2) |
975 (0 << 1) | (unsigned)I->isConstant();
976 output_vbr(oSlot);
977
978 // The extension word has this format: bit 0 = has initializer, bit 1-3 =
Chris Lattner404cddf2005-11-12 01:33:40 +0000979 // linkage, bit 4-8 = alignment (log2), bit 9 = has SectionID,
980 // bits 10+ = future use.
Jeff Cohenba0ffcc2005-11-12 01:01:50 +0000981 unsigned ExtWord = (unsigned)I->hasInitializer() |
982 (getEncodedLinkage(I) << 1) |
Chris Lattner404cddf2005-11-12 01:33:40 +0000983 ((Log2_32(I->getAlignment())+1) << 4) |
984 ((unsigned)I->hasSection() << 9);
Chris Lattner8eb52dd2005-11-06 07:11:04 +0000985 output_vbr(ExtWord);
Chris Lattner404cddf2005-11-12 01:33:40 +0000986 if (I->hasSection()) {
987 // Give section names unique ID's.
988 unsigned &Entry = SectionID[I->getSection()];
989 if (Entry == 0) {
990 Entry = ++SectionIDCounter;
991 SectionNames.push_back(I->getSection());
992 }
993 output_vbr(Entry);
994 }
Chris Lattner8eb52dd2005-11-06 07:11:04 +0000995 }
Chris Lattnerd70684f2001-09-18 04:01:05 +0000996
Chris Lattner1b98c5c2001-10-13 06:48:38 +0000997 // If we have an initializer, output it now.
Chris Lattner0b12b5f2002-06-25 16:13:21 +0000998 if (I->hasInitializer()) {
Alkis Evlogimenos60596382003-10-17 02:02:40 +0000999 Slot = Table.getSlot((Value*)I->getInitializer());
Chris Lattnerd70684f2001-09-18 04:01:05 +00001000 assert(Slot != -1 && "No slot for global var initializer!");
Reid Spencerad89bd62004-07-25 18:07:36 +00001001 output_vbr((unsigned)Slot);
Chris Lattnerd70684f2001-09-18 04:01:05 +00001002 }
Chris Lattner70cc3392001-09-10 07:58:01 +00001003 }
Reid Spencerad89bd62004-07-25 18:07:36 +00001004 output_typeid((unsigned)Table.getSlot(Type::VoidTy));
Chris Lattner70cc3392001-09-10 07:58:01 +00001005
Chris Lattnera79e7cc2004-10-16 18:18:16 +00001006 // Output the types of the functions in this module.
Chris Lattner7fc9fe32001-06-27 23:41:11 +00001007 for (Module::const_iterator I = M->begin(), End = M->end(); I != End; ++I) {
Alkis Evlogimenos60596382003-10-17 02:02:40 +00001008 int Slot = Table.getSlot(I->getType());
Chris Lattnera79e7cc2004-10-16 18:18:16 +00001009 assert(Slot != -1 && "Module slot calculator is broken!");
Chris Lattner00950542001-06-06 20:29:01 +00001010 assert(Slot >= Type::FirstDerivedTyID && "Derived type not in range!");
Chris Lattnere73bd452005-11-06 07:43:39 +00001011 assert(((Slot << 6) >> 6) == Slot && "Slot # too big!");
Chris Lattner54b369e2005-11-06 07:46:13 +00001012 unsigned CC = I->getCallingConv()+1;
1013 unsigned ID = (Slot << 5) | (CC & 15);
Chris Lattner479ffeb2005-05-06 20:42:57 +00001014
Chris Lattnerd6e431f2004-11-15 22:39:49 +00001015 if (I->isExternal()) // If external, we don't have an FunctionInfo block.
1016 ID |= 1 << 4;
Chris Lattnere73bd452005-11-06 07:43:39 +00001017
Anton Korobeynikovb74ed072006-09-14 18:23:27 +00001018 if (I->getAlignment() || I->hasSection() || (CC & ~15) != 0 ||
1019 (I->isExternal() && I->hasDLLImportLinkage()) ||
1020 (I->isExternal() && I->hasExternalWeakLinkage())
1021 )
Chris Lattnere73bd452005-11-06 07:43:39 +00001022 ID |= 1 << 31; // Do we need an extension word?
1023
Chris Lattnera79e7cc2004-10-16 18:18:16 +00001024 output_vbr(ID);
Chris Lattnere73bd452005-11-06 07:43:39 +00001025
1026 if (ID & (1 << 31)) {
1027 // Extension byte: bits 0-4 = alignment, bits 5-9 = top nibble of calling
Anton Korobeynikovb74ed072006-09-14 18:23:27 +00001028 // convention, bit 10 = hasSectionID., bits 11-12 = external linkage type
1029 unsigned extLinkage = 0;
1030
1031 if (I->isExternal()) {
1032 if (I->hasDLLImportLinkage()) {
1033 extLinkage = 1;
1034 } else if (I->hasExternalWeakLinkage()) {
1035 extLinkage = 2;
1036 }
1037 }
1038
Chris Lattner404cddf2005-11-12 01:33:40 +00001039 ID = (Log2_32(I->getAlignment())+1) | ((CC >> 4) << 5) |
Anton Korobeynikovb74ed072006-09-14 18:23:27 +00001040 (I->hasSection() << 10) |
1041 ((extLinkage & 3) << 11);
Chris Lattnere73bd452005-11-06 07:43:39 +00001042 output_vbr(ID);
Chris Lattner404cddf2005-11-12 01:33:40 +00001043
1044 // Give section names unique ID's.
1045 if (I->hasSection()) {
1046 unsigned &Entry = SectionID[I->getSection()];
1047 if (Entry == 0) {
1048 Entry = ++SectionIDCounter;
1049 SectionNames.push_back(I->getSection());
1050 }
1051 output_vbr(Entry);
1052 }
Chris Lattnere73bd452005-11-06 07:43:39 +00001053 }
Chris Lattner00950542001-06-06 20:29:01 +00001054 }
Chris Lattnera79e7cc2004-10-16 18:18:16 +00001055 output_vbr((unsigned)Table.getSlot(Type::VoidTy) << 5);
Reid Spencerad89bd62004-07-25 18:07:36 +00001056
Chris Lattnera79e7cc2004-10-16 18:18:16 +00001057 // Emit the list of dependent libraries for the Module.
Reid Spencer5ac88122004-07-25 21:32:02 +00001058 Module::lib_iterator LI = M->lib_begin();
1059 Module::lib_iterator LE = M->lib_end();
Chris Lattnera79e7cc2004-10-16 18:18:16 +00001060 output_vbr(unsigned(LE - LI)); // Emit the number of dependent libraries.
1061 for (; LI != LE; ++LI)
Reid Spencer38d54be2004-08-17 07:45:14 +00001062 output(*LI);
Reid Spencerad89bd62004-07-25 18:07:36 +00001063
1064 // Output the target triple from the module
Reid Spencer38d54be2004-08-17 07:45:14 +00001065 output(M->getTargetTriple());
Chris Lattner404cddf2005-11-12 01:33:40 +00001066
1067 // Emit the table of section names.
1068 output_vbr((unsigned)SectionNames.size());
1069 for (unsigned i = 0, e = SectionNames.size(); i != e; ++i)
1070 output(SectionNames[i]);
Chris Lattner7e6db762006-01-23 23:43:17 +00001071
1072 // Output the inline asm string.
Chris Lattner66316012006-01-24 04:14:29 +00001073 output(M->getModuleInlineAsm());
Chris Lattner00950542001-06-06 20:29:01 +00001074}
1075
Chris Lattnercf3e67f2004-01-18 21:08:52 +00001076void BytecodeWriter::outputInstructions(const Function *F) {
Reid Spencerad89bd62004-07-25 18:07:36 +00001077 BytecodeBlock ILBlock(BytecodeFormat::InstructionListBlockID, *this);
Chris Lattnercf3e67f2004-01-18 21:08:52 +00001078 for (Function::const_iterator BB = F->begin(), E = F->end(); BB != E; ++BB)
1079 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I!=E; ++I)
1080 outputInstruction(*I);
Chris Lattnercf3e67f2004-01-18 21:08:52 +00001081}
1082
Chris Lattner186a1f72003-03-19 20:56:46 +00001083void BytecodeWriter::outputFunction(const Function *F) {
Chris Lattnerfd7f8fe2004-11-15 21:56:33 +00001084 // If this is an external function, there is nothing else to emit!
1085 if (F->isExternal()) return;
1086
Chris Lattnerd6e431f2004-11-15 22:39:49 +00001087 BytecodeBlock FunctionBlock(BytecodeFormat::FunctionBlockID, *this);
1088 output_vbr(getEncodedLinkage(F));
1089
Chris Lattnercf3e67f2004-01-18 21:08:52 +00001090 // Get slot information about the function...
1091 Table.incorporateFunction(F);
1092
1093 if (Table.getCompactionTable().empty()) {
1094 // Output information about the constants in the function if the compaction
1095 // table is not being used.
Chris Lattnere8fdde12001-09-07 16:39:41 +00001096 outputConstants(true);
Chris Lattnercf3e67f2004-01-18 21:08:52 +00001097 } else {
1098 // Otherwise, emit the compaction table.
1099 outputCompactionTable();
Chris Lattnere8fdde12001-09-07 16:39:41 +00001100 }
Misha Brukman23c6d2c2005-04-21 21:48:46 +00001101
Chris Lattnercf3e67f2004-01-18 21:08:52 +00001102 // Output all of the instructions in the body of the function
1103 outputInstructions(F);
Misha Brukman23c6d2c2005-04-21 21:48:46 +00001104
Chris Lattnercf3e67f2004-01-18 21:08:52 +00001105 // If needed, output the symbol table for the function...
1106 outputSymbolTable(F->getSymbolTable());
Misha Brukman23c6d2c2005-04-21 21:48:46 +00001107
Chris Lattnercf3e67f2004-01-18 21:08:52 +00001108 Table.purgeFunction();
1109}
1110
1111void BytecodeWriter::outputCompactionTablePlane(unsigned PlaneNo,
1112 const std::vector<const Value*> &Plane,
1113 unsigned StartNo) {
1114 unsigned End = Table.getModuleLevel(PlaneNo);
Chris Lattner52f86d62004-01-20 00:54:06 +00001115 if (Plane.empty() || StartNo == End || End == 0) return; // Nothing to emit
Chris Lattnercf3e67f2004-01-18 21:08:52 +00001116 assert(StartNo < End && "Cannot emit negative range!");
1117 assert(StartNo < Plane.size() && End <= Plane.size());
1118
Chris Lattnercf3e67f2004-01-18 21:08:52 +00001119 // Do not emit the null initializer!
Reid Spencercb3595c2004-07-04 11:45:47 +00001120 ++StartNo;
Chris Lattnercf3e67f2004-01-18 21:08:52 +00001121
Chris Lattner24102432004-01-18 22:35:34 +00001122 // Figure out which encoding to use. By far the most common case we have is
1123 // to emit 0-2 entries in a compaction table plane.
1124 switch (End-StartNo) {
1125 case 0: // Avoid emitting two vbr's if possible.
1126 case 1:
1127 case 2:
Reid Spencerad89bd62004-07-25 18:07:36 +00001128 output_vbr((PlaneNo << 2) | End-StartNo);
Chris Lattner24102432004-01-18 22:35:34 +00001129 break;
1130 default:
1131 // Output the number of things.
Reid Spencerad89bd62004-07-25 18:07:36 +00001132 output_vbr((unsigned(End-StartNo) << 2) | 3);
1133 output_typeid(PlaneNo); // Emit the type plane this is
Chris Lattner24102432004-01-18 22:35:34 +00001134 break;
1135 }
1136
Chris Lattnercf3e67f2004-01-18 21:08:52 +00001137 for (unsigned i = StartNo; i != End; ++i)
Reid Spencerad89bd62004-07-25 18:07:36 +00001138 output_vbr(Table.getGlobalSlot(Plane[i]));
Chris Lattnercf3e67f2004-01-18 21:08:52 +00001139}
1140
Reid Spencercb3595c2004-07-04 11:45:47 +00001141void BytecodeWriter::outputCompactionTypes(unsigned StartNo) {
1142 // Get the compaction type table from the slot calculator
1143 const std::vector<const Type*> &CTypes = Table.getCompactionTypes();
1144
1145 // The compaction types may have been uncompactified back to the
1146 // global types. If so, we just write an empty table
Chris Lattnerc847f7c2006-07-28 22:07:54 +00001147 if (CTypes.size() == 0) {
Reid Spencerad89bd62004-07-25 18:07:36 +00001148 output_vbr(0U);
Reid Spencercb3595c2004-07-04 11:45:47 +00001149 return;
1150 }
1151
1152 assert(CTypes.size() >= StartNo && "Invalid compaction types start index");
1153
1154 // Determine how many types to write
1155 unsigned NumTypes = CTypes.size() - StartNo;
1156
1157 // Output the number of types.
Reid Spencerad89bd62004-07-25 18:07:36 +00001158 output_vbr(NumTypes);
Reid Spencercb3595c2004-07-04 11:45:47 +00001159
1160 for (unsigned i = StartNo; i < StartNo+NumTypes; ++i)
Reid Spencerad89bd62004-07-25 18:07:36 +00001161 output_typeid(Table.getGlobalSlot(CTypes[i]));
Reid Spencercb3595c2004-07-04 11:45:47 +00001162}
1163
Chris Lattnercf3e67f2004-01-18 21:08:52 +00001164void BytecodeWriter::outputCompactionTable() {
Reid Spencer0033c182004-08-27 00:38:44 +00001165 // Avoid writing the compaction table at all if there is no content.
1166 if (Table.getCompactionTypes().size() >= Type::FirstDerivedTyID ||
1167 (!Table.CompactionTableIsEmpty())) {
Misha Brukman23c6d2c2005-04-21 21:48:46 +00001168 BytecodeBlock CTB(BytecodeFormat::CompactionTableBlockID, *this,
Reid Spencer0033c182004-08-27 00:38:44 +00001169 true/*ElideIfEmpty*/);
Chris Lattnerf9d71782004-10-14 01:46:07 +00001170 const std::vector<std::vector<const Value*> > &CT =
1171 Table.getCompactionTable();
Misha Brukman23c6d2c2005-04-21 21:48:46 +00001172
Reid Spencer0033c182004-08-27 00:38:44 +00001173 // First things first, emit the type compaction table if there is one.
1174 outputCompactionTypes(Type::FirstDerivedTyID);
Chris Lattnercf3e67f2004-01-18 21:08:52 +00001175
Reid Spencer0033c182004-08-27 00:38:44 +00001176 for (unsigned i = 0, e = CT.size(); i != e; ++i)
1177 outputCompactionTablePlane(i, CT[i], 0);
1178 }
Chris Lattner00950542001-06-06 20:29:01 +00001179}
1180
Chris Lattner00950542001-06-06 20:29:01 +00001181void BytecodeWriter::outputSymbolTable(const SymbolTable &MST) {
Chris Lattner737d3cd2004-01-10 19:56:59 +00001182 // Do not output the Bytecode block for an empty symbol table, it just wastes
1183 // space!
Chris Lattnerf9d71782004-10-14 01:46:07 +00001184 if (MST.isEmpty()) return;
Chris Lattner737d3cd2004-01-10 19:56:59 +00001185
Reid Spencerad89bd62004-07-25 18:07:36 +00001186 BytecodeBlock SymTabBlock(BytecodeFormat::SymbolTableBlockID, *this,
Chris Lattnerf9d71782004-10-14 01:46:07 +00001187 true/*ElideIfEmpty*/);
Chris Lattner00950542001-06-06 20:29:01 +00001188
Misha Brukman23c6d2c2005-04-21 21:48:46 +00001189 // Write the number of types
Reid Spencerad89bd62004-07-25 18:07:36 +00001190 output_vbr(MST.num_types());
Reid Spencer250c4182004-08-17 02:59:02 +00001191
1192 // Write each of the types
Reid Spencer94f2df22004-05-25 17:29:59 +00001193 for (SymbolTable::type_const_iterator TI = MST.type_begin(),
Chris Lattnerc847f7c2006-07-28 22:07:54 +00001194 TE = MST.type_end(); TI != TE; ++TI) {
Reid Spencer250c4182004-08-17 02:59:02 +00001195 // Symtab entry:[def slot #][name]
Reid Spencerad89bd62004-07-25 18:07:36 +00001196 output_typeid((unsigned)Table.getSlot(TI->second));
Misha Brukman23c6d2c2005-04-21 21:48:46 +00001197 output(TI->first);
Reid Spencer94f2df22004-05-25 17:29:59 +00001198 }
1199
1200 // Now do each of the type planes in order.
Misha Brukman23c6d2c2005-04-21 21:48:46 +00001201 for (SymbolTable::plane_const_iterator PI = MST.plane_begin(),
Reid Spencer94f2df22004-05-25 17:29:59 +00001202 PE = MST.plane_end(); PI != PE; ++PI) {
1203 SymbolTable::value_const_iterator I = MST.value_begin(PI->first);
1204 SymbolTable::value_const_iterator End = MST.value_end(PI->first);
Chris Lattner00950542001-06-06 20:29:01 +00001205 int Slot;
Misha Brukman23c6d2c2005-04-21 21:48:46 +00001206
Chris Lattner00950542001-06-06 20:29:01 +00001207 if (I == End) continue; // Don't mess with an absent type...
1208
Reid Spencer250c4182004-08-17 02:59:02 +00001209 // Write the number of values in this plane
Chris Lattner001d16a2005-03-07 02:59:36 +00001210 output_vbr((unsigned)PI->second.size());
Chris Lattner00950542001-06-06 20:29:01 +00001211
Reid Spencer250c4182004-08-17 02:59:02 +00001212 // Write the slot number of the type for this plane
Reid Spencer94f2df22004-05-25 17:29:59 +00001213 Slot = Table.getSlot(PI->first);
Chris Lattner00950542001-06-06 20:29:01 +00001214 assert(Slot != -1 && "Type in symtab, but not in table!");
Reid Spencerad89bd62004-07-25 18:07:36 +00001215 output_typeid((unsigned)Slot);
Chris Lattner00950542001-06-06 20:29:01 +00001216
Reid Spencer250c4182004-08-17 02:59:02 +00001217 // Write each of the values in this plane
Chris Lattner7fc9fe32001-06-27 23:41:11 +00001218 for (; I != End; ++I) {
Chris Lattner00950542001-06-06 20:29:01 +00001219 // Symtab entry: [def slot #][name]
Alkis Evlogimenos60596382003-10-17 02:02:40 +00001220 Slot = Table.getSlot(I->second);
Chris Lattnere8fdde12001-09-07 16:39:41 +00001221 assert(Slot != -1 && "Value in symtab but has no slot number!!");
Reid Spencerad89bd62004-07-25 18:07:36 +00001222 output_vbr((unsigned)Slot);
Reid Spencer38d54be2004-08-17 07:45:14 +00001223 output(I->first);
Chris Lattner00950542001-06-06 20:29:01 +00001224 }
1225 }
1226}
1227
Reid Spencer17f52c52004-11-06 23:17:23 +00001228void llvm::WriteBytecodeToFile(const Module *M, std::ostream &Out,
Chris Lattnerc847f7c2006-07-28 22:07:54 +00001229 bool compress) {
Reid Spencerad89bd62004-07-25 18:07:36 +00001230 assert(M && "You can't write a null module!!");
Chris Lattner00950542001-06-06 20:29:01 +00001231
Reid Spencer32f55532006-06-07 23:18:34 +00001232 // Make sure that std::cout is put into binary mode for systems
1233 // that care.
1234 if (&Out == std::cout)
1235 sys::Program::ChangeStdoutToBinary();
1236
Reid Spencer17f52c52004-11-06 23:17:23 +00001237 // Create a vector of unsigned char for the bytecode output. We
1238 // reserve 256KBytes of space in the vector so that we avoid doing
1239 // lots of little allocations. 256KBytes is sufficient for a large
1240 // proportion of the bytecode files we will encounter. Larger files
1241 // will be automatically doubled in size as needed (std::vector
1242 // behavior).
Reid Spencerad89bd62004-07-25 18:07:36 +00001243 std::vector<unsigned char> Buffer;
Reid Spencer17f52c52004-11-06 23:17:23 +00001244 Buffer.reserve(256 * 1024);
Chris Lattner00950542001-06-06 20:29:01 +00001245
Reid Spencer17f52c52004-11-06 23:17:23 +00001246 // The BytecodeWriter populates Buffer for us.
Reid Spencerad89bd62004-07-25 18:07:36 +00001247 BytecodeWriter BCW(Buffer, M);
Chris Lattner00950542001-06-06 20:29:01 +00001248
Reid Spencer17f52c52004-11-06 23:17:23 +00001249 // Keep track of how much we've written
Chris Lattnerce6ef112002-07-26 18:40:14 +00001250 BytesWritten += Buffer.size();
1251
Reid Spencer17f52c52004-11-06 23:17:23 +00001252 // Determine start and end points of the Buffer
Reid Spencer83296f52004-11-07 18:17:38 +00001253 const unsigned char *FirstByte = &Buffer.front();
Reid Spencer17f52c52004-11-06 23:17:23 +00001254
1255 // If we're supposed to compress this mess ...
1256 if (compress) {
1257
1258 // We signal compression by using an alternate magic number for the
Reid Spencer83296f52004-11-07 18:17:38 +00001259 // file. The compressed bytecode file's magic number is "llvc" instead
Misha Brukman23c6d2c2005-04-21 21:48:46 +00001260 // of "llvm".
Reid Spencer83296f52004-11-07 18:17:38 +00001261 char compressed_magic[4];
1262 compressed_magic[0] = 'l';
1263 compressed_magic[1] = 'l';
1264 compressed_magic[2] = 'v';
1265 compressed_magic[3] = 'c';
Reid Spencer17f52c52004-11-06 23:17:23 +00001266
Reid Spencer83296f52004-11-07 18:17:38 +00001267 Out.write(compressed_magic,4);
Reid Spencer17f52c52004-11-06 23:17:23 +00001268
Reid Spencera70d84d2004-11-14 22:01:41 +00001269 // Compress everything after the magic number (which we altered)
Reid Spencer3ed469c2006-11-02 20:25:50 +00001270 Compressor::compressToStream(
Reid Spencer17f52c52004-11-06 23:17:23 +00001271 (char*)(FirstByte+4), // Skip the magic number
1272 Buffer.size()-4, // Skip the magic number
Reid Spencer84472d62004-11-25 19:38:05 +00001273 Out // Where to write compressed data
Reid Spencer17f52c52004-11-06 23:17:23 +00001274 );
1275
Reid Spencer17f52c52004-11-06 23:17:23 +00001276 } else {
1277
1278 // We're not compressing, so just write the entire block.
Reid Spencer83296f52004-11-07 18:17:38 +00001279 Out.write((char*)FirstByte, Buffer.size());
Chris Lattnere8fdde12001-09-07 16:39:41 +00001280 }
Reid Spencer17f52c52004-11-06 23:17:23 +00001281
1282 // make sure it hits disk now
Chris Lattner00950542001-06-06 20:29:01 +00001283 Out.flush();
1284}