blob: ea5159b28fe87416b69eb0bd8900141e604a66ec [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
Reid Spencer91ac04a2007-04-09 06:14:31 +000020#define DEBUG_TYPE "bcwriter"
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"
Reid Spencer91ac04a2007-04-09 06:14:31 +000026#include "llvm/ParameterAttributes.h"
Chris Lattner3bc5a602006-01-25 23:08:15 +000027#include "llvm/InlineAsm.h"
Reid Spencerad89bd62004-07-25 18:07:36 +000028#include "llvm/Instructions.h"
Chris Lattner00950542001-06-06 20:29:01 +000029#include "llvm/Module.h"
Reid Spencer78d033e2007-01-06 07:24:44 +000030#include "llvm/TypeSymbolTable.h"
Reid Spenceref9b9a72007-02-05 20:47:22 +000031#include "llvm/ValueSymbolTable.h"
Reid Spencerad89bd62004-07-25 18:07:36 +000032#include "llvm/Support/GetElementPtrTypeIterator.h"
Reid Spencer17f52c52004-11-06 23:17:23 +000033#include "llvm/Support/Compressor.h"
Jim Laskeycb6682f2005-08-17 19:34:49 +000034#include "llvm/Support/MathExtras.h"
Bill Wendling68fe61d2006-11-29 00:19:40 +000035#include "llvm/Support/Streams.h"
Reid Spencer32f55532006-06-07 23:18:34 +000036#include "llvm/System/Program.h"
Chris Lattnerae052aa2007-02-10 07:31:44 +000037#include "llvm/ADT/SmallVector.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000038#include "llvm/ADT/STLExtras.h"
39#include "llvm/ADT/Statistic.h"
Chris Lattner32abce62004-01-10 19:10:01 +000040#include <cstring>
Chris Lattner00950542001-06-06 20:29:01 +000041#include <algorithm>
Chris Lattner44f549b2004-01-10 18:49:43 +000042using namespace llvm;
Brian Gaeked0fde302003-11-11 22:41:34 +000043
Reid Spencer38d54be2004-08-17 07:45:14 +000044/// This value needs to be incremented every time the bytecode format changes
45/// so that the reader can distinguish which format of the bytecode file has
46/// been written.
47/// @brief The bytecode version number
Reid Spencer6996feb2006-11-08 21:27:54 +000048const unsigned BCVersionNum = 7;
Reid Spencer38d54be2004-08-17 07:45:14 +000049
Devang Patel19974732007-05-03 01:11:54 +000050char WriteBytecodePass::ID = 0;
Chris Lattner635cd932002-07-23 19:56:44 +000051static RegisterPass<WriteBytecodePass> X("emitbytecode", "Bytecode Writer");
52
Chris Lattner1c560ad2006-12-19 23:16:47 +000053STATISTIC(BytesWritten, "Number of bytecode bytes written");
Chris Lattner635cd932002-07-23 19:56:44 +000054
Reid Spencerad89bd62004-07-25 18:07:36 +000055//===----------------------------------------------------------------------===//
56//=== Output Primitives ===//
57//===----------------------------------------------------------------------===//
58
59// output - If a position is specified, it must be in the valid portion of the
Misha Brukman23c6d2c2005-04-21 21:48:46 +000060// string... note that this should be inlined always so only the relevant IF
Reid Spencerad89bd62004-07-25 18:07:36 +000061// body should be included.
62inline void BytecodeWriter::output(unsigned i, int pos) {
63 if (pos == -1) { // Be endian clean, little endian is our friend
Misha Brukman23c6d2c2005-04-21 21:48:46 +000064 Out.push_back((unsigned char)i);
Reid Spencerad89bd62004-07-25 18:07:36 +000065 Out.push_back((unsigned char)(i >> 8));
66 Out.push_back((unsigned char)(i >> 16));
67 Out.push_back((unsigned char)(i >> 24));
68 } else {
69 Out[pos ] = (unsigned char)i;
70 Out[pos+1] = (unsigned char)(i >> 8);
71 Out[pos+2] = (unsigned char)(i >> 16);
72 Out[pos+3] = (unsigned char)(i >> 24);
73 }
74}
75
Reid Spencer7d003412007-02-09 18:03:35 +000076inline void BytecodeWriter::output(int32_t i) {
77 output((uint32_t)i);
Reid Spencerad89bd62004-07-25 18:07:36 +000078}
79
80/// output_vbr - Output an unsigned value, by using the least number of bytes
81/// possible. This is useful because many of our "infinite" values are really
82/// very small most of the time; but can be large a few times.
Misha Brukman23c6d2c2005-04-21 21:48:46 +000083/// Data format used: If you read a byte with the high bit set, use the low
84/// seven bits as data and then read another byte.
Reid Spencerad89bd62004-07-25 18:07:36 +000085inline void BytecodeWriter::output_vbr(uint64_t i) {
86 while (1) {
87 if (i < 0x80) { // done?
88 Out.push_back((unsigned char)i); // We know the high bit is clear...
89 return;
90 }
Misha Brukman23c6d2c2005-04-21 21:48:46 +000091
Reid Spencerad89bd62004-07-25 18:07:36 +000092 // Nope, we are bigger than a character, output the next 7 bits and set the
93 // high bit to say that there is more coming...
94 Out.push_back(0x80 | ((unsigned char)i & 0x7F));
95 i >>= 7; // Shift out 7 bits now...
96 }
97}
98
Reid Spencer7d003412007-02-09 18:03:35 +000099inline void BytecodeWriter::output_vbr(uint32_t i) {
Reid Spencerad89bd62004-07-25 18:07:36 +0000100 while (1) {
101 if (i < 0x80) { // done?
102 Out.push_back((unsigned char)i); // We know the high bit is clear...
103 return;
104 }
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000105
Reid Spencerad89bd62004-07-25 18:07:36 +0000106 // Nope, we are bigger than a character, output the next 7 bits and set the
107 // high bit to say that there is more coming...
108 Out.push_back(0x80 | ((unsigned char)i & 0x7F));
109 i >>= 7; // Shift out 7 bits now...
110 }
111}
112
113inline void BytecodeWriter::output_typeid(unsigned i) {
114 if (i <= 0x00FFFFFF)
115 this->output_vbr(i);
116 else {
117 this->output_vbr(0x00FFFFFF);
118 this->output_vbr(i);
119 }
120}
121
122inline void BytecodeWriter::output_vbr(int64_t i) {
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000123 if (i < 0)
Reid Spencerad89bd62004-07-25 18:07:36 +0000124 output_vbr(((uint64_t)(-i) << 1) | 1); // Set low order sign bit...
125 else
126 output_vbr((uint64_t)i << 1); // Low order bit is clear.
127}
128
129
130inline void BytecodeWriter::output_vbr(int i) {
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000131 if (i < 0)
Reid Spencerad89bd62004-07-25 18:07:36 +0000132 output_vbr(((unsigned)(-i) << 1) | 1); // Set low order sign bit...
133 else
134 output_vbr((unsigned)i << 1); // Low order bit is clear.
135}
136
Chris Lattnerdec628e2007-02-12 05:18:08 +0000137inline void BytecodeWriter::output_str(const char *Str, unsigned Len) {
Chris Lattnerc847f7c2006-07-28 22:07:54 +0000138 output_vbr(Len); // Strings may have an arbitrary length.
Chris Lattnerdec628e2007-02-12 05:18:08 +0000139 Out.insert(Out.end(), Str, Str+Len);
Reid Spencerad89bd62004-07-25 18:07:36 +0000140}
141
142inline void BytecodeWriter::output_data(const void *Ptr, const void *End) {
143 Out.insert(Out.end(), (const unsigned char*)Ptr, (const unsigned char*)End);
144}
145
146inline void BytecodeWriter::output_float(float& FloatVal) {
147 /// FIXME: This isn't optimal, it has size problems on some platforms
148 /// where FP is not IEEE.
Jim Laskeycb6682f2005-08-17 19:34:49 +0000149 uint32_t i = FloatToBits(FloatVal);
Chris Lattnerc847f7c2006-07-28 22:07:54 +0000150 Out.push_back( static_cast<unsigned char>( (i ) & 0xFF));
151 Out.push_back( static_cast<unsigned char>( (i >> 8 ) & 0xFF));
Jim Laskeycb6682f2005-08-17 19:34:49 +0000152 Out.push_back( static_cast<unsigned char>( (i >> 16) & 0xFF));
153 Out.push_back( static_cast<unsigned char>( (i >> 24) & 0xFF));
Reid Spencerad89bd62004-07-25 18:07:36 +0000154}
155
156inline void BytecodeWriter::output_double(double& DoubleVal) {
157 /// FIXME: This isn't optimal, it has size problems on some platforms
158 /// where FP is not IEEE.
Jim Laskeycb6682f2005-08-17 19:34:49 +0000159 uint64_t i = DoubleToBits(DoubleVal);
Chris Lattnerc847f7c2006-07-28 22:07:54 +0000160 Out.push_back( static_cast<unsigned char>( (i ) & 0xFF));
161 Out.push_back( static_cast<unsigned char>( (i >> 8 ) & 0xFF));
Jim Laskeycb6682f2005-08-17 19:34:49 +0000162 Out.push_back( static_cast<unsigned char>( (i >> 16) & 0xFF));
163 Out.push_back( static_cast<unsigned char>( (i >> 24) & 0xFF));
164 Out.push_back( static_cast<unsigned char>( (i >> 32) & 0xFF));
165 Out.push_back( static_cast<unsigned char>( (i >> 40) & 0xFF));
166 Out.push_back( static_cast<unsigned char>( (i >> 48) & 0xFF));
167 Out.push_back( static_cast<unsigned char>( (i >> 56) & 0xFF));
Reid Spencerad89bd62004-07-25 18:07:36 +0000168}
169
Chris Lattnerc76ea432005-11-12 18:34:09 +0000170inline BytecodeBlock::BytecodeBlock(unsigned ID, BytecodeWriter &w,
171 bool elideIfEmpty, bool hasLongFormat)
Reid Spencerad89bd62004-07-25 18:07:36 +0000172 : Id(ID), Writer(w), ElideIfEmpty(elideIfEmpty), HasLongFormat(hasLongFormat){
173
174 if (HasLongFormat) {
175 w.output(ID);
176 w.output(0U); // For length in long format
177 } else {
178 w.output(0U); /// Place holder for ID and length for this block
179 }
180 Loc = w.size();
181}
182
Chris Lattnerb0bf6642004-10-14 01:35:17 +0000183inline BytecodeBlock::~BytecodeBlock() { // Do backpatch when block goes out
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000184 // of scope...
Reid Spencerad89bd62004-07-25 18:07:36 +0000185 if (Loc == Writer.size() && ElideIfEmpty) {
186 // If the block is empty, and we are allowed to, do not emit the block at
187 // all!
188 Writer.resize(Writer.size()-(HasLongFormat?8:4));
189 return;
190 }
191
Reid Spencerad89bd62004-07-25 18:07:36 +0000192 if (HasLongFormat)
193 Writer.output(unsigned(Writer.size()-Loc), int(Loc-4));
194 else
195 Writer.output(unsigned(Writer.size()-Loc) << 5 | (Id & 0x1F), int(Loc-4));
Reid Spencerad89bd62004-07-25 18:07:36 +0000196}
197
198//===----------------------------------------------------------------------===//
199//=== Constant Output ===//
200//===----------------------------------------------------------------------===//
201
Reid Spencer91ac04a2007-04-09 06:14:31 +0000202void BytecodeWriter::outputParamAttrsList(const ParamAttrsList *Attrs) {
203 if (!Attrs) {
204 output_vbr(unsigned(0));
205 return;
206 }
207 unsigned numAttrs = Attrs->size();
208 output_vbr(numAttrs);
209 for (unsigned i = 0; i < numAttrs; ++i) {
210 uint16_t index = Attrs->getParamIndex(i);
211 uint16_t attrs = Attrs->getParamAttrs(index);
212 output_vbr(uint32_t(index));
213 output_vbr(uint32_t(attrs));
214 }
215}
216
Reid Spencerad89bd62004-07-25 18:07:36 +0000217void BytecodeWriter::outputType(const Type *T) {
Andrew Lenharth38ecbf12006-12-08 18:06:16 +0000218 const StructType* STy = dyn_cast<StructType>(T);
219 if(STy && STy->isPacked())
Reid Spencera54b7cb2007-01-12 07:05:14 +0000220 output_vbr((unsigned)Type::PackedStructTyID);
Andrew Lenharth38ecbf12006-12-08 18:06:16 +0000221 else
222 output_vbr((unsigned)T->getTypeID());
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000223
Reid Spencerad89bd62004-07-25 18:07:36 +0000224 // That's all there is to handling primitive types...
Reid Spencera54b7cb2007-01-12 07:05:14 +0000225 if (T->isPrimitiveType())
Reid Spencerad89bd62004-07-25 18:07:36 +0000226 return; // We might do this if we alias a prim type: %x = type int
Reid Spencerad89bd62004-07-25 18:07:36 +0000227
228 switch (T->getTypeID()) { // Handle derived types now.
Reid Spencera54b7cb2007-01-12 07:05:14 +0000229 case Type::IntegerTyID:
230 output_vbr(cast<IntegerType>(T)->getBitWidth());
231 break;
Reid Spencerad89bd62004-07-25 18:07:36 +0000232 case Type::FunctionTyID: {
Reid Spencer91ac04a2007-04-09 06:14:31 +0000233 const FunctionType *FT = cast<FunctionType>(T);
234 output_typeid(Table.getTypeSlot(FT->getReturnType()));
Reid Spencerad89bd62004-07-25 18:07:36 +0000235
236 // Output the number of arguments to function (+1 if varargs):
Reid Spencer91ac04a2007-04-09 06:14:31 +0000237 output_vbr((unsigned)FT->getNumParams()+FT->isVarArg());
Reid Spencerad89bd62004-07-25 18:07:36 +0000238
239 // Output all of the arguments...
Reid Spencer91ac04a2007-04-09 06:14:31 +0000240 FunctionType::param_iterator I = FT->param_begin();
241 for (; I != FT->param_end(); ++I)
Chris Lattner972b4dc2007-02-10 05:17:48 +0000242 output_typeid(Table.getTypeSlot(*I));
Reid Spencerad89bd62004-07-25 18:07:36 +0000243
244 // Terminate list with VoidTy if we are a varargs function...
Reid Spencer91ac04a2007-04-09 06:14:31 +0000245 if (FT->isVarArg())
Reid Spencerad89bd62004-07-25 18:07:36 +0000246 output_typeid((unsigned)Type::VoidTyID);
Reid Spencer91ac04a2007-04-09 06:14:31 +0000247
248 // Put out all the parameter attributes
249 outputParamAttrsList(FT->getParamAttrs());
Reid Spencerad89bd62004-07-25 18:07:36 +0000250 break;
251 }
252
253 case Type::ArrayTyID: {
254 const ArrayType *AT = cast<ArrayType>(T);
Chris Lattner972b4dc2007-02-10 05:17:48 +0000255 output_typeid(Table.getTypeSlot(AT->getElementType()));
Reid Spencerad89bd62004-07-25 18:07:36 +0000256 output_vbr(AT->getNumElements());
257 break;
258 }
259
Reid Spencer9d6565a2007-02-15 02:26:10 +0000260 case Type::VectorTyID: {
261 const VectorType *PT = cast<VectorType>(T);
Chris Lattner972b4dc2007-02-10 05:17:48 +0000262 output_typeid(Table.getTypeSlot(PT->getElementType()));
Brian Gaeke715c90b2004-08-20 06:00:58 +0000263 output_vbr(PT->getNumElements());
264 break;
265 }
266
Reid Spencerad89bd62004-07-25 18:07:36 +0000267 case Type::StructTyID: {
268 const StructType *ST = cast<StructType>(T);
Reid Spencerad89bd62004-07-25 18:07:36 +0000269 // Output all of the element types...
270 for (StructType::element_iterator I = ST->element_begin(),
271 E = ST->element_end(); I != E; ++I) {
Chris Lattner972b4dc2007-02-10 05:17:48 +0000272 output_typeid(Table.getTypeSlot(*I));
Reid Spencerad89bd62004-07-25 18:07:36 +0000273 }
274
275 // Terminate list with VoidTy
276 output_typeid((unsigned)Type::VoidTyID);
277 break;
278 }
279
Chris Lattner972b4dc2007-02-10 05:17:48 +0000280 case Type::PointerTyID:
281 output_typeid(Table.getTypeSlot(cast<PointerType>(T)->getElementType()));
Reid Spencerad89bd62004-07-25 18:07:36 +0000282 break;
Reid Spencerad89bd62004-07-25 18:07:36 +0000283
Chris Lattnerb0bf6642004-10-14 01:35:17 +0000284 case Type::OpaqueTyID:
Reid Spencerad89bd62004-07-25 18:07:36 +0000285 // No need to emit anything, just the count of opaque types is enough.
286 break;
Reid Spencerad89bd62004-07-25 18:07:36 +0000287
Reid Spencerad89bd62004-07-25 18:07:36 +0000288 default:
Bill Wendlinge8156192006-12-07 01:30:32 +0000289 cerr << __FILE__ << ":" << __LINE__ << ": Don't know how to serialize"
290 << " Type '" << T->getDescription() << "'\n";
Reid Spencerad89bd62004-07-25 18:07:36 +0000291 break;
292 }
293}
294
295void BytecodeWriter::outputConstant(const Constant *CPV) {
Chris Lattner42a75512007-01-15 02:27:26 +0000296 assert(((CPV->getType()->isPrimitiveType() || CPV->getType()->isInteger()) ||
Reid Spencera54b7cb2007-01-12 07:05:14 +0000297 !CPV->isNullValue()) && "Shouldn't output null constants!");
Reid Spencerad89bd62004-07-25 18:07:36 +0000298
299 // We must check for a ConstantExpr before switching by type because
300 // a ConstantExpr can be of any type, and has no explicit value.
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000301 //
Reid Spencerad89bd62004-07-25 18:07:36 +0000302 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CPV)) {
303 // FIXME: Encoding of constant exprs could be much more compact!
304 assert(CE->getNumOperands() > 0 && "ConstantExpr with 0 operands");
Reid Spencer3da59db2006-11-27 01:05:10 +0000305 assert(CE->getNumOperands() != 1 || CE->isCast());
Chris Lattnera79e7cc2004-10-16 18:18:16 +0000306 output_vbr(1+CE->getNumOperands()); // flags as an expr
Reid Spencerb83eb642006-10-20 07:07:24 +0000307 output_vbr(CE->getOpcode()); // Put out the CE op code
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000308
Reid Spencerad89bd62004-07-25 18:07:36 +0000309 for (User::const_op_iterator OI = CE->op_begin(); OI != CE->op_end(); ++OI){
Chris Lattner972b4dc2007-02-10 05:17:48 +0000310 output_vbr(Table.getSlot(*OI));
311 output_typeid(Table.getTypeSlot((*OI)->getType()));
Reid Spencerad89bd62004-07-25 18:07:36 +0000312 }
Reid Spencer595b4772006-12-04 05:23:49 +0000313 if (CE->isCompare())
314 output_vbr((unsigned)CE->getPredicate());
Reid Spencerad89bd62004-07-25 18:07:36 +0000315 return;
Chris Lattnera79e7cc2004-10-16 18:18:16 +0000316 } else if (isa<UndefValue>(CPV)) {
317 output_vbr(1U); // 1 -> UndefValue constant.
318 return;
Reid Spencerad89bd62004-07-25 18:07:36 +0000319 } else {
Reid Spencerb83eb642006-10-20 07:07:24 +0000320 output_vbr(0U); // flag as not a ConstantExpr (i.e. 0 operands)
Reid Spencerad89bd62004-07-25 18:07:36 +0000321 }
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000322
Reid Spencerad89bd62004-07-25 18:07:36 +0000323 switch (CPV->getType()->getTypeID()) {
Reid Spencera54b7cb2007-01-12 07:05:14 +0000324 case Type::IntegerTyID: { // Integer types...
Reid Spencer9abd1382007-02-28 02:25:20 +0000325 const ConstantInt *CI = cast<ConstantInt>(CPV);
Reid Spencera54b7cb2007-01-12 07:05:14 +0000326 unsigned NumBits = cast<IntegerType>(CPV->getType())->getBitWidth();
Chris Lattnerfb939312007-01-12 23:26:17 +0000327 if (NumBits <= 32)
Reid Spencer9abd1382007-02-28 02:25:20 +0000328 output_vbr(uint32_t(CI->getZExtValue()));
Reid Spencera54b7cb2007-01-12 07:05:14 +0000329 else if (NumBits <= 64)
Reid Spencer9abd1382007-02-28 02:25:20 +0000330 output_vbr(uint64_t(CI->getZExtValue()));
331 else {
332 // We have an arbitrary precision integer value to write whose
333 // bit width is > 64. However, in canonical unsigned integer
334 // format it is likely that the high bits are going to be zero.
335 // So, we only write the number of active words.
336 uint32_t activeWords = CI->getValue().getActiveWords();
337 const uint64_t *rawData = CI->getValue().getRawData();
338 output_vbr(activeWords);
339 for (uint32_t i = 0; i < activeWords; ++i)
340 output_vbr(rawData[i]);
341 }
Reid Spencerad89bd62004-07-25 18:07:36 +0000342 break;
Reid Spencera54b7cb2007-01-12 07:05:14 +0000343 }
Reid Spencerad89bd62004-07-25 18:07:36 +0000344
Reid Spencerad89bd62004-07-25 18:07:36 +0000345 case Type::ArrayTyID: {
346 const ConstantArray *CPA = cast<ConstantArray>(CPV);
347 assert(!CPA->isString() && "Constant strings should be handled specially!");
348
Chris Lattnera2bdad42007-02-10 05:13:03 +0000349 for (unsigned i = 0, e = CPA->getNumOperands(); i != e; ++i)
350 output_vbr(Table.getSlot(CPA->getOperand(i)));
Reid Spencerad89bd62004-07-25 18:07:36 +0000351 break;
352 }
353
Reid Spencer9d6565a2007-02-15 02:26:10 +0000354 case Type::VectorTyID: {
355 const ConstantVector *CP = cast<ConstantVector>(CPV);
Chris Lattnera2bdad42007-02-10 05:13:03 +0000356 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
357 output_vbr(Table.getSlot(CP->getOperand(i)));
Brian Gaeke715c90b2004-08-20 06:00:58 +0000358 break;
359 }
360
Reid Spencerad89bd62004-07-25 18:07:36 +0000361 case Type::StructTyID: {
362 const ConstantStruct *CPS = cast<ConstantStruct>(CPV);
Reid Spencerad89bd62004-07-25 18:07:36 +0000363
Chris Lattnera2bdad42007-02-10 05:13:03 +0000364 for (unsigned i = 0, e = CPS->getNumOperands(); i != e; ++i)
365 output_vbr(Table.getSlot(CPS->getOperand(i)));
Reid Spencerad89bd62004-07-25 18:07:36 +0000366 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:
Bill Wendlinge8156192006-12-07 01:30:32 +0000387 cerr << __FILE__ << ":" << __LINE__ << ": Don't know how to serialize"
388 << " type '" << *CPV->getType() << "'\n";
Reid Spencerad89bd62004-07-25 18:07:36 +0000389 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;
Chris Lattner972b4dc2007-02-10 05:17:48 +0000420 output_typeid(Table.getTypeSlot(Str->getType()));
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000421
Reid Spencerad89bd62004-07-25 18:07:36 +0000422 // Now that we emitted the type (which indicates the size of the string),
423 // emit all of the characters.
424 std::string Val = Str->getAsString();
425 output_data(Val.c_str(), Val.c_str()+Val.size());
426 }
427}
428
429//===----------------------------------------------------------------------===//
430//=== Instruction Output ===//
431//===----------------------------------------------------------------------===//
Reid Spencerad89bd62004-07-25 18:07:36 +0000432
Chris Lattnerda895d62005-02-27 06:18:25 +0000433// outputInstructionFormat0 - Output those weird instructions that have a large
Chris Lattnerdee199f2005-05-06 22:34:01 +0000434// number of operands or have large operands themselves.
Reid Spencerad89bd62004-07-25 18:07:36 +0000435//
436// Format: [opcode] [type] [numargs] [arg0] [arg1] ... [arg<numargs-1>]
437//
Chris Lattnerf9d71782004-10-14 01:46:07 +0000438void BytecodeWriter::outputInstructionFormat0(const Instruction *I,
439 unsigned Opcode,
440 const SlotCalculator &Table,
441 unsigned Type) {
Reid Spencerad89bd62004-07-25 18:07:36 +0000442 // Opcode must have top two bits clear...
443 output_vbr(Opcode << 2); // Instruction Opcode ID
444 output_typeid(Type); // Result type
445
446 unsigned NumArgs = I->getNumOperands();
Chris Lattner39a6a362007-04-09 03:37:36 +0000447 bool HasExtraArg = false;
448 if (isa<CastInst>(I) || isa<InvokeInst>(I) ||
Christopher Lamb43c7f372007-04-22 19:24:39 +0000449 isa<CmpInst>(I) || isa<VAArgInst>(I) || Opcode == 58 ||
450 Opcode == 62 || Opcode == 63)
Chris Lattner39a6a362007-04-09 03:37:36 +0000451 HasExtraArg = true;
452 if (const AllocationInst *AI = dyn_cast<AllocationInst>(I))
453 HasExtraArg = AI->getAlignment() != 0;
454
455 output_vbr(NumArgs + HasExtraArg);
Reid Spencerad89bd62004-07-25 18:07:36 +0000456
457 if (!isa<GetElementPtrInst>(&I)) {
Chris Lattnera2bdad42007-02-10 05:13:03 +0000458 for (unsigned i = 0; i < NumArgs; ++i)
459 output_vbr(Table.getSlot(I->getOperand(i)));
Reid Spencerad89bd62004-07-25 18:07:36 +0000460
461 if (isa<CastInst>(I) || isa<VAArgInst>(I)) {
Chris Lattner972b4dc2007-02-10 05:17:48 +0000462 output_typeid(Table.getTypeSlot(I->getType()));
Reid Spencercae60532006-12-06 04:27:07 +0000463 } else if (isa<CmpInst>(I)) {
464 output_vbr(unsigned(cast<CmpInst>(I)->getPredicate()));
Reid Spencer3da59db2006-11-27 01:05:10 +0000465 } else if (isa<InvokeInst>(I)) {
Chris Lattnerdee199f2005-05-06 22:34:01 +0000466 output_vbr(cast<InvokeInst>(I)->getCallingConv());
467 } else if (Opcode == 58) { // Call escape sequence
468 output_vbr((cast<CallInst>(I)->getCallingConv() << 1) |
Jeff Cohen39cef602005-05-07 02:44:04 +0000469 unsigned(cast<CallInst>(I)->isTailCall()));
Chris Lattner39a6a362007-04-09 03:37:36 +0000470 } else if (const AllocationInst *AI = dyn_cast<AllocationInst>(I)) {
471 if (AI->getAlignment())
472 output_vbr((unsigned)Log2_32(AI->getAlignment())+1);
Christopher Lamb43c7f372007-04-22 19:24:39 +0000473 } else if (Opcode == 62) { // Attributed load
474 output_vbr((unsigned)(((Log2_32(cast<LoadInst>(I)->getAlignment())+1)<<1)
475 + (cast<LoadInst>(I)->isVolatile() ? 1 : 0)));
476 } else if (Opcode == 63) { // Attributed store
477 output_vbr((unsigned)(((Log2_32(cast<StoreInst>(I)->getAlignment())+1)<<1)
478 + (cast<StoreInst>(I)->isVolatile() ? 1 : 0)));
Reid Spencerad89bd62004-07-25 18:07:36 +0000479 }
Reid Spencerad89bd62004-07-25 18:07:36 +0000480 } else {
Chris Lattnera2bdad42007-02-10 05:13:03 +0000481 output_vbr(Table.getSlot(I->getOperand(0)));
Reid Spencerad89bd62004-07-25 18:07:36 +0000482
483 // We need to encode the type of sequential type indices into their slot #
484 unsigned Idx = 1;
485 for (gep_type_iterator TI = gep_type_begin(I), E = gep_type_end(I);
486 Idx != NumArgs; ++TI, ++Idx) {
Chris Lattnera2bdad42007-02-10 05:13:03 +0000487 unsigned Slot = Table.getSlot(I->getOperand(Idx));
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000488
Reid Spencerad89bd62004-07-25 18:07:36 +0000489 if (isa<SequentialType>(*TI)) {
Reid Spencera54b7cb2007-01-12 07:05:14 +0000490 // These should be either 32-bits or 64-bits, however, with bit
491 // accurate types we just distinguish between less than or equal to
492 // 32-bits or greater than 32-bits.
Reid Spencer790366b2007-01-13 00:10:02 +0000493 unsigned BitWidth =
494 cast<IntegerType>(I->getOperand(Idx)->getType())->getBitWidth();
495 assert(BitWidth == 32 || BitWidth == 64 &&
496 "Invalid bitwidth for GEP index");
497 unsigned IdxId = BitWidth == 32 ? 0 : 1;
Reid Spencer88cfda22006-12-31 05:44:24 +0000498 Slot = (Slot << 1) | IdxId;
Reid Spencerad89bd62004-07-25 18:07:36 +0000499 }
Chris Lattnera2bdad42007-02-10 05:13:03 +0000500 output_vbr(Slot);
Reid Spencerad89bd62004-07-25 18:07:36 +0000501 }
502 }
Reid Spencerad89bd62004-07-25 18:07:36 +0000503}
504
505
506// outputInstrVarArgsCall - Output the absurdly annoying varargs function calls.
507// This are more annoying than most because the signature of the call does not
508// tell us anything about the types of the arguments in the varargs portion.
509// Because of this, we encode (as type 0) all of the argument types explicitly
510// before the argument value. This really sucks, but you shouldn't be using
511// varargs functions in your code! *death to printf*!
512//
513// Format: [opcode] [type] [numargs] [arg0] [arg1] ... [arg<numargs-1>]
514//
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000515void BytecodeWriter::outputInstrVarArgsCall(const Instruction *I,
516 unsigned Opcode,
517 const SlotCalculator &Table,
518 unsigned Type) {
Reid Spencerad89bd62004-07-25 18:07:36 +0000519 assert(isa<CallInst>(I) || isa<InvokeInst>(I));
520 // Opcode must have top two bits clear...
521 output_vbr(Opcode << 2); // Instruction Opcode ID
522 output_typeid(Type); // Result type (varargs type)
523
524 const PointerType *PTy = cast<PointerType>(I->getOperand(0)->getType());
525 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
526 unsigned NumParams = FTy->getNumParams();
527
528 unsigned NumFixedOperands;
529 if (isa<CallInst>(I)) {
530 // Output an operand for the callee and each fixed argument, then two for
531 // each variable argument.
532 NumFixedOperands = 1+NumParams;
533 } else {
534 assert(isa<InvokeInst>(I) && "Not call or invoke??");
535 // Output an operand for the callee and destinations, then two for each
536 // variable argument.
537 NumFixedOperands = 3+NumParams;
538 }
Reid Spencer3da59db2006-11-27 01:05:10 +0000539 output_vbr(2 * I->getNumOperands()-NumFixedOperands +
540 unsigned(Opcode == 58 || isa<InvokeInst>(I)));
Reid Spencerad89bd62004-07-25 18:07:36 +0000541
542 // The type for the function has already been emitted in the type field of the
543 // instruction. Just emit the slot # now.
Chris Lattnera2bdad42007-02-10 05:13:03 +0000544 for (unsigned i = 0; i != NumFixedOperands; ++i)
545 output_vbr(Table.getSlot(I->getOperand(i)));
Reid Spencerad89bd62004-07-25 18:07:36 +0000546
547 for (unsigned i = NumFixedOperands, e = I->getNumOperands(); i != e; ++i) {
548 // Output Arg Type ID
Chris Lattner972b4dc2007-02-10 05:17:48 +0000549 output_typeid(Table.getTypeSlot(I->getOperand(i)->getType()));
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000550
Reid Spencerad89bd62004-07-25 18:07:36 +0000551 // Output arg ID itself
Chris Lattnera2bdad42007-02-10 05:13:03 +0000552 output_vbr(Table.getSlot(I->getOperand(i)));
Reid Spencerad89bd62004-07-25 18:07:36 +0000553 }
Chris Lattnera65371e2006-05-26 18:42:34 +0000554
Reid Spencer3da59db2006-11-27 01:05:10 +0000555 if (isa<InvokeInst>(I)) {
556 // Emit the tail call/calling conv for invoke instructions
557 output_vbr(cast<InvokeInst>(I)->getCallingConv());
558 } else if (Opcode == 58) {
Chris Lattnera65371e2006-05-26 18:42:34 +0000559 const CallInst *CI = cast<CallInst>(I);
560 output_vbr((CI->getCallingConv() << 1) | unsigned(CI->isTailCall()));
Chris Lattnera65371e2006-05-26 18:42:34 +0000561 }
Reid Spencerad89bd62004-07-25 18:07:36 +0000562}
563
564
565// outputInstructionFormat1 - Output one operand instructions, knowing that no
566// operand index is >= 2^12.
567//
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000568inline void BytecodeWriter::outputInstructionFormat1(const Instruction *I,
569 unsigned Opcode,
570 unsigned *Slots,
571 unsigned Type) {
Reid Spencerad89bd62004-07-25 18:07:36 +0000572 // bits Instruction format:
573 // --------------------------
574 // 01-00: Opcode type, fixed to 1.
575 // 07-02: Opcode
576 // 19-08: Resulting type plane
577 // 31-20: Operand #1 (if set to (2^12-1), then zero operands)
578 //
Chris Lattnerf9d71782004-10-14 01:46:07 +0000579 output(1 | (Opcode << 2) | (Type << 8) | (Slots[0] << 20));
Reid Spencerad89bd62004-07-25 18:07:36 +0000580}
581
582
583// outputInstructionFormat2 - Output two operand instructions, knowing that no
584// operand index is >= 2^8.
585//
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000586inline void BytecodeWriter::outputInstructionFormat2(const Instruction *I,
587 unsigned Opcode,
588 unsigned *Slots,
589 unsigned Type) {
Reid Spencerad89bd62004-07-25 18:07:36 +0000590 // bits Instruction format:
591 // --------------------------
592 // 01-00: Opcode type, fixed to 2.
593 // 07-02: Opcode
594 // 15-08: Resulting type plane
595 // 23-16: Operand #1
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000596 // 31-24: Operand #2
Reid Spencerad89bd62004-07-25 18:07:36 +0000597 //
Chris Lattnerf9d71782004-10-14 01:46:07 +0000598 output(2 | (Opcode << 2) | (Type << 8) | (Slots[0] << 16) | (Slots[1] << 24));
Reid Spencerad89bd62004-07-25 18:07:36 +0000599}
600
601
602// outputInstructionFormat3 - Output three operand instructions, knowing that no
603// operand index is >= 2^6.
604//
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000605inline void BytecodeWriter::outputInstructionFormat3(const Instruction *I,
Reid Spencerad89bd62004-07-25 18:07:36 +0000606 unsigned Opcode,
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000607 unsigned *Slots,
608 unsigned Type) {
Reid Spencerad89bd62004-07-25 18:07:36 +0000609 // bits Instruction format:
610 // --------------------------
611 // 01-00: Opcode type, fixed to 3.
612 // 07-02: Opcode
613 // 13-08: Resulting type plane
614 // 19-14: Operand #1
615 // 25-20: Operand #2
616 // 31-26: Operand #3
617 //
Chris Lattnerf9d71782004-10-14 01:46:07 +0000618 output(3 | (Opcode << 2) | (Type << 8) |
Chris Lattner84d1ced2004-10-14 01:57:28 +0000619 (Slots[0] << 14) | (Slots[1] << 20) | (Slots[2] << 26));
Reid Spencerad89bd62004-07-25 18:07:36 +0000620}
621
622void BytecodeWriter::outputInstruction(const Instruction &I) {
Reid Spencer3da59db2006-11-27 01:05:10 +0000623 assert(I.getOpcode() < 57 && "Opcode too big???");
Reid Spencerad89bd62004-07-25 18:07:36 +0000624 unsigned Opcode = I.getOpcode();
625 unsigned NumOperands = I.getNumOperands();
626
Christopher Lamb43c7f372007-04-22 19:24:39 +0000627 // Encode 'tail call' as 61
Chris Lattner38287bd2005-05-06 06:13:34 +0000628 // 63.
Chris Lattnerdee199f2005-05-06 22:34:01 +0000629 if (const CallInst *CI = dyn_cast<CallInst>(&I)) {
630 if (CI->getCallingConv() == CallingConv::C) {
631 if (CI->isTailCall())
632 Opcode = 61; // CCC + Tail Call
633 else
634 ; // Opcode = Instruction::Call
635 } else if (CI->getCallingConv() == CallingConv::Fast) {
636 if (CI->isTailCall())
637 Opcode = 59; // FastCC + TailCall
638 else
639 Opcode = 60; // FastCC + Not Tail Call
640 } else {
641 Opcode = 58; // Call escape sequence.
642 }
Chris Lattnerdee199f2005-05-06 22:34:01 +0000643 }
Reid Spencerad89bd62004-07-25 18:07:36 +0000644
645 // Figure out which type to encode with the instruction. Typically we want
646 // the type of the first parameter, as opposed to the type of the instruction
647 // (for example, with setcc, we always know it returns bool, but the type of
648 // the first param is actually interesting). But if we have no arguments
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000649 // we take the type of the instruction itself.
Reid Spencerad89bd62004-07-25 18:07:36 +0000650 //
651 const Type *Ty;
652 switch (I.getOpcode()) {
653 case Instruction::Select:
654 case Instruction::Malloc:
655 case Instruction::Alloca:
656 Ty = I.getType(); // These ALWAYS want to encode the return type
657 break;
658 case Instruction::Store:
659 Ty = I.getOperand(1)->getType(); // Encode the pointer type...
660 assert(isa<PointerType>(Ty) && "Store to nonpointer type!?!?");
661 break;
662 default: // Otherwise use the default behavior...
663 Ty = NumOperands ? I.getOperand(0)->getType() : I.getType();
664 break;
665 }
666
Chris Lattner972b4dc2007-02-10 05:17:48 +0000667 unsigned Type = Table.getTypeSlot(Ty);
Reid Spencerad89bd62004-07-25 18:07:36 +0000668
669 // Varargs calls and invokes are encoded entirely different from any other
670 // instructions.
671 if (const CallInst *CI = dyn_cast<CallInst>(&I)){
672 const PointerType *Ty =cast<PointerType>(CI->getCalledValue()->getType());
673 if (cast<FunctionType>(Ty->getElementType())->isVarArg()) {
674 outputInstrVarArgsCall(CI, Opcode, Table, Type);
675 return;
676 }
677 } else if (const InvokeInst *II = dyn_cast<InvokeInst>(&I)) {
678 const PointerType *Ty =cast<PointerType>(II->getCalledValue()->getType());
679 if (cast<FunctionType>(Ty->getElementType())->isVarArg()) {
680 outputInstrVarArgsCall(II, Opcode, Table, Type);
681 return;
682 }
683 }
684
685 if (NumOperands <= 3) {
686 // Make sure that we take the type number into consideration. We don't want
687 // to overflow the field size for the instruction format we select.
688 //
689 unsigned MaxOpSlot = Type;
690 unsigned Slots[3]; Slots[0] = (1 << 12)-1; // Marker to signify 0 operands
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000691
Reid Spencerad89bd62004-07-25 18:07:36 +0000692 for (unsigned i = 0; i != NumOperands; ++i) {
Chris Lattnera2bdad42007-02-10 05:13:03 +0000693 unsigned Slot = Table.getSlot(I.getOperand(i));
694 if (Slot > MaxOpSlot) MaxOpSlot = Slot;
695 Slots[i] = Slot;
Reid Spencerad89bd62004-07-25 18:07:36 +0000696 }
697
698 // Handle the special cases for various instructions...
699 if (isa<CastInst>(I) || isa<VAArgInst>(I)) {
700 // Cast has to encode the destination type as the second argument in the
701 // packet, or else we won't know what type to cast to!
Chris Lattnercb43fdc2007-02-10 04:15:40 +0000702 Slots[1] = Table.getTypeSlot(I.getType());
Reid Spencerad89bd62004-07-25 18:07:36 +0000703 if (Slots[1] > MaxOpSlot) MaxOpSlot = Slots[1];
704 NumOperands++;
Chris Lattner42ba6b42005-11-05 22:08:14 +0000705 } else if (const AllocationInst *AI = dyn_cast<AllocationInst>(&I)) {
706 assert(NumOperands == 1 && "Bogus allocation!");
707 if (AI->getAlignment()) {
708 Slots[1] = Log2_32(AI->getAlignment())+1;
709 if (Slots[1] > MaxOpSlot) MaxOpSlot = Slots[1];
710 NumOperands = 2;
711 }
Reid Spencerc8dab492006-12-03 06:28:54 +0000712 } else if (isa<ICmpInst>(I) || isa<FCmpInst>(I)) {
713 // We need to encode the compare instruction's predicate as the third
714 // operand. Its not really a slot, but we don't want to break the
715 // instruction format for these instructions.
716 NumOperands++;
717 assert(NumOperands == 3 && "CmpInst with wrong number of operands?");
718 Slots[2] = unsigned(cast<CmpInst>(&I)->getPredicate());
719 if (Slots[2] > MaxOpSlot)
720 MaxOpSlot = Slots[2];
Reid Spencerad89bd62004-07-25 18:07:36 +0000721 } else if (const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(&I)) {
722 // We need to encode the type of sequential type indices into their slot #
723 unsigned Idx = 1;
724 for (gep_type_iterator I = gep_type_begin(GEP), E = gep_type_end(GEP);
725 I != E; ++I, ++Idx)
726 if (isa<SequentialType>(*I)) {
Reid Spencera54b7cb2007-01-12 07:05:14 +0000727 // These should be either 32-bits or 64-bits, however, with bit
728 // accurate types we just distinguish between less than or equal to
729 // 32-bits or greater than 32-bits.
Reid Spencer790366b2007-01-13 00:10:02 +0000730 unsigned BitWidth =
731 cast<IntegerType>(GEP->getOperand(Idx)->getType())->getBitWidth();
732 assert(BitWidth == 32 || BitWidth == 64 &&
733 "Invalid bitwidth for GEP index");
734 unsigned IdxId = BitWidth == 32 ? 0 : 1;
Reid Spencer88cfda22006-12-31 05:44:24 +0000735 Slots[Idx] = (Slots[Idx] << 1) | IdxId;
Reid Spencerad89bd62004-07-25 18:07:36 +0000736 if (Slots[Idx] > MaxOpSlot) MaxOpSlot = Slots[Idx];
737 }
Chris Lattnerdee199f2005-05-06 22:34:01 +0000738 } else if (Opcode == 58) {
739 // If this is the escape sequence for call, emit the tailcall/cc info.
740 const CallInst &CI = cast<CallInst>(I);
741 ++NumOperands;
Chris Lattnerebf8e6c2006-05-19 21:57:37 +0000742 if (NumOperands <= 3) {
743 Slots[NumOperands-1] =
744 (CI.getCallingConv() << 1)|unsigned(CI.isTailCall());
Chris Lattnerdee199f2005-05-06 22:34:01 +0000745 if (Slots[NumOperands-1] > MaxOpSlot)
746 MaxOpSlot = Slots[NumOperands-1];
747 }
Reid Spencer3da59db2006-11-27 01:05:10 +0000748 } else if (isa<InvokeInst>(I)) {
Chris Lattnerdee199f2005-05-06 22:34:01 +0000749 // Invoke escape seq has at least 4 operands to encode.
750 ++NumOperands;
Christopher Lamb43c7f372007-04-22 19:24:39 +0000751 } else if (const LoadInst *LI = dyn_cast<LoadInst>(&I)) {
752 // Encode attributed load as opcode 62
753 // We need to encode the attributes of the load instruction as the second
754 // operand. Its not really a slot, but we don't want to break the
755 // instruction format for these instructions.
756 if (LI->getAlignment() || LI->isVolatile()) {
757 NumOperands = 2;
758 Slots[1] = ((Log2_32(LI->getAlignment())+1)<<1) +
759 (LI->isVolatile() ? 1 : 0);
760 if (Slots[1] > MaxOpSlot)
761 MaxOpSlot = Slots[1];
762 Opcode = 62;
763 }
764 } else if (const StoreInst *SI = dyn_cast<StoreInst>(&I)) {
765 // Encode attributed store as opcode 63
766 // We need to encode the attributes of the store instruction as the third
767 // operand. Its not really a slot, but we don't want to break the
768 // instruction format for these instructions.
769 if (SI->getAlignment() || SI->isVolatile()) {
770 NumOperands = 3;
771 Slots[2] = ((Log2_32(SI->getAlignment())+1)<<1) +
772 (SI->isVolatile() ? 1 : 0);
773 if (Slots[2] > MaxOpSlot)
774 MaxOpSlot = Slots[2];
775 Opcode = 63;
776 }
Reid Spencerad89bd62004-07-25 18:07:36 +0000777 }
778
779 // Decide which instruction encoding to use. This is determined primarily
780 // by the number of operands, and secondarily by whether or not the max
781 // operand will fit into the instruction encoding. More operands == fewer
782 // bits per operand.
783 //
784 switch (NumOperands) {
785 case 0:
786 case 1:
787 if (MaxOpSlot < (1 << 12)-1) { // -1 because we use 4095 to indicate 0 ops
788 outputInstructionFormat1(&I, Opcode, Slots, Type);
789 return;
790 }
791 break;
792
793 case 2:
794 if (MaxOpSlot < (1 << 8)) {
795 outputInstructionFormat2(&I, Opcode, Slots, Type);
796 return;
797 }
798 break;
799
800 case 3:
801 if (MaxOpSlot < (1 << 6)) {
802 outputInstructionFormat3(&I, Opcode, Slots, Type);
803 return;
804 }
805 break;
806 default:
807 break;
808 }
809 }
810
811 // If we weren't handled before here, we either have a large number of
812 // operands or a large operand index that we are referring to.
813 outputInstructionFormat0(&I, Opcode, Table, Type);
814}
815
816//===----------------------------------------------------------------------===//
817//=== Block Output ===//
818//===----------------------------------------------------------------------===//
819
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000820BytecodeWriter::BytecodeWriter(std::vector<unsigned char> &o, const Module *M)
Reid Spencer798ff642004-05-26 07:37:11 +0000821 : Out(o), Table(M) {
Chris Lattner00950542001-06-06 20:29:01 +0000822
Chris Lattner83bb3d22004-01-14 23:36:54 +0000823 // Emit the signature...
Chris Lattnerc847f7c2006-07-28 22:07:54 +0000824 static const unsigned char *Sig = (const unsigned char*)"llvm";
Reid Spencerad89bd62004-07-25 18:07:36 +0000825 output_data(Sig, Sig+4);
Chris Lattner00950542001-06-06 20:29:01 +0000826
827 // Emit the top level CLASS block.
Reid Spencerad89bd62004-07-25 18:07:36 +0000828 BytecodeBlock ModuleBlock(BytecodeFormat::ModuleBlockID, *this, false, true);
Chris Lattner00950542001-06-06 20:29:01 +0000829
Reid Spenceraacc35a2007-01-26 08:10:24 +0000830 // Output the version identifier
831 output_vbr(BCVersionNum);
Chris Lattner00950542001-06-06 20:29:01 +0000832
Reid Spencercb3595c2004-07-04 11:45:47 +0000833 // The Global type plane comes first
Chris Lattner186a1f72003-03-19 20:56:46 +0000834 {
Chris Lattnerc847f7c2006-07-28 22:07:54 +0000835 BytecodeBlock CPool(BytecodeFormat::GlobalTypePlaneBlockID, *this);
836 outputTypes(Type::FirstDerivedTyID);
Chris Lattner186a1f72003-03-19 20:56:46 +0000837 }
Chris Lattner00950542001-06-06 20:29:01 +0000838
Chris Lattner186a1f72003-03-19 20:56:46 +0000839 // The ModuleInfoBlock follows directly after the type information
Chris Lattnere8fdde12001-09-07 16:39:41 +0000840 outputModuleInfoBlock(M);
841
Chris Lattner186a1f72003-03-19 20:56:46 +0000842 // Output module level constants, used for global variable initializers
Chris Lattner8dcd81c2007-02-09 07:53:20 +0000843 outputConstants();
Chris Lattner186a1f72003-03-19 20:56:46 +0000844
Chris Lattnerb5794002002-04-07 22:49:37 +0000845 // Do the whole module now! Process each function at a time...
Chris Lattner0b12b5f2002-06-25 16:13:21 +0000846 for (Module::const_iterator I = M->begin(), E = M->end(); I != E; ++I)
Chris Lattner186a1f72003-03-19 20:56:46 +0000847 outputFunction(I);
Chris Lattnere8fdde12001-09-07 16:39:41 +0000848
Reid Spencer78d033e2007-01-06 07:24:44 +0000849 // Output the symbole table for types
850 outputTypeSymbolTable(M->getTypeSymbolTable());
851
852 // Output the symbol table for values
853 outputValueSymbolTable(M->getValueSymbolTable());
Chris Lattner00950542001-06-06 20:29:01 +0000854}
855
Chris Lattnerf9d71782004-10-14 01:46:07 +0000856void BytecodeWriter::outputTypes(unsigned TypeNum) {
Reid Spencercb3595c2004-07-04 11:45:47 +0000857 // Write the type plane for types first because earlier planes (e.g. for a
858 // primitive type like float) may have constants constructed using types
859 // coming later (e.g., via getelementptr from a pointer type). The type
860 // plane is needed before types can be fwd or bkwd referenced.
861 const std::vector<const Type*>& Types = Table.getTypes();
862 assert(!Types.empty() && "No types at all?");
863 assert(TypeNum <= Types.size() && "Invalid TypeNo index");
864
865 unsigned NumEntries = Types.size() - TypeNum;
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000866
Reid Spencercb3595c2004-07-04 11:45:47 +0000867 // Output type header: [num entries]
Reid Spencerad89bd62004-07-25 18:07:36 +0000868 output_vbr(NumEntries);
Reid Spencercb3595c2004-07-04 11:45:47 +0000869
870 for (unsigned i = TypeNum; i < TypeNum+NumEntries; ++i)
871 outputType(Types[i]);
872}
873
Vikram S. Advea7dac3d2002-07-14 23:07:51 +0000874// Helper function for outputConstants().
875// Writes out all the constants in the plane Plane starting at entry StartNo.
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000876//
Chris Lattner863da4c2007-02-10 07:42:59 +0000877void BytecodeWriter::outputConstantsInPlane(const Value *const *Plane,
878 unsigned PlaneSize,
879 unsigned StartNo) {
Vikram S. Advea7dac3d2002-07-14 23:07:51 +0000880 unsigned ValNo = StartNo;
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000881
Chris Lattner83bb3d22004-01-14 23:36:54 +0000882 // Scan through and ignore function arguments, global values, and constant
883 // strings.
Chris Lattner863da4c2007-02-10 07:42:59 +0000884 for (; ValNo < PlaneSize &&
Chris Lattner83bb3d22004-01-14 23:36:54 +0000885 (isa<Argument>(Plane[ValNo]) || isa<GlobalValue>(Plane[ValNo]) ||
886 (isa<ConstantArray>(Plane[ValNo]) &&
887 cast<ConstantArray>(Plane[ValNo])->isString())); ValNo++)
Vikram S. Advea7dac3d2002-07-14 23:07:51 +0000888 /*empty*/;
889
890 unsigned NC = ValNo; // Number of constants
Chris Lattner863da4c2007-02-10 07:42:59 +0000891 for (; NC < PlaneSize && (isa<Constant>(Plane[NC]) ||
892 isa<InlineAsm>(Plane[NC])); NC++)
Vikram S. Advea7dac3d2002-07-14 23:07:51 +0000893 /*empty*/;
894 NC -= ValNo; // Convert from index into count
895 if (NC == 0) return; // Skip empty type planes...
896
Chris Lattnerd6942d72004-01-14 16:54:21 +0000897 // FIXME: Most slabs only have 1 or 2 entries! We should encode this much
898 // more compactly.
899
Reid Spencerb83eb642006-10-20 07:07:24 +0000900 // Put out type header: [num entries][type id number]
Vikram S. Advea7dac3d2002-07-14 23:07:51 +0000901 //
Reid Spencerad89bd62004-07-25 18:07:36 +0000902 output_vbr(NC);
Vikram S. Advea7dac3d2002-07-14 23:07:51 +0000903
Chris Lattner972b4dc2007-02-10 05:17:48 +0000904 // Put out the Type ID Number.
Chris Lattner863da4c2007-02-10 07:42:59 +0000905 output_typeid(Table.getTypeSlot(Plane[0]->getType()));
Vikram S. Advea7dac3d2002-07-14 23:07:51 +0000906
Vikram S. Advea7dac3d2002-07-14 23:07:51 +0000907 for (unsigned i = ValNo; i < ValNo+NC; ++i) {
908 const Value *V = Plane[i];
Chris Lattner3bc5a602006-01-25 23:08:15 +0000909 if (const Constant *C = dyn_cast<Constant>(V))
Reid Spencere0125b62004-07-18 00:16:21 +0000910 outputConstant(C);
Chris Lattner3bc5a602006-01-25 23:08:15 +0000911 else
912 outputInlineAsm(cast<InlineAsm>(V));
Vikram S. Advea7dac3d2002-07-14 23:07:51 +0000913 }
914}
915
Chris Lattner9e60d8d2005-05-05 22:21:19 +0000916static inline bool hasNullValue(const Type *Ty) {
917 return Ty != Type::LabelTy && Ty != Type::VoidTy && !isa<OpaqueType>(Ty);
Chris Lattner80b97342004-01-17 23:25:43 +0000918}
919
Chris Lattner8dcd81c2007-02-09 07:53:20 +0000920void BytecodeWriter::outputConstants() {
Reid Spencerad89bd62004-07-25 18:07:36 +0000921 BytecodeBlock CPool(BytecodeFormat::ConstantPoolBlockID, *this,
Chris Lattner0baa0af2004-01-15 21:06:57 +0000922 true /* Elide block if empty */);
Chris Lattner00950542001-06-06 20:29:01 +0000923
924 unsigned NumPlanes = Table.getNumPlanes();
Chris Lattnerf69315b2003-05-22 18:35:38 +0000925
Chris Lattner8dcd81c2007-02-09 07:53:20 +0000926 // Output module-level string constants before any other constants.
927 outputConstantStrings();
Chris Lattner83bb3d22004-01-14 23:36:54 +0000928
Reid Spencercb3595c2004-07-04 11:45:47 +0000929 for (unsigned pno = 0; pno != NumPlanes; pno++) {
Chris Lattner863da4c2007-02-10 07:42:59 +0000930 const SlotCalculator::TypePlane &Plane = Table.getPlane(pno);
Reid Spencercb3595c2004-07-04 11:45:47 +0000931 if (!Plane.empty()) { // Skip empty type planes...
932 unsigned ValNo = 0;
Chris Lattner9e60d8d2005-05-05 22:21:19 +0000933 if (hasNullValue(Plane[0]->getType())) {
Reid Spencer0852c802004-07-04 11:46:15 +0000934 // Skip zero initializer
Chris Lattner8dcd81c2007-02-09 07:53:20 +0000935 ValNo = 1;
Chris Lattnerf69315b2003-05-22 18:35:38 +0000936 }
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000937
Reid Spencercb3595c2004-07-04 11:45:47 +0000938 // Write out constants in the plane
Chris Lattner863da4c2007-02-10 07:42:59 +0000939 outputConstantsInPlane(&Plane[0], Plane.size(), ValNo);
Chris Lattnerf69315b2003-05-22 18:35:38 +0000940 }
Reid Spencercb3595c2004-07-04 11:45:47 +0000941 }
Chris Lattner00950542001-06-06 20:29:01 +0000942}
943
Chris Lattner6b252422003-10-16 18:28:50 +0000944static unsigned getEncodedLinkage(const GlobalValue *GV) {
945 switch (GV->getLinkage()) {
946 default: assert(0 && "Invalid linkage!");
Anton Korobeynikovb74ed072006-09-14 18:23:27 +0000947 case GlobalValue::ExternalLinkage: return 0;
948 case GlobalValue::WeakLinkage: return 1;
949 case GlobalValue::AppendingLinkage: return 2;
950 case GlobalValue::InternalLinkage: return 3;
951 case GlobalValue::LinkOnceLinkage: return 4;
952 case GlobalValue::DLLImportLinkage: return 5;
953 case GlobalValue::DLLExportLinkage: return 6;
954 case GlobalValue::ExternalWeakLinkage: return 7;
Chris Lattner6b252422003-10-16 18:28:50 +0000955 }
956}
957
Anton Korobeynikov7f705592007-01-12 19:20:47 +0000958static unsigned getEncodedVisibility(const GlobalValue *GV) {
959 switch (GV->getVisibility()) {
960 default: assert(0 && "Invalid visibility!");
Anton Korobeynikov6f9896f2007-04-29 18:35:00 +0000961 case GlobalValue::DefaultVisibility: return 0;
962 case GlobalValue::HiddenVisibility: return 1;
963 case GlobalValue::ProtectedVisibility: return 2;
Anton Korobeynikov7f705592007-01-12 19:20:47 +0000964 }
965}
966
Chris Lattner00950542001-06-06 20:29:01 +0000967void BytecodeWriter::outputModuleInfoBlock(const Module *M) {
Reid Spencerad89bd62004-07-25 18:07:36 +0000968 BytecodeBlock ModuleInfoBlock(BytecodeFormat::ModuleGlobalInfoBlockID, *this);
Misha Brukman23c6d2c2005-04-21 21:48:46 +0000969
Chris Lattner404cddf2005-11-12 01:33:40 +0000970 // Give numbers to sections as we encounter them.
971 unsigned SectionIDCounter = 0;
972 std::vector<std::string> SectionNames;
973 std::map<std::string, unsigned> SectionID;
974
Chris Lattner70cc3392001-09-10 07:58:01 +0000975 // Output the types for the global variables in the module...
Chris Lattner28caccf2005-05-06 20:27:03 +0000976 for (Module::const_global_iterator I = M->global_begin(),
Chris Lattner8eb52dd2005-11-06 07:11:04 +0000977 End = M->global_end(); I != End; ++I) {
Chris Lattner972b4dc2007-02-10 05:17:48 +0000978 unsigned Slot = Table.getTypeSlot(I->getType());
Chris Lattnerd70684f2001-09-18 04:01:05 +0000979
Chris Lattner8eb52dd2005-11-06 07:11:04 +0000980 assert((I->hasInitializer() || !I->hasInternalLinkage()) &&
981 "Global must have an initializer or have external linkage!");
982
Chris Lattner22482a12003-10-18 06:30:21 +0000983 // Fields: bit0 = isConstant, bit1 = hasInitializer, bit2-4=Linkage,
Lauro Ramos Venancioc7635522007-04-12 18:32:50 +0000984 // bit5 = isThreadLocal, bit6+ = Slot # for type.
Anton Korobeynikov7f705592007-01-12 19:20:47 +0000985 bool HasExtensionWord = (I->getAlignment() != 0) ||
986 I->hasSection() ||
987 (I->getVisibility() != GlobalValue::DefaultVisibility);
Chris Lattner8eb52dd2005-11-06 07:11:04 +0000988
989 // If we need to use the extension byte, set linkage=3(internal) and
990 // initializer = 0 (impossible!).
991 if (!HasExtensionWord) {
Lauro Ramos Venancioc7635522007-04-12 18:32:50 +0000992 unsigned oSlot = (Slot << 6)| (((unsigned)I->isThreadLocal()) << 5) |
993 (getEncodedLinkage(I) << 2) | (I->hasInitializer() << 1)
994 | (unsigned)I->isConstant();
Chris Lattner8eb52dd2005-11-06 07:11:04 +0000995 output_vbr(oSlot);
Anton Korobeynikovb74ed072006-09-14 18:23:27 +0000996 } else {
Lauro Ramos Venancioc7635522007-04-12 18:32:50 +0000997 unsigned oSlot = (Slot << 6) | (((unsigned)I->isThreadLocal()) << 5) |
998 (3 << 2) | (0 << 1) | (unsigned)I->isConstant();
Chris Lattner8eb52dd2005-11-06 07:11:04 +0000999 output_vbr(oSlot);
1000
1001 // The extension word has this format: bit 0 = has initializer, bit 1-3 =
Anton Korobeynikov7f705592007-01-12 19:20:47 +00001002 // linkage, bit 4-8 = alignment (log2), bit 9 = has SectionID,
1003 // bits 10-12 = visibility, bits 13+ = future use.
Jeff Cohenba0ffcc2005-11-12 01:01:50 +00001004 unsigned ExtWord = (unsigned)I->hasInitializer() |
1005 (getEncodedLinkage(I) << 1) |
Chris Lattner404cddf2005-11-12 01:33:40 +00001006 ((Log2_32(I->getAlignment())+1) << 4) |
Anton Korobeynikov7f705592007-01-12 19:20:47 +00001007 ((unsigned)I->hasSection() << 9) |
1008 (getEncodedVisibility(I) << 10);
Chris Lattner8eb52dd2005-11-06 07:11:04 +00001009 output_vbr(ExtWord);
Chris Lattner404cddf2005-11-12 01:33:40 +00001010 if (I->hasSection()) {
1011 // Give section names unique ID's.
1012 unsigned &Entry = SectionID[I->getSection()];
1013 if (Entry == 0) {
1014 Entry = ++SectionIDCounter;
1015 SectionNames.push_back(I->getSection());
1016 }
1017 output_vbr(Entry);
1018 }
Chris Lattner8eb52dd2005-11-06 07:11:04 +00001019 }
Chris Lattnerd70684f2001-09-18 04:01:05 +00001020
Chris Lattner1b98c5c2001-10-13 06:48:38 +00001021 // If we have an initializer, output it now.
Chris Lattnera2bdad42007-02-10 05:13:03 +00001022 if (I->hasInitializer())
1023 output_vbr(Table.getSlot((Value*)I->getInitializer()));
Chris Lattner70cc3392001-09-10 07:58:01 +00001024 }
Chris Lattner972b4dc2007-02-10 05:17:48 +00001025 output_typeid(Table.getTypeSlot(Type::VoidTy));
Chris Lattner70cc3392001-09-10 07:58:01 +00001026
Chris Lattnera79e7cc2004-10-16 18:18:16 +00001027 // Output the types of the functions in this module.
Chris Lattner7fc9fe32001-06-27 23:41:11 +00001028 for (Module::const_iterator I = M->begin(), End = M->end(); I != End; ++I) {
Chris Lattner972b4dc2007-02-10 05:17:48 +00001029 unsigned Slot = Table.getTypeSlot(I->getType());
Chris Lattnere73bd452005-11-06 07:43:39 +00001030 assert(((Slot << 6) >> 6) == Slot && "Slot # too big!");
Chris Lattner54b369e2005-11-06 07:46:13 +00001031 unsigned CC = I->getCallingConv()+1;
1032 unsigned ID = (Slot << 5) | (CC & 15);
Chris Lattner479ffeb2005-05-06 20:42:57 +00001033
Reid Spencere8501ab2007-04-16 23:32:28 +00001034 if (I->isDeclaration()) // If external, we don't have an FunctionInfo block.
Chris Lattnerd6e431f2004-11-15 22:39:49 +00001035 ID |= 1 << 4;
Chris Lattnere73bd452005-11-06 07:43:39 +00001036
Anton Korobeynikovb74ed072006-09-14 18:23:27 +00001037 if (I->getAlignment() || I->hasSection() || (CC & ~15) != 0 ||
Reid Spencer5cbf9852007-01-30 20:08:39 +00001038 (I->isDeclaration() && I->hasDLLImportLinkage()) ||
1039 (I->isDeclaration() && I->hasExternalWeakLinkage())
Anton Korobeynikovb74ed072006-09-14 18:23:27 +00001040 )
Chris Lattnere73bd452005-11-06 07:43:39 +00001041 ID |= 1 << 31; // Do we need an extension word?
1042
Chris Lattnera79e7cc2004-10-16 18:18:16 +00001043 output_vbr(ID);
Chris Lattnere73bd452005-11-06 07:43:39 +00001044
1045 if (ID & (1 << 31)) {
1046 // Extension byte: bits 0-4 = alignment, bits 5-9 = top nibble of calling
Anton Korobeynikovb74ed072006-09-14 18:23:27 +00001047 // convention, bit 10 = hasSectionID., bits 11-12 = external linkage type
1048 unsigned extLinkage = 0;
1049
Reid Spencer5cbf9852007-01-30 20:08:39 +00001050 if (I->isDeclaration()) {
Anton Korobeynikovb74ed072006-09-14 18:23:27 +00001051 if (I->hasDLLImportLinkage()) {
1052 extLinkage = 1;
1053 } else if (I->hasExternalWeakLinkage()) {
1054 extLinkage = 2;
1055 }
1056 }
1057
Chris Lattner404cddf2005-11-12 01:33:40 +00001058 ID = (Log2_32(I->getAlignment())+1) | ((CC >> 4) << 5) |
Anton Korobeynikovb74ed072006-09-14 18:23:27 +00001059 (I->hasSection() << 10) |
1060 ((extLinkage & 3) << 11);
Chris Lattnere73bd452005-11-06 07:43:39 +00001061 output_vbr(ID);
Chris Lattner404cddf2005-11-12 01:33:40 +00001062
1063 // Give section names unique ID's.
1064 if (I->hasSection()) {
1065 unsigned &Entry = SectionID[I->getSection()];
1066 if (Entry == 0) {
1067 Entry = ++SectionIDCounter;
1068 SectionNames.push_back(I->getSection());
1069 }
1070 output_vbr(Entry);
1071 }
Chris Lattnere73bd452005-11-06 07:43:39 +00001072 }
Chris Lattner00950542001-06-06 20:29:01 +00001073 }
Chris Lattner972b4dc2007-02-10 05:17:48 +00001074 output_vbr(Table.getTypeSlot(Type::VoidTy) << 5);
Reid Spencerad89bd62004-07-25 18:07:36 +00001075
Chris Lattnera79e7cc2004-10-16 18:18:16 +00001076 // Emit the list of dependent libraries for the Module.
Reid Spencer5ac88122004-07-25 21:32:02 +00001077 Module::lib_iterator LI = M->lib_begin();
1078 Module::lib_iterator LE = M->lib_end();
Chris Lattnera79e7cc2004-10-16 18:18:16 +00001079 output_vbr(unsigned(LE - LI)); // Emit the number of dependent libraries.
1080 for (; LI != LE; ++LI)
Reid Spencer38d54be2004-08-17 07:45:14 +00001081 output(*LI);
Reid Spencerad89bd62004-07-25 18:07:36 +00001082
1083 // Output the target triple from the module
Reid Spencer38d54be2004-08-17 07:45:14 +00001084 output(M->getTargetTriple());
Reid Spenceraacc35a2007-01-26 08:10:24 +00001085
1086 // Output the data layout from the module
1087 output(M->getDataLayout());
Chris Lattner404cddf2005-11-12 01:33:40 +00001088
1089 // Emit the table of section names.
1090 output_vbr((unsigned)SectionNames.size());
1091 for (unsigned i = 0, e = SectionNames.size(); i != e; ++i)
1092 output(SectionNames[i]);
Anton Korobeynikov8b0a8c82007-04-25 14:27:10 +00001093
Chris Lattner7e6db762006-01-23 23:43:17 +00001094 // Output the inline asm string.
Chris Lattner66316012006-01-24 04:14:29 +00001095 output(M->getModuleInlineAsm());
Anton Korobeynikov8b0a8c82007-04-25 14:27:10 +00001096
1097 // Output aliases
1098 for (Module::const_alias_iterator I = M->alias_begin(), E = M->alias_end();
1099 I != E; ++I) {
Anton Korobeynikova80e1182007-04-28 13:45:00 +00001100 unsigned TypeSlotNo = Table.getTypeSlot(I->getType());
1101 unsigned AliaseeSlotNo = Table.getSlot(I->getAliasee());
1102 assert(((TypeSlotNo << 3) >> 3) == TypeSlotNo && "Slot # too big!");
Anton Korobeynikov8b0a8c82007-04-25 14:27:10 +00001103 unsigned aliasLinkage = 0;
Anton Korobeynikova80e1182007-04-28 13:45:00 +00001104 unsigned isConstantAliasee = ((!isa<GlobalValue>(I->getAliasee())) << 2);
Anton Korobeynikov8b0a8c82007-04-25 14:27:10 +00001105 switch (I->getLinkage()) {
1106 case GlobalValue::ExternalLinkage:
1107 aliasLinkage = 0;
1108 break;
1109 case GlobalValue::InternalLinkage:
1110 aliasLinkage = 1;
1111 break;
1112 case GlobalValue::WeakLinkage:
1113 aliasLinkage = 2;
1114 break;
1115 default:
1116 assert(0 && "Invalid alias linkage");
1117 }
Anton Korobeynikova80e1182007-04-28 13:45:00 +00001118 output_vbr((TypeSlotNo << 3) | isConstantAliasee | aliasLinkage);
1119 output_vbr(AliaseeSlotNo);
Anton Korobeynikov8b0a8c82007-04-25 14:27:10 +00001120 }
1121 output_typeid(Table.getTypeSlot(Type::VoidTy));
Chris Lattner00950542001-06-06 20:29:01 +00001122}
1123
Chris Lattnercf3e67f2004-01-18 21:08:52 +00001124void BytecodeWriter::outputInstructions(const Function *F) {
Reid Spencerad89bd62004-07-25 18:07:36 +00001125 BytecodeBlock ILBlock(BytecodeFormat::InstructionListBlockID, *this);
Chris Lattnercf3e67f2004-01-18 21:08:52 +00001126 for (Function::const_iterator BB = F->begin(), E = F->end(); BB != E; ++BB)
1127 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I!=E; ++I)
1128 outputInstruction(*I);
Chris Lattnercf3e67f2004-01-18 21:08:52 +00001129}
1130
Chris Lattner186a1f72003-03-19 20:56:46 +00001131void BytecodeWriter::outputFunction(const Function *F) {
Chris Lattnerfd7f8fe2004-11-15 21:56:33 +00001132 // If this is an external function, there is nothing else to emit!
Reid Spencer5cbf9852007-01-30 20:08:39 +00001133 if (F->isDeclaration()) return;
Chris Lattnerfd7f8fe2004-11-15 21:56:33 +00001134
Chris Lattnerd6e431f2004-11-15 22:39:49 +00001135 BytecodeBlock FunctionBlock(BytecodeFormat::FunctionBlockID, *this);
Anton Korobeynikov7f705592007-01-12 19:20:47 +00001136 unsigned rWord = (getEncodedVisibility(F) << 16) | getEncodedLinkage(F);
1137 output_vbr(rWord);
Chris Lattnerd6e431f2004-11-15 22:39:49 +00001138
Chris Lattnercf3e67f2004-01-18 21:08:52 +00001139 // Get slot information about the function...
1140 Table.incorporateFunction(F);
1141
Chris Lattnercf3e67f2004-01-18 21:08:52 +00001142 // Output all of the instructions in the body of the function
1143 outputInstructions(F);
Misha Brukman23c6d2c2005-04-21 21:48:46 +00001144
Chris Lattnercf3e67f2004-01-18 21:08:52 +00001145 // If needed, output the symbol table for the function...
Reid Spencer78d033e2007-01-06 07:24:44 +00001146 outputValueSymbolTable(F->getValueSymbolTable());
Misha Brukman23c6d2c2005-04-21 21:48:46 +00001147
Chris Lattnercf3e67f2004-01-18 21:08:52 +00001148 Table.purgeFunction();
1149}
1150
Chris Lattner00950542001-06-06 20:29:01 +00001151
Reid Spencer78d033e2007-01-06 07:24:44 +00001152void BytecodeWriter::outputTypeSymbolTable(const TypeSymbolTable &TST) {
1153 // Do not output the block for an empty symbol table, it just wastes
Chris Lattner737d3cd2004-01-10 19:56:59 +00001154 // space!
Reid Spencer78d033e2007-01-06 07:24:44 +00001155 if (TST.empty()) return;
Chris Lattner737d3cd2004-01-10 19:56:59 +00001156
Reid Spencer78d033e2007-01-06 07:24:44 +00001157 // Create a header for the symbol table
1158 BytecodeBlock SymTabBlock(BytecodeFormat::TypeSymbolTableBlockID, *this,
Chris Lattnerf9d71782004-10-14 01:46:07 +00001159 true/*ElideIfEmpty*/);
Misha Brukman23c6d2c2005-04-21 21:48:46 +00001160 // Write the number of types
Reid Spencer78d033e2007-01-06 07:24:44 +00001161 output_vbr(TST.size());
Reid Spencer250c4182004-08-17 02:59:02 +00001162
1163 // Write each of the types
Reid Spencer78d033e2007-01-06 07:24:44 +00001164 for (TypeSymbolTable::const_iterator TI = TST.begin(), TE = TST.end();
1165 TI != TE; ++TI) {
Reid Spencer250c4182004-08-17 02:59:02 +00001166 // Symtab entry:[def slot #][name]
Chris Lattner972b4dc2007-02-10 05:17:48 +00001167 output_typeid(Table.getTypeSlot(TI->second));
Misha Brukman23c6d2c2005-04-21 21:48:46 +00001168 output(TI->first);
Reid Spencer94f2df22004-05-25 17:29:59 +00001169 }
Reid Spencer78d033e2007-01-06 07:24:44 +00001170}
1171
Reid Spenceref9b9a72007-02-05 20:47:22 +00001172void BytecodeWriter::outputValueSymbolTable(const ValueSymbolTable &VST) {
Reid Spencer78d033e2007-01-06 07:24:44 +00001173 // Do not output the Bytecode block for an empty symbol table, it just wastes
1174 // space!
Reid Spenceref9b9a72007-02-05 20:47:22 +00001175 if (VST.empty()) return;
Reid Spencer78d033e2007-01-06 07:24:44 +00001176
1177 BytecodeBlock SymTabBlock(BytecodeFormat::ValueSymbolTableBlockID, *this,
1178 true/*ElideIfEmpty*/);
Reid Spencer94f2df22004-05-25 17:29:59 +00001179
Reid Spenceref9b9a72007-02-05 20:47:22 +00001180 // Organize the symbol table by type
Chris Lattnerdec628e2007-02-12 05:18:08 +00001181 typedef SmallVector<const ValueName*, 8> PlaneMapVector;
Reid Spencer91ac04a2007-04-09 06:14:31 +00001182 typedef DenseMap<const Type*, PlaneMapVector> PlaneMap;
Reid Spenceref9b9a72007-02-05 20:47:22 +00001183 PlaneMap Planes;
1184 for (ValueSymbolTable::const_iterator SI = VST.begin(), SE = VST.end();
1185 SI != SE; ++SI)
Chris Lattnerdec628e2007-02-12 05:18:08 +00001186 Planes[SI->getValue()->getType()].push_back(&*SI);
Reid Spenceref9b9a72007-02-05 20:47:22 +00001187
Chris Lattnerae052aa2007-02-10 07:31:44 +00001188 for (PlaneMap::iterator PI = Planes.begin(), PE = Planes.end();
Reid Spenceref9b9a72007-02-05 20:47:22 +00001189 PI != PE; ++PI) {
Reid Spenceref9b9a72007-02-05 20:47:22 +00001190 PlaneMapVector::const_iterator I = PI->second.begin();
1191 PlaneMapVector::const_iterator End = PI->second.end();
1192
Chris Lattner00950542001-06-06 20:29:01 +00001193 if (I == End) continue; // Don't mess with an absent type...
1194
Reid Spencer250c4182004-08-17 02:59:02 +00001195 // Write the number of values in this plane
Chris Lattner001d16a2005-03-07 02:59:36 +00001196 output_vbr((unsigned)PI->second.size());
Chris Lattner00950542001-06-06 20:29:01 +00001197
Reid Spencer250c4182004-08-17 02:59:02 +00001198 // Write the slot number of the type for this plane
Chris Lattner972b4dc2007-02-10 05:17:48 +00001199 output_typeid(Table.getTypeSlot(PI->first));
Chris Lattner00950542001-06-06 20:29:01 +00001200
Reid Spencer250c4182004-08-17 02:59:02 +00001201 // Write each of the values in this plane
Chris Lattner7fc9fe32001-06-27 23:41:11 +00001202 for (; I != End; ++I) {
Chris Lattner00950542001-06-06 20:29:01 +00001203 // Symtab entry: [def slot #][name]
Chris Lattnerdec628e2007-02-12 05:18:08 +00001204 output_vbr(Table.getSlot((*I)->getValue()));
1205 output_str((*I)->getKeyData(), (*I)->getKeyLength());
Chris Lattner00950542001-06-06 20:29:01 +00001206 }
1207 }
1208}
1209
Bill Wendlinge8156192006-12-07 01:30:32 +00001210void llvm::WriteBytecodeToFile(const Module *M, OStream &Out,
Chris Lattnerc847f7c2006-07-28 22:07:54 +00001211 bool compress) {
Reid Spencerad89bd62004-07-25 18:07:36 +00001212 assert(M && "You can't write a null module!!");
Chris Lattner00950542001-06-06 20:29:01 +00001213
Reid Spencer32f55532006-06-07 23:18:34 +00001214 // Make sure that std::cout is put into binary mode for systems
1215 // that care.
Bill Wendlinge8156192006-12-07 01:30:32 +00001216 if (Out == cout)
Reid Spencer32f55532006-06-07 23:18:34 +00001217 sys::Program::ChangeStdoutToBinary();
1218
Reid Spencer17f52c52004-11-06 23:17:23 +00001219 // Create a vector of unsigned char for the bytecode output. We
1220 // reserve 256KBytes of space in the vector so that we avoid doing
1221 // lots of little allocations. 256KBytes is sufficient for a large
1222 // proportion of the bytecode files we will encounter. Larger files
1223 // will be automatically doubled in size as needed (std::vector
1224 // behavior).
Reid Spencerad89bd62004-07-25 18:07:36 +00001225 std::vector<unsigned char> Buffer;
Reid Spencer17f52c52004-11-06 23:17:23 +00001226 Buffer.reserve(256 * 1024);
Chris Lattner00950542001-06-06 20:29:01 +00001227
Reid Spencer17f52c52004-11-06 23:17:23 +00001228 // The BytecodeWriter populates Buffer for us.
Reid Spencerad89bd62004-07-25 18:07:36 +00001229 BytecodeWriter BCW(Buffer, M);
Chris Lattner00950542001-06-06 20:29:01 +00001230
Reid Spencer17f52c52004-11-06 23:17:23 +00001231 // Keep track of how much we've written
Chris Lattnerce6ef112002-07-26 18:40:14 +00001232 BytesWritten += Buffer.size();
1233
Reid Spencer17f52c52004-11-06 23:17:23 +00001234 // Determine start and end points of the Buffer
Reid Spencer83296f52004-11-07 18:17:38 +00001235 const unsigned char *FirstByte = &Buffer.front();
Reid Spencer17f52c52004-11-06 23:17:23 +00001236
1237 // If we're supposed to compress this mess ...
1238 if (compress) {
1239
1240 // We signal compression by using an alternate magic number for the
Reid Spencer83296f52004-11-07 18:17:38 +00001241 // file. The compressed bytecode file's magic number is "llvc" instead
Misha Brukman23c6d2c2005-04-21 21:48:46 +00001242 // of "llvm".
Reid Spencer83296f52004-11-07 18:17:38 +00001243 char compressed_magic[4];
1244 compressed_magic[0] = 'l';
1245 compressed_magic[1] = 'l';
1246 compressed_magic[2] = 'v';
1247 compressed_magic[3] = 'c';
Reid Spencer17f52c52004-11-06 23:17:23 +00001248
Bill Wendling68fe61d2006-11-29 00:19:40 +00001249 Out.stream()->write(compressed_magic,4);
Reid Spencer17f52c52004-11-06 23:17:23 +00001250
Reid Spencera70d84d2004-11-14 22:01:41 +00001251 // Compress everything after the magic number (which we altered)
Reid Spencer3ed469c2006-11-02 20:25:50 +00001252 Compressor::compressToStream(
Reid Spencer17f52c52004-11-06 23:17:23 +00001253 (char*)(FirstByte+4), // Skip the magic number
1254 Buffer.size()-4, // Skip the magic number
Bill Wendling68fe61d2006-11-29 00:19:40 +00001255 *Out.stream() // Where to write compressed data
Reid Spencer17f52c52004-11-06 23:17:23 +00001256 );
1257
Reid Spencer17f52c52004-11-06 23:17:23 +00001258 } else {
1259
1260 // We're not compressing, so just write the entire block.
Bill Wendling68fe61d2006-11-29 00:19:40 +00001261 Out.stream()->write((char*)FirstByte, Buffer.size());
Chris Lattnere8fdde12001-09-07 16:39:41 +00001262 }
Reid Spencer17f52c52004-11-06 23:17:23 +00001263
1264 // make sure it hits disk now
Bill Wendling68fe61d2006-11-29 00:19:40 +00001265 Out.stream()->flush();
Chris Lattner00950542001-06-06 20:29:01 +00001266}