1 //===-- Writer.cpp - Library for writing LLVM bytecode files --------------===//
3 // The LLVM Compiler Infrastructure
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.
8 //===----------------------------------------------------------------------===//
10 // This library implements the functionality defined in llvm/Bytecode/Writer.h
12 // Note that this file uses an unusual technique of outputting all the bytecode
13 // to a vector of unsigned char, then copies the vector to an ostream. The
14 // 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. :( :( :(
18 //===----------------------------------------------------------------------===//
20 #include "WriterInternals.h"
21 #include "llvm/Bytecode/WriteBytecodePass.h"
22 #include "llvm/Constants.h"
23 #include "llvm/DerivedTypes.h"
24 #include "llvm/Instructions.h"
25 #include "llvm/Module.h"
26 #include "llvm/SymbolTable.h"
27 #include "llvm/Support/GetElementPtrTypeIterator.h"
28 #include "Support/STLExtras.h"
29 #include "Support/Statistic.h"
34 /// This value needs to be incremented every time the bytecode format changes
35 /// so that the reader can distinguish which format of the bytecode file has
37 /// @brief The bytecode version number
38 const unsigned BCVersionNum = 4;
40 static RegisterPass<WriteBytecodePass> X("emitbytecode", "Bytecode Writer");
43 BytesWritten("bytecodewriter", "Number of bytecode bytes written");
45 //===----------------------------------------------------------------------===//
46 //=== Output Primitives ===//
47 //===----------------------------------------------------------------------===//
49 // output - If a position is specified, it must be in the valid portion of the
50 // string... note that this should be inlined always so only the relevant IF
51 // body should be included.
52 inline void BytecodeWriter::output(unsigned i, int pos) {
53 if (pos == -1) { // Be endian clean, little endian is our friend
54 Out.push_back((unsigned char)i);
55 Out.push_back((unsigned char)(i >> 8));
56 Out.push_back((unsigned char)(i >> 16));
57 Out.push_back((unsigned char)(i >> 24));
59 Out[pos ] = (unsigned char)i;
60 Out[pos+1] = (unsigned char)(i >> 8);
61 Out[pos+2] = (unsigned char)(i >> 16);
62 Out[pos+3] = (unsigned char)(i >> 24);
66 inline void BytecodeWriter::output(int i) {
70 /// output_vbr - Output an unsigned value, by using the least number of bytes
71 /// possible. This is useful because many of our "infinite" values are really
72 /// very small most of the time; but can be large a few times.
73 /// Data format used: If you read a byte with the high bit set, use the low
74 /// seven bits as data and then read another byte.
75 inline void BytecodeWriter::output_vbr(uint64_t i) {
77 if (i < 0x80) { // done?
78 Out.push_back((unsigned char)i); // We know the high bit is clear...
82 // Nope, we are bigger than a character, output the next 7 bits and set the
83 // high bit to say that there is more coming...
84 Out.push_back(0x80 | ((unsigned char)i & 0x7F));
85 i >>= 7; // Shift out 7 bits now...
89 inline void BytecodeWriter::output_vbr(unsigned i) {
91 if (i < 0x80) { // done?
92 Out.push_back((unsigned char)i); // We know the high bit is clear...
96 // Nope, we are bigger than a character, output the next 7 bits and set the
97 // high bit to say that there is more coming...
98 Out.push_back(0x80 | ((unsigned char)i & 0x7F));
99 i >>= 7; // Shift out 7 bits now...
103 inline void BytecodeWriter::output_typeid(unsigned i) {
107 this->output_vbr(0x00FFFFFF);
112 inline void BytecodeWriter::output_vbr(int64_t i) {
114 output_vbr(((uint64_t)(-i) << 1) | 1); // Set low order sign bit...
116 output_vbr((uint64_t)i << 1); // Low order bit is clear.
120 inline void BytecodeWriter::output_vbr(int i) {
122 output_vbr(((unsigned)(-i) << 1) | 1); // Set low order sign bit...
124 output_vbr((unsigned)i << 1); // Low order bit is clear.
127 inline void BytecodeWriter::output(const std::string &s) {
128 unsigned Len = s.length();
129 output_vbr(Len ); // Strings may have an arbitrary length...
130 Out.insert(Out.end(), s.begin(), s.end());
133 inline void BytecodeWriter::output_data(const void *Ptr, const void *End) {
134 Out.insert(Out.end(), (const unsigned char*)Ptr, (const unsigned char*)End);
137 inline void BytecodeWriter::output_float(float& FloatVal) {
138 /// FIXME: This isn't optimal, it has size problems on some platforms
139 /// where FP is not IEEE.
144 FloatUnion.f = FloatVal;
145 Out.push_back( static_cast<unsigned char>( (FloatUnion.i & 0xFF )));
146 Out.push_back( static_cast<unsigned char>( (FloatUnion.i >> 8) & 0xFF));
147 Out.push_back( static_cast<unsigned char>( (FloatUnion.i >> 16) & 0xFF));
148 Out.push_back( static_cast<unsigned char>( (FloatUnion.i >> 24) & 0xFF));
151 inline void BytecodeWriter::output_double(double& DoubleVal) {
152 /// FIXME: This isn't optimal, it has size problems on some platforms
153 /// where FP is not IEEE.
158 DoubleUnion.d = DoubleVal;
159 Out.push_back( static_cast<unsigned char>( (DoubleUnion.i & 0xFF )));
160 Out.push_back( static_cast<unsigned char>( (DoubleUnion.i >> 8) & 0xFF));
161 Out.push_back( static_cast<unsigned char>( (DoubleUnion.i >> 16) & 0xFF));
162 Out.push_back( static_cast<unsigned char>( (DoubleUnion.i >> 24) & 0xFF));
163 Out.push_back( static_cast<unsigned char>( (DoubleUnion.i >> 32) & 0xFF));
164 Out.push_back( static_cast<unsigned char>( (DoubleUnion.i >> 40) & 0xFF));
165 Out.push_back( static_cast<unsigned char>( (DoubleUnion.i >> 48) & 0xFF));
166 Out.push_back( static_cast<unsigned char>( (DoubleUnion.i >> 56) & 0xFF));
169 inline BytecodeBlock::BytecodeBlock(unsigned ID, BytecodeWriter& w,
170 bool elideIfEmpty, bool hasLongFormat )
171 : Id(ID), Writer(w), ElideIfEmpty(elideIfEmpty), HasLongFormat(hasLongFormat){
175 w.output(0U); // For length in long format
177 w.output(0U); /// Place holder for ID and length for this block
182 inline BytecodeBlock::~BytecodeBlock() { // Do backpatch when block goes out
184 if (Loc == Writer.size() && ElideIfEmpty) {
185 // If the block is empty, and we are allowed to, do not emit the block at
187 Writer.resize(Writer.size()-(HasLongFormat?8:4));
191 //cerr << "OldLoc = " << Loc << " NewLoc = " << NewLoc << " diff = "
192 // << (NewLoc-Loc) << endl;
194 Writer.output(unsigned(Writer.size()-Loc), int(Loc-4));
196 Writer.output(unsigned(Writer.size()-Loc) << 5 | (Id & 0x1F), int(Loc-4));
199 //===----------------------------------------------------------------------===//
200 //=== Constant Output ===//
201 //===----------------------------------------------------------------------===//
203 void BytecodeWriter::outputType(const Type *T) {
204 output_vbr((unsigned)T->getTypeID());
206 // That's all there is to handling primitive types...
207 if (T->isPrimitiveType()) {
208 return; // We might do this if we alias a prim type: %x = type int
211 switch (T->getTypeID()) { // Handle derived types now.
212 case Type::FunctionTyID: {
213 const FunctionType *MT = cast<FunctionType>(T);
214 int Slot = Table.getSlot(MT->getReturnType());
215 assert(Slot != -1 && "Type used but not available!!");
216 output_typeid((unsigned)Slot);
218 // Output the number of arguments to function (+1 if varargs):
219 output_vbr((unsigned)MT->getNumParams()+MT->isVarArg());
221 // Output all of the arguments...
222 FunctionType::param_iterator I = MT->param_begin();
223 for (; I != MT->param_end(); ++I) {
224 Slot = Table.getSlot(*I);
225 assert(Slot != -1 && "Type used but not available!!");
226 output_typeid((unsigned)Slot);
229 // Terminate list with VoidTy if we are a varargs function...
231 output_typeid((unsigned)Type::VoidTyID);
235 case Type::ArrayTyID: {
236 const ArrayType *AT = cast<ArrayType>(T);
237 int Slot = Table.getSlot(AT->getElementType());
238 assert(Slot != -1 && "Type used but not available!!");
239 output_typeid((unsigned)Slot);
240 //std::cerr << "Type slot = " << Slot << " Type = " << T->getName() << endl;
242 output_vbr(AT->getNumElements());
246 case Type::PackedTyID: {
247 const PackedType *PT = cast<PackedType>(T);
248 int Slot = Table.getSlot(PT->getElementType());
249 assert(Slot != -1 && "Type used but not available!!");
250 output_typeid((unsigned)Slot);
251 output_vbr(PT->getNumElements());
256 case Type::StructTyID: {
257 const StructType *ST = cast<StructType>(T);
259 // Output all of the element types...
260 for (StructType::element_iterator I = ST->element_begin(),
261 E = ST->element_end(); I != E; ++I) {
262 int Slot = Table.getSlot(*I);
263 assert(Slot != -1 && "Type used but not available!!");
264 output_typeid((unsigned)Slot);
267 // Terminate list with VoidTy
268 output_typeid((unsigned)Type::VoidTyID);
272 case Type::PointerTyID: {
273 const PointerType *PT = cast<PointerType>(T);
274 int Slot = Table.getSlot(PT->getElementType());
275 assert(Slot != -1 && "Type used but not available!!");
276 output_typeid((unsigned)Slot);
280 case Type::OpaqueTyID: {
281 // No need to emit anything, just the count of opaque types is enough.
285 //case Type::PackedTyID:
287 std::cerr << __FILE__ << ":" << __LINE__ << ": Don't know how to serialize"
288 << " Type '" << T->getDescription() << "'\n";
293 void BytecodeWriter::outputConstant(const Constant *CPV) {
294 assert((CPV->getType()->isPrimitiveType() || !CPV->isNullValue()) &&
295 "Shouldn't output null constants!");
297 // We must check for a ConstantExpr before switching by type because
298 // a ConstantExpr can be of any type, and has no explicit value.
300 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CPV)) {
301 // FIXME: Encoding of constant exprs could be much more compact!
302 assert(CE->getNumOperands() > 0 && "ConstantExpr with 0 operands");
303 output_vbr(CE->getNumOperands()); // flags as an expr
304 output_vbr(CE->getOpcode()); // flags as an expr
306 for (User::const_op_iterator OI = CE->op_begin(); OI != CE->op_end(); ++OI){
307 int Slot = Table.getSlot(*OI);
308 assert(Slot != -1 && "Unknown constant used in ConstantExpr!!");
309 output_vbr((unsigned)Slot);
310 Slot = Table.getSlot((*OI)->getType());
311 output_typeid((unsigned)Slot);
315 output_vbr(0U); // flag as not a ConstantExpr
318 switch (CPV->getType()->getTypeID()) {
319 case Type::BoolTyID: // Boolean Types
320 if (cast<ConstantBool>(CPV)->getValue())
326 case Type::UByteTyID: // Unsigned integer types...
327 case Type::UShortTyID:
329 case Type::ULongTyID:
330 output_vbr(cast<ConstantUInt>(CPV)->getValue());
333 case Type::SByteTyID: // Signed integer types...
334 case Type::ShortTyID:
337 output_vbr(cast<ConstantSInt>(CPV)->getValue());
340 case Type::ArrayTyID: {
341 const ConstantArray *CPA = cast<ConstantArray>(CPV);
342 assert(!CPA->isString() && "Constant strings should be handled specially!");
344 for (unsigned i = 0, e = CPA->getNumOperands(); i != e; ++i) {
345 int Slot = Table.getSlot(CPA->getOperand(i));
346 assert(Slot != -1 && "Constant used but not available!!");
347 output_vbr((unsigned)Slot);
352 case Type::PackedTyID: {
353 const ConstantPacked *CP = cast<ConstantPacked>(CPV);
355 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i) {
356 int Slot = Table.getSlot(CP->getOperand(i));
357 assert(Slot != -1 && "Constant used but not available!!");
358 output_vbr((unsigned)Slot);
363 case Type::StructTyID: {
364 const ConstantStruct *CPS = cast<ConstantStruct>(CPV);
366 for (unsigned i = 0, e = CPS->getNumOperands(); i != e; ++i) {
367 int Slot = Table.getSlot(CPS->getOperand(i));
368 assert(Slot != -1 && "Constant used but not available!!");
369 output_vbr((unsigned)Slot);
374 case Type::PointerTyID:
375 assert(0 && "No non-null, non-constant-expr constants allowed!");
378 case Type::FloatTyID: { // Floating point types...
379 float Tmp = (float)cast<ConstantFP>(CPV)->getValue();
383 case Type::DoubleTyID: {
384 double Tmp = cast<ConstantFP>(CPV)->getValue();
390 case Type::LabelTyID:
392 std::cerr << __FILE__ << ":" << __LINE__ << ": Don't know how to serialize"
393 << " type '" << *CPV->getType() << "'\n";
399 void BytecodeWriter::outputConstantStrings() {
400 SlotCalculator::string_iterator I = Table.string_begin();
401 SlotCalculator::string_iterator E = Table.string_end();
402 if (I == E) return; // No strings to emit
404 // If we have != 0 strings to emit, output them now. Strings are emitted into
405 // the 'void' type plane.
406 output_vbr(unsigned(E-I));
407 output_typeid(Type::VoidTyID);
409 // Emit all of the strings.
410 for (I = Table.string_begin(); I != E; ++I) {
411 const ConstantArray *Str = *I;
412 int Slot = Table.getSlot(Str->getType());
413 assert(Slot != -1 && "Constant string of unknown type?");
414 output_typeid((unsigned)Slot);
416 // Now that we emitted the type (which indicates the size of the string),
417 // emit all of the characters.
418 std::string Val = Str->getAsString();
419 output_data(Val.c_str(), Val.c_str()+Val.size());
423 //===----------------------------------------------------------------------===//
424 //=== Instruction Output ===//
425 //===----------------------------------------------------------------------===//
426 typedef unsigned char uchar;
428 // outputInstructionFormat0 - Output those wierd instructions that have a large
429 // number of operands or have large operands themselves...
431 // Format: [opcode] [type] [numargs] [arg0] [arg1] ... [arg<numargs-1>]
433 void BytecodeWriter::outputInstructionFormat0(const Instruction *I, unsigned Opcode,
434 const SlotCalculator &Table,
436 // Opcode must have top two bits clear...
437 output_vbr(Opcode << 2); // Instruction Opcode ID
438 output_typeid(Type); // Result type
440 unsigned NumArgs = I->getNumOperands();
441 output_vbr(NumArgs + (isa<CastInst>(I) || isa<VANextInst>(I) ||
444 if (!isa<GetElementPtrInst>(&I)) {
445 for (unsigned i = 0; i < NumArgs; ++i) {
446 int Slot = Table.getSlot(I->getOperand(i));
447 assert(Slot >= 0 && "No slot number for value!?!?");
448 output_vbr((unsigned)Slot);
451 if (isa<CastInst>(I) || isa<VAArgInst>(I)) {
452 int Slot = Table.getSlot(I->getType());
453 assert(Slot != -1 && "Cast return type unknown?");
454 output_typeid((unsigned)Slot);
455 } else if (const VANextInst *VAI = dyn_cast<VANextInst>(I)) {
456 int Slot = Table.getSlot(VAI->getArgType());
457 assert(Slot != -1 && "VarArg argument type unknown?");
458 output_typeid((unsigned)Slot);
462 int Slot = Table.getSlot(I->getOperand(0));
463 assert(Slot >= 0 && "No slot number for value!?!?");
464 output_vbr(unsigned(Slot));
466 // We need to encode the type of sequential type indices into their slot #
468 for (gep_type_iterator TI = gep_type_begin(I), E = gep_type_end(I);
469 Idx != NumArgs; ++TI, ++Idx) {
470 Slot = Table.getSlot(I->getOperand(Idx));
471 assert(Slot >= 0 && "No slot number for value!?!?");
473 if (isa<SequentialType>(*TI)) {
475 switch (I->getOperand(Idx)->getType()->getTypeID()) {
476 default: assert(0 && "Unknown index type!");
477 case Type::UIntTyID: IdxId = 0; break;
478 case Type::IntTyID: IdxId = 1; break;
479 case Type::ULongTyID: IdxId = 2; break;
480 case Type::LongTyID: IdxId = 3; break;
482 Slot = (Slot << 2) | IdxId;
484 output_vbr(unsigned(Slot));
490 // outputInstrVarArgsCall - Output the absurdly annoying varargs function calls.
491 // This are more annoying than most because the signature of the call does not
492 // tell us anything about the types of the arguments in the varargs portion.
493 // Because of this, we encode (as type 0) all of the argument types explicitly
494 // before the argument value. This really sucks, but you shouldn't be using
495 // varargs functions in your code! *death to printf*!
497 // Format: [opcode] [type] [numargs] [arg0] [arg1] ... [arg<numargs-1>]
499 void BytecodeWriter::outputInstrVarArgsCall(const Instruction *I,
501 const SlotCalculator &Table,
503 assert(isa<CallInst>(I) || isa<InvokeInst>(I));
504 // Opcode must have top two bits clear...
505 output_vbr(Opcode << 2); // Instruction Opcode ID
506 output_typeid(Type); // Result type (varargs type)
508 const PointerType *PTy = cast<PointerType>(I->getOperand(0)->getType());
509 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
510 unsigned NumParams = FTy->getNumParams();
512 unsigned NumFixedOperands;
513 if (isa<CallInst>(I)) {
514 // Output an operand for the callee and each fixed argument, then two for
515 // each variable argument.
516 NumFixedOperands = 1+NumParams;
518 assert(isa<InvokeInst>(I) && "Not call or invoke??");
519 // Output an operand for the callee and destinations, then two for each
520 // variable argument.
521 NumFixedOperands = 3+NumParams;
523 output_vbr(2 * I->getNumOperands()-NumFixedOperands);
525 // The type for the function has already been emitted in the type field of the
526 // instruction. Just emit the slot # now.
527 for (unsigned i = 0; i != NumFixedOperands; ++i) {
528 int Slot = Table.getSlot(I->getOperand(i));
529 assert(Slot >= 0 && "No slot number for value!?!?");
530 output_vbr((unsigned)Slot);
533 for (unsigned i = NumFixedOperands, e = I->getNumOperands(); i != e; ++i) {
534 // Output Arg Type ID
535 int Slot = Table.getSlot(I->getOperand(i)->getType());
536 assert(Slot >= 0 && "No slot number for value!?!?");
537 output_typeid((unsigned)Slot);
539 // Output arg ID itself
540 Slot = Table.getSlot(I->getOperand(i));
541 assert(Slot >= 0 && "No slot number for value!?!?");
542 output_vbr((unsigned)Slot);
547 // outputInstructionFormat1 - Output one operand instructions, knowing that no
548 // operand index is >= 2^12.
550 inline void BytecodeWriter::outputInstructionFormat1(const Instruction *I,
554 // bits Instruction format:
555 // --------------------------
556 // 01-00: Opcode type, fixed to 1.
558 // 19-08: Resulting type plane
559 // 31-20: Operand #1 (if set to (2^12-1), then zero operands)
561 unsigned Bits = 1 | (Opcode << 2) | (Type << 8) | (Slots[0] << 20);
562 // cerr << "1 " << IType << " " << Type << " " << Slots[0] << endl;
567 // outputInstructionFormat2 - Output two operand instructions, knowing that no
568 // operand index is >= 2^8.
570 inline void BytecodeWriter::outputInstructionFormat2(const Instruction *I,
574 // bits Instruction format:
575 // --------------------------
576 // 01-00: Opcode type, fixed to 2.
578 // 15-08: Resulting type plane
582 unsigned Bits = 2 | (Opcode << 2) | (Type << 8) |
583 (Slots[0] << 16) | (Slots[1] << 24);
584 // cerr << "2 " << IType << " " << Type << " " << Slots[0] << " "
585 // << Slots[1] << endl;
590 // outputInstructionFormat3 - Output three operand instructions, knowing that no
591 // operand index is >= 2^6.
593 inline void BytecodeWriter::outputInstructionFormat3(const Instruction *I,
597 // bits Instruction format:
598 // --------------------------
599 // 01-00: Opcode type, fixed to 3.
601 // 13-08: Resulting type plane
606 unsigned Bits = 3 | (Opcode << 2) | (Type << 8) |
607 (Slots[0] << 14) | (Slots[1] << 20) | (Slots[2] << 26);
608 //cerr << "3 " << IType << " " << Type << " " << Slots[0] << " "
609 // << Slots[1] << " " << Slots[2] << endl;
613 void BytecodeWriter::outputInstruction(const Instruction &I) {
614 assert(I.getOpcode() < 62 && "Opcode too big???");
615 unsigned Opcode = I.getOpcode();
616 unsigned NumOperands = I.getNumOperands();
618 // Encode 'volatile load' as 62 and 'volatile store' as 63.
619 if (isa<LoadInst>(I) && cast<LoadInst>(I).isVolatile())
621 if (isa<StoreInst>(I) && cast<StoreInst>(I).isVolatile())
624 // Figure out which type to encode with the instruction. Typically we want
625 // the type of the first parameter, as opposed to the type of the instruction
626 // (for example, with setcc, we always know it returns bool, but the type of
627 // the first param is actually interesting). But if we have no arguments
628 // we take the type of the instruction itself.
631 switch (I.getOpcode()) {
632 case Instruction::Select:
633 case Instruction::Malloc:
634 case Instruction::Alloca:
635 Ty = I.getType(); // These ALWAYS want to encode the return type
637 case Instruction::Store:
638 Ty = I.getOperand(1)->getType(); // Encode the pointer type...
639 assert(isa<PointerType>(Ty) && "Store to nonpointer type!?!?");
641 default: // Otherwise use the default behavior...
642 Ty = NumOperands ? I.getOperand(0)->getType() : I.getType();
647 int Slot = Table.getSlot(Ty);
648 assert(Slot != -1 && "Type not available!!?!");
649 Type = (unsigned)Slot;
651 // Varargs calls and invokes are encoded entirely different from any other
653 if (const CallInst *CI = dyn_cast<CallInst>(&I)){
654 const PointerType *Ty =cast<PointerType>(CI->getCalledValue()->getType());
655 if (cast<FunctionType>(Ty->getElementType())->isVarArg()) {
656 outputInstrVarArgsCall(CI, Opcode, Table, Type);
659 } else if (const InvokeInst *II = dyn_cast<InvokeInst>(&I)) {
660 const PointerType *Ty =cast<PointerType>(II->getCalledValue()->getType());
661 if (cast<FunctionType>(Ty->getElementType())->isVarArg()) {
662 outputInstrVarArgsCall(II, Opcode, Table, Type);
667 if (NumOperands <= 3) {
668 // Make sure that we take the type number into consideration. We don't want
669 // to overflow the field size for the instruction format we select.
671 unsigned MaxOpSlot = Type;
672 unsigned Slots[3]; Slots[0] = (1 << 12)-1; // Marker to signify 0 operands
674 for (unsigned i = 0; i != NumOperands; ++i) {
675 int slot = Table.getSlot(I.getOperand(i));
676 assert(slot != -1 && "Broken bytecode!");
677 if (unsigned(slot) > MaxOpSlot) MaxOpSlot = unsigned(slot);
678 Slots[i] = unsigned(slot);
681 // Handle the special cases for various instructions...
682 if (isa<CastInst>(I) || isa<VAArgInst>(I)) {
683 // Cast has to encode the destination type as the second argument in the
684 // packet, or else we won't know what type to cast to!
685 Slots[1] = Table.getSlot(I.getType());
686 assert(Slots[1] != ~0U && "Cast return type unknown?");
687 if (Slots[1] > MaxOpSlot) MaxOpSlot = Slots[1];
689 } else if (const VANextInst *VANI = dyn_cast<VANextInst>(&I)) {
690 Slots[1] = Table.getSlot(VANI->getArgType());
691 assert(Slots[1] != ~0U && "va_next return type unknown?");
692 if (Slots[1] > MaxOpSlot) MaxOpSlot = Slots[1];
694 } else if (const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(&I)) {
695 // We need to encode the type of sequential type indices into their slot #
697 for (gep_type_iterator I = gep_type_begin(GEP), E = gep_type_end(GEP);
699 if (isa<SequentialType>(*I)) {
701 switch (GEP->getOperand(Idx)->getType()->getTypeID()) {
702 default: assert(0 && "Unknown index type!");
703 case Type::UIntTyID: IdxId = 0; break;
704 case Type::IntTyID: IdxId = 1; break;
705 case Type::ULongTyID: IdxId = 2; break;
706 case Type::LongTyID: IdxId = 3; break;
708 Slots[Idx] = (Slots[Idx] << 2) | IdxId;
709 if (Slots[Idx] > MaxOpSlot) MaxOpSlot = Slots[Idx];
713 // Decide which instruction encoding to use. This is determined primarily
714 // by the number of operands, and secondarily by whether or not the max
715 // operand will fit into the instruction encoding. More operands == fewer
718 switch (NumOperands) {
721 if (MaxOpSlot < (1 << 12)-1) { // -1 because we use 4095 to indicate 0 ops
722 outputInstructionFormat1(&I, Opcode, Slots, Type);
728 if (MaxOpSlot < (1 << 8)) {
729 outputInstructionFormat2(&I, Opcode, Slots, Type);
735 if (MaxOpSlot < (1 << 6)) {
736 outputInstructionFormat3(&I, Opcode, Slots, Type);
745 // If we weren't handled before here, we either have a large number of
746 // operands or a large operand index that we are referring to.
747 outputInstructionFormat0(&I, Opcode, Table, Type);
750 //===----------------------------------------------------------------------===//
751 //=== Block Output ===//
752 //===----------------------------------------------------------------------===//
754 BytecodeWriter::BytecodeWriter(std::vector<unsigned char> &o, const Module *M)
757 // Emit the signature...
758 static const unsigned char *Sig = (const unsigned char*)"llvm";
759 output_data(Sig, Sig+4);
761 // Emit the top level CLASS block.
762 BytecodeBlock ModuleBlock(BytecodeFormat::ModuleBlockID, *this, false, true);
764 bool isBigEndian = M->getEndianness() == Module::BigEndian;
765 bool hasLongPointers = M->getPointerSize() == Module::Pointer64;
766 bool hasNoEndianness = M->getEndianness() == Module::AnyEndianness;
767 bool hasNoPointerSize = M->getPointerSize() == Module::AnyPointerSize;
769 // Output the version identifier... we are currently on bytecode version #2,
770 // which corresponds to LLVM v1.3.
771 unsigned Version = (BCVersionNum << 4) |
772 (unsigned)isBigEndian | (hasLongPointers << 1) |
773 (hasNoEndianness << 2) |
774 (hasNoPointerSize << 3);
777 // The Global type plane comes first
779 BytecodeBlock CPool(BytecodeFormat::GlobalTypePlaneBlockID, *this );
780 outputTypes(Type::FirstDerivedTyID);
783 // The ModuleInfoBlock follows directly after the type information
784 outputModuleInfoBlock(M);
786 // Output module level constants, used for global variable initializers
787 outputConstants(false);
789 // Do the whole module now! Process each function at a time...
790 for (Module::const_iterator I = M->begin(), E = M->end(); I != E; ++I)
793 // If needed, output the symbol table for the module...
794 outputSymbolTable(M->getSymbolTable());
797 void BytecodeWriter::outputTypes(unsigned TypeNum)
799 // Write the type plane for types first because earlier planes (e.g. for a
800 // primitive type like float) may have constants constructed using types
801 // coming later (e.g., via getelementptr from a pointer type). The type
802 // plane is needed before types can be fwd or bkwd referenced.
803 const std::vector<const Type*>& Types = Table.getTypes();
804 assert(!Types.empty() && "No types at all?");
805 assert(TypeNum <= Types.size() && "Invalid TypeNo index");
807 unsigned NumEntries = Types.size() - TypeNum;
809 // Output type header: [num entries]
810 output_vbr(NumEntries);
812 for (unsigned i = TypeNum; i < TypeNum+NumEntries; ++i)
813 outputType(Types[i]);
816 // Helper function for outputConstants().
817 // Writes out all the constants in the plane Plane starting at entry StartNo.
819 void BytecodeWriter::outputConstantsInPlane(const std::vector<const Value*>
820 &Plane, unsigned StartNo) {
821 unsigned ValNo = StartNo;
823 // Scan through and ignore function arguments, global values, and constant
825 for (; ValNo < Plane.size() &&
826 (isa<Argument>(Plane[ValNo]) || isa<GlobalValue>(Plane[ValNo]) ||
827 (isa<ConstantArray>(Plane[ValNo]) &&
828 cast<ConstantArray>(Plane[ValNo])->isString())); ValNo++)
831 unsigned NC = ValNo; // Number of constants
832 for (; NC < Plane.size() && (isa<Constant>(Plane[NC])); NC++)
834 NC -= ValNo; // Convert from index into count
835 if (NC == 0) return; // Skip empty type planes...
837 // FIXME: Most slabs only have 1 or 2 entries! We should encode this much
840 // Output type header: [num entries][type id number]
844 // Output the Type ID Number...
845 int Slot = Table.getSlot(Plane.front()->getType());
846 assert (Slot != -1 && "Type in constant pool but not in function!!");
847 output_typeid((unsigned)Slot);
849 for (unsigned i = ValNo; i < ValNo+NC; ++i) {
850 const Value *V = Plane[i];
851 if (const Constant *C = dyn_cast<Constant>(V)) {
857 static inline bool hasNullValue(unsigned TyID) {
858 return TyID != Type::LabelTyID && TyID != Type::VoidTyID;
861 void BytecodeWriter::outputConstants(bool isFunction) {
862 BytecodeBlock CPool(BytecodeFormat::ConstantPoolBlockID, *this,
863 true /* Elide block if empty */);
865 unsigned NumPlanes = Table.getNumPlanes();
868 // Output the type plane before any constants!
869 outputTypes( Table.getModuleTypeLevel() );
871 // Output module-level string constants before any other constants.x
872 outputConstantStrings();
874 for (unsigned pno = 0; pno != NumPlanes; pno++) {
875 const std::vector<const Value*> &Plane = Table.getPlane(pno);
876 if (!Plane.empty()) { // Skip empty type planes...
878 if (isFunction) // Don't re-emit module constants
879 ValNo += Table.getModuleLevel(pno);
881 if (hasNullValue(pno)) {
882 // Skip zero initializer
887 // Write out constants in the plane
888 outputConstantsInPlane(Plane, ValNo);
893 static unsigned getEncodedLinkage(const GlobalValue *GV) {
894 switch (GV->getLinkage()) {
895 default: assert(0 && "Invalid linkage!");
896 case GlobalValue::ExternalLinkage: return 0;
897 case GlobalValue::WeakLinkage: return 1;
898 case GlobalValue::AppendingLinkage: return 2;
899 case GlobalValue::InternalLinkage: return 3;
900 case GlobalValue::LinkOnceLinkage: return 4;
904 void BytecodeWriter::outputModuleInfoBlock(const Module *M) {
905 BytecodeBlock ModuleInfoBlock(BytecodeFormat::ModuleGlobalInfoBlockID, *this);
907 // Output the types for the global variables in the module...
908 for (Module::const_giterator I = M->gbegin(), End = M->gend(); I != End;++I) {
909 int Slot = Table.getSlot(I->getType());
910 assert(Slot != -1 && "Module global vars is broken!");
912 // Fields: bit0 = isConstant, bit1 = hasInitializer, bit2-4=Linkage,
913 // bit5+ = Slot # for type
914 unsigned oSlot = ((unsigned)Slot << 5) | (getEncodedLinkage(I) << 2) |
915 (I->hasInitializer() << 1) | (unsigned)I->isConstant();
918 // If we have an initializer, output it now.
919 if (I->hasInitializer()) {
920 Slot = Table.getSlot((Value*)I->getInitializer());
921 assert(Slot != -1 && "No slot for global var initializer!");
922 output_vbr((unsigned)Slot);
925 output_typeid((unsigned)Table.getSlot(Type::VoidTy));
927 // Output the types of the functions in this module...
928 for (Module::const_iterator I = M->begin(), End = M->end(); I != End; ++I) {
929 int Slot = Table.getSlot(I->getType());
930 assert(Slot != -1 && "Module const pool is broken!");
931 assert(Slot >= Type::FirstDerivedTyID && "Derived type not in range!");
932 output_typeid((unsigned)Slot);
934 output_typeid((unsigned)Table.getSlot(Type::VoidTy));
936 // Put out the list of dependent libraries for the Module
937 Module::lib_iterator LI = M->lib_begin();
938 Module::lib_iterator LE = M->lib_end();
939 output_vbr( unsigned(LE - LI) ); // Put out the number of dependent libraries
940 for ( ; LI != LE; ++LI ) {
944 // Output the target triple from the module
945 output(M->getTargetTriple());
948 void BytecodeWriter::outputInstructions(const Function *F) {
949 BytecodeBlock ILBlock(BytecodeFormat::InstructionListBlockID, *this);
950 for (Function::const_iterator BB = F->begin(), E = F->end(); BB != E; ++BB)
951 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I!=E; ++I)
952 outputInstruction(*I);
955 void BytecodeWriter::outputFunction(const Function *F) {
956 BytecodeBlock FunctionBlock(BytecodeFormat::FunctionBlockID, *this);
957 output_vbr(getEncodedLinkage(F));
959 // If this is an external function, there is nothing else to emit!
960 if (F->isExternal()) return;
962 // Get slot information about the function...
963 Table.incorporateFunction(F);
965 if (Table.getCompactionTable().empty()) {
966 // Output information about the constants in the function if the compaction
967 // table is not being used.
968 outputConstants(true);
970 // Otherwise, emit the compaction table.
971 outputCompactionTable();
974 // Output all of the instructions in the body of the function
975 outputInstructions(F);
977 // If needed, output the symbol table for the function...
978 outputSymbolTable(F->getSymbolTable());
980 Table.purgeFunction();
983 void BytecodeWriter::outputCompactionTablePlane(unsigned PlaneNo,
984 const std::vector<const Value*> &Plane,
986 unsigned End = Table.getModuleLevel(PlaneNo);
987 if (Plane.empty() || StartNo == End || End == 0) return; // Nothing to emit
988 assert(StartNo < End && "Cannot emit negative range!");
989 assert(StartNo < Plane.size() && End <= Plane.size());
991 // Do not emit the null initializer!
994 // Figure out which encoding to use. By far the most common case we have is
995 // to emit 0-2 entries in a compaction table plane.
996 switch (End-StartNo) {
997 case 0: // Avoid emitting two vbr's if possible.
1000 output_vbr((PlaneNo << 2) | End-StartNo);
1003 // Output the number of things.
1004 output_vbr((unsigned(End-StartNo) << 2) | 3);
1005 output_typeid(PlaneNo); // Emit the type plane this is
1009 for (unsigned i = StartNo; i != End; ++i)
1010 output_vbr(Table.getGlobalSlot(Plane[i]));
1013 void BytecodeWriter::outputCompactionTypes(unsigned StartNo) {
1014 // Get the compaction type table from the slot calculator
1015 const std::vector<const Type*> &CTypes = Table.getCompactionTypes();
1017 // The compaction types may have been uncompactified back to the
1018 // global types. If so, we just write an empty table
1019 if (CTypes.size() == 0 ) {
1024 assert(CTypes.size() >= StartNo && "Invalid compaction types start index");
1026 // Determine how many types to write
1027 unsigned NumTypes = CTypes.size() - StartNo;
1029 // Output the number of types.
1030 output_vbr(NumTypes);
1032 for (unsigned i = StartNo; i < StartNo+NumTypes; ++i)
1033 output_typeid(Table.getGlobalSlot(CTypes[i]));
1036 void BytecodeWriter::outputCompactionTable() {
1037 // Avoid writing the compaction table at all if there is no content.
1038 if (Table.getCompactionTypes().size() >= Type::FirstDerivedTyID ||
1039 (!Table.CompactionTableIsEmpty())) {
1040 BytecodeBlock CTB(BytecodeFormat::CompactionTableBlockID, *this,
1041 true/*ElideIfEmpty*/);
1042 const std::vector<std::vector<const Value*> > &CT =Table.getCompactionTable();
1044 // First things first, emit the type compaction table if there is one.
1045 outputCompactionTypes(Type::FirstDerivedTyID);
1047 for (unsigned i = 0, e = CT.size(); i != e; ++i)
1048 outputCompactionTablePlane(i, CT[i], 0);
1052 void BytecodeWriter::outputSymbolTable(const SymbolTable &MST) {
1053 // Do not output the Bytecode block for an empty symbol table, it just wastes
1055 if ( MST.isEmpty() ) return;
1057 BytecodeBlock SymTabBlock(BytecodeFormat::SymbolTableBlockID, *this,
1058 true/* ElideIfEmpty*/);
1060 // Write the number of types
1061 output_vbr(MST.num_types());
1063 // Write each of the types
1064 for (SymbolTable::type_const_iterator TI = MST.type_begin(),
1065 TE = MST.type_end(); TI != TE; ++TI ) {
1066 // Symtab entry:[def slot #][name]
1067 output_typeid((unsigned)Table.getSlot(TI->second));
1071 // Now do each of the type planes in order.
1072 for (SymbolTable::plane_const_iterator PI = MST.plane_begin(),
1073 PE = MST.plane_end(); PI != PE; ++PI) {
1074 SymbolTable::value_const_iterator I = MST.value_begin(PI->first);
1075 SymbolTable::value_const_iterator End = MST.value_end(PI->first);
1078 if (I == End) continue; // Don't mess with an absent type...
1080 // Write the number of values in this plane
1081 output_vbr(MST.type_size(PI->first));
1083 // Write the slot number of the type for this plane
1084 Slot = Table.getSlot(PI->first);
1085 assert(Slot != -1 && "Type in symtab, but not in table!");
1086 output_typeid((unsigned)Slot);
1088 // Write each of the values in this plane
1089 for (; I != End; ++I) {
1090 // Symtab entry: [def slot #][name]
1091 Slot = Table.getSlot(I->second);
1092 assert(Slot != -1 && "Value in symtab but has no slot number!!");
1093 output_vbr((unsigned)Slot);
1099 void llvm::WriteBytecodeToFile(const Module *M, std::ostream &Out) {
1100 assert(M && "You can't write a null module!!");
1102 std::vector<unsigned char> Buffer;
1103 Buffer.reserve(64 * 1024); // avoid lots of little reallocs
1105 // This object populates buffer for us...
1106 BytecodeWriter BCW(Buffer, M);
1108 // Keep track of how much we've written...
1109 BytesWritten += Buffer.size();
1111 // Okay, write the deque out to the ostream now... the deque is not
1112 // sequential in memory, however, so write out as much as possible in big
1113 // chunks, until we're done.
1116 std::vector<unsigned char>::const_iterator I = Buffer.begin(),E = Buffer.end();
1117 while (I != E) { // Loop until it's all written
1118 // Scan to see how big this chunk is...
1119 const unsigned char *ChunkPtr = &*I;
1120 const unsigned char *LastPtr = ChunkPtr;
1122 const unsigned char *ThisPtr = &*++I;
1123 if (++LastPtr != ThisPtr) // Advanced by more than a byte of memory?
1127 // Write out the chunk...
1128 Out.write((char*)ChunkPtr, unsigned(LastPtr-ChunkPtr));