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 #define DEBUG_TYPE "bytecodewriter"
21 #include "WriterInternals.h"
22 #include "llvm/Bytecode/WriteBytecodePass.h"
23 #include "llvm/CallingConv.h"
24 #include "llvm/Constants.h"
25 #include "llvm/DerivedTypes.h"
26 #include "llvm/InlineAsm.h"
27 #include "llvm/Instructions.h"
28 #include "llvm/Module.h"
29 #include "llvm/SymbolTable.h"
30 #include "llvm/TypeSymbolTable.h"
31 #include "llvm/Support/GetElementPtrTypeIterator.h"
32 #include "llvm/Support/Compressor.h"
33 #include "llvm/Support/MathExtras.h"
34 #include "llvm/Support/Streams.h"
35 #include "llvm/System/Program.h"
36 #include "llvm/ADT/STLExtras.h"
37 #include "llvm/ADT/Statistic.h"
42 /// This value needs to be incremented every time the bytecode format changes
43 /// so that the reader can distinguish which format of the bytecode file has
45 /// @brief The bytecode version number
46 const unsigned BCVersionNum = 7;
48 static RegisterPass<WriteBytecodePass> X("emitbytecode", "Bytecode Writer");
50 STATISTIC(BytesWritten, "Number of bytecode bytes written");
52 //===----------------------------------------------------------------------===//
53 //=== Output Primitives ===//
54 //===----------------------------------------------------------------------===//
56 // output - If a position is specified, it must be in the valid portion of the
57 // string... note that this should be inlined always so only the relevant IF
58 // body should be included.
59 inline void BytecodeWriter::output(unsigned i, int pos) {
60 if (pos == -1) { // Be endian clean, little endian is our friend
61 Out.push_back((unsigned char)i);
62 Out.push_back((unsigned char)(i >> 8));
63 Out.push_back((unsigned char)(i >> 16));
64 Out.push_back((unsigned char)(i >> 24));
66 Out[pos ] = (unsigned char)i;
67 Out[pos+1] = (unsigned char)(i >> 8);
68 Out[pos+2] = (unsigned char)(i >> 16);
69 Out[pos+3] = (unsigned char)(i >> 24);
73 inline void BytecodeWriter::output(int i) {
77 /// output_vbr - Output an unsigned value, by using the least number of bytes
78 /// possible. This is useful because many of our "infinite" values are really
79 /// very small most of the time; but can be large a few times.
80 /// Data format used: If you read a byte with the high bit set, use the low
81 /// seven bits as data and then read another byte.
82 inline void BytecodeWriter::output_vbr(uint64_t i) {
84 if (i < 0x80) { // done?
85 Out.push_back((unsigned char)i); // We know the high bit is clear...
89 // Nope, we are bigger than a character, output the next 7 bits and set the
90 // high bit to say that there is more coming...
91 Out.push_back(0x80 | ((unsigned char)i & 0x7F));
92 i >>= 7; // Shift out 7 bits now...
96 inline void BytecodeWriter::output_vbr(unsigned i) {
98 if (i < 0x80) { // done?
99 Out.push_back((unsigned char)i); // We know the high bit is clear...
103 // Nope, we are bigger than a character, output the next 7 bits and set the
104 // high bit to say that there is more coming...
105 Out.push_back(0x80 | ((unsigned char)i & 0x7F));
106 i >>= 7; // Shift out 7 bits now...
110 inline void BytecodeWriter::output_typeid(unsigned i) {
114 this->output_vbr(0x00FFFFFF);
119 inline void BytecodeWriter::output_vbr(int64_t i) {
121 output_vbr(((uint64_t)(-i) << 1) | 1); // Set low order sign bit...
123 output_vbr((uint64_t)i << 1); // Low order bit is clear.
127 inline void BytecodeWriter::output_vbr(int i) {
129 output_vbr(((unsigned)(-i) << 1) | 1); // Set low order sign bit...
131 output_vbr((unsigned)i << 1); // Low order bit is clear.
134 inline void BytecodeWriter::output(const std::string &s) {
135 unsigned Len = s.length();
136 output_vbr(Len); // Strings may have an arbitrary length.
137 Out.insert(Out.end(), s.begin(), s.end());
140 inline void BytecodeWriter::output_data(const void *Ptr, const void *End) {
141 Out.insert(Out.end(), (const unsigned char*)Ptr, (const unsigned char*)End);
144 inline void BytecodeWriter::output_float(float& FloatVal) {
145 /// FIXME: This isn't optimal, it has size problems on some platforms
146 /// where FP is not IEEE.
147 uint32_t i = FloatToBits(FloatVal);
148 Out.push_back( static_cast<unsigned char>( (i ) & 0xFF));
149 Out.push_back( static_cast<unsigned char>( (i >> 8 ) & 0xFF));
150 Out.push_back( static_cast<unsigned char>( (i >> 16) & 0xFF));
151 Out.push_back( static_cast<unsigned char>( (i >> 24) & 0xFF));
154 inline void BytecodeWriter::output_double(double& DoubleVal) {
155 /// FIXME: This isn't optimal, it has size problems on some platforms
156 /// where FP is not IEEE.
157 uint64_t i = DoubleToBits(DoubleVal);
158 Out.push_back( static_cast<unsigned char>( (i ) & 0xFF));
159 Out.push_back( static_cast<unsigned char>( (i >> 8 ) & 0xFF));
160 Out.push_back( static_cast<unsigned char>( (i >> 16) & 0xFF));
161 Out.push_back( static_cast<unsigned char>( (i >> 24) & 0xFF));
162 Out.push_back( static_cast<unsigned char>( (i >> 32) & 0xFF));
163 Out.push_back( static_cast<unsigned char>( (i >> 40) & 0xFF));
164 Out.push_back( static_cast<unsigned char>( (i >> 48) & 0xFF));
165 Out.push_back( static_cast<unsigned char>( (i >> 56) & 0xFF));
168 inline BytecodeBlock::BytecodeBlock(unsigned ID, BytecodeWriter &w,
169 bool elideIfEmpty, bool hasLongFormat)
170 : Id(ID), Writer(w), ElideIfEmpty(elideIfEmpty), HasLongFormat(hasLongFormat){
174 w.output(0U); // For length in long format
176 w.output(0U); /// Place holder for ID and length for this block
181 inline BytecodeBlock::~BytecodeBlock() { // Do backpatch when block goes out
183 if (Loc == Writer.size() && ElideIfEmpty) {
184 // If the block is empty, and we are allowed to, do not emit the block at
186 Writer.resize(Writer.size()-(HasLongFormat?8:4));
191 Writer.output(unsigned(Writer.size()-Loc), int(Loc-4));
193 Writer.output(unsigned(Writer.size()-Loc) << 5 | (Id & 0x1F), int(Loc-4));
196 //===----------------------------------------------------------------------===//
197 //=== Constant Output ===//
198 //===----------------------------------------------------------------------===//
200 void BytecodeWriter::outputType(const Type *T) {
201 const StructType* STy = dyn_cast<StructType>(T);
202 if(STy && STy->isPacked())
203 output_vbr((unsigned)Type::BC_ONLY_PackedStructTyID);
205 output_vbr((unsigned)T->getTypeID());
207 // That's all there is to handling primitive types...
208 if (T->isPrimitiveType()) {
209 return; // We might do this if we alias a prim type: %x = type int
212 switch (T->getTypeID()) { // Handle derived types now.
213 case Type::FunctionTyID: {
214 const FunctionType *MT = cast<FunctionType>(T);
215 int Slot = Table.getSlot(MT->getReturnType());
216 assert(Slot != -1 && "Type used but not available!!");
217 output_typeid((unsigned)Slot);
218 output_vbr(unsigned(MT->getParamAttrs(0)));
220 // Output the number of arguments to function (+1 if varargs):
221 output_vbr((unsigned)MT->getNumParams()+MT->isVarArg());
223 // Output all of the arguments...
224 FunctionType::param_iterator I = MT->param_begin();
226 for (; I != MT->param_end(); ++I) {
227 Slot = Table.getSlot(*I);
228 assert(Slot != -1 && "Type used but not available!!");
229 output_typeid((unsigned)Slot);
230 output_vbr(unsigned(MT->getParamAttrs(Idx)));
234 // Terminate list with VoidTy if we are a varargs function...
236 output_typeid((unsigned)Type::VoidTyID);
240 case Type::ArrayTyID: {
241 const ArrayType *AT = cast<ArrayType>(T);
242 int Slot = Table.getSlot(AT->getElementType());
243 assert(Slot != -1 && "Type used but not available!!");
244 output_typeid((unsigned)Slot);
245 output_vbr(AT->getNumElements());
249 case Type::PackedTyID: {
250 const PackedType *PT = cast<PackedType>(T);
251 int Slot = Table.getSlot(PT->getElementType());
252 assert(Slot != -1 && "Type used but not available!!");
253 output_typeid((unsigned)Slot);
254 output_vbr(PT->getNumElements());
258 case Type::StructTyID: {
259 const StructType *ST = cast<StructType>(T);
260 // Output all of the element types...
261 for (StructType::element_iterator I = ST->element_begin(),
262 E = ST->element_end(); I != E; ++I) {
263 int Slot = Table.getSlot(*I);
264 assert(Slot != -1 && "Type used but not available!!");
265 output_typeid((unsigned)Slot);
268 // Terminate list with VoidTy
269 output_typeid((unsigned)Type::VoidTyID);
273 case Type::PointerTyID: {
274 const PointerType *PT = cast<PointerType>(T);
275 int Slot = Table.getSlot(PT->getElementType());
276 assert(Slot != -1 && "Type used but not available!!");
277 output_typeid((unsigned)Slot);
281 case Type::OpaqueTyID:
282 // No need to emit anything, just the count of opaque types is enough.
286 cerr << __FILE__ << ":" << __LINE__ << ": Don't know how to serialize"
287 << " Type '" << T->getDescription() << "'\n";
292 void BytecodeWriter::outputConstant(const Constant *CPV) {
293 assert((CPV->getType()->isPrimitiveType() || !CPV->isNullValue()) &&
294 "Shouldn't output null constants!");
296 // We must check for a ConstantExpr before switching by type because
297 // a ConstantExpr can be of any type, and has no explicit value.
299 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CPV)) {
300 // FIXME: Encoding of constant exprs could be much more compact!
301 assert(CE->getNumOperands() > 0 && "ConstantExpr with 0 operands");
302 assert(CE->getNumOperands() != 1 || CE->isCast());
303 output_vbr(1+CE->getNumOperands()); // flags as an expr
304 output_vbr(CE->getOpcode()); // Put out the CE op code
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);
314 output_vbr((unsigned)CE->getPredicate());
316 } else if (isa<UndefValue>(CPV)) {
317 output_vbr(1U); // 1 -> UndefValue constant.
320 output_vbr(0U); // flag as not a ConstantExpr (i.e. 0 operands)
323 switch (CPV->getType()->getTypeID()) {
324 case Type::Int1TyID: // Boolean Types
325 if (cast<ConstantInt>(CPV)->getBoolValue())
331 case Type::Int8TyID: // Unsigned integer types...
332 case Type::Int16TyID:
333 case Type::Int32TyID:
334 case Type::Int64TyID:
335 output_vbr(cast<ConstantInt>(CPV)->getZExtValue());
338 case Type::ArrayTyID: {
339 const ConstantArray *CPA = cast<ConstantArray>(CPV);
340 assert(!CPA->isString() && "Constant strings should be handled specially!");
342 for (unsigned i = 0, e = CPA->getNumOperands(); i != e; ++i) {
343 int Slot = Table.getSlot(CPA->getOperand(i));
344 assert(Slot != -1 && "Constant used but not available!!");
345 output_vbr((unsigned)Slot);
350 case Type::PackedTyID: {
351 const ConstantPacked *CP = cast<ConstantPacked>(CPV);
353 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i) {
354 int Slot = Table.getSlot(CP->getOperand(i));
355 assert(Slot != -1 && "Constant used but not available!!");
356 output_vbr((unsigned)Slot);
361 case Type::StructTyID: {
362 const ConstantStruct *CPS = cast<ConstantStruct>(CPV);
364 for (unsigned i = 0, e = CPS->getNumOperands(); i != e; ++i) {
365 int Slot = Table.getSlot(CPS->getOperand(i));
366 assert(Slot != -1 && "Constant used but not available!!");
367 output_vbr((unsigned)Slot);
372 case Type::PointerTyID:
373 assert(0 && "No non-null, non-constant-expr constants allowed!");
376 case Type::FloatTyID: { // Floating point types...
377 float Tmp = (float)cast<ConstantFP>(CPV)->getValue();
381 case Type::DoubleTyID: {
382 double Tmp = cast<ConstantFP>(CPV)->getValue();
388 case Type::LabelTyID:
390 cerr << __FILE__ << ":" << __LINE__ << ": Don't know how to serialize"
391 << " type '" << *CPV->getType() << "'\n";
397 /// outputInlineAsm - InlineAsm's get emitted to the constant pool, so they can
398 /// be shared by multiple uses.
399 void BytecodeWriter::outputInlineAsm(const InlineAsm *IA) {
400 // Output a marker, so we know when we have one one parsing the constant pool.
401 // Note that this encoding is 5 bytes: not very efficient for a marker. Since
402 // unique inline asms are rare, this should hardly matter.
405 output(IA->getAsmString());
406 output(IA->getConstraintString());
407 output_vbr(unsigned(IA->hasSideEffects()));
410 void BytecodeWriter::outputConstantStrings() {
411 SlotCalculator::string_iterator I = Table.string_begin();
412 SlotCalculator::string_iterator E = Table.string_end();
413 if (I == E) return; // No strings to emit
415 // If we have != 0 strings to emit, output them now. Strings are emitted into
416 // the 'void' type plane.
417 output_vbr(unsigned(E-I));
418 output_typeid(Type::VoidTyID);
420 // Emit all of the strings.
421 for (I = Table.string_begin(); I != E; ++I) {
422 const ConstantArray *Str = *I;
423 int Slot = Table.getSlot(Str->getType());
424 assert(Slot != -1 && "Constant string of unknown type?");
425 output_typeid((unsigned)Slot);
427 // Now that we emitted the type (which indicates the size of the string),
428 // emit all of the characters.
429 std::string Val = Str->getAsString();
430 output_data(Val.c_str(), Val.c_str()+Val.size());
434 //===----------------------------------------------------------------------===//
435 //=== Instruction Output ===//
436 //===----------------------------------------------------------------------===//
438 // outputInstructionFormat0 - Output those weird instructions that have a large
439 // number of operands or have large operands themselves.
441 // Format: [opcode] [type] [numargs] [arg0] [arg1] ... [arg<numargs-1>]
443 void BytecodeWriter::outputInstructionFormat0(const Instruction *I,
445 const SlotCalculator &Table,
447 // Opcode must have top two bits clear...
448 output_vbr(Opcode << 2); // Instruction Opcode ID
449 output_typeid(Type); // Result type
451 unsigned NumArgs = I->getNumOperands();
452 output_vbr(NumArgs + (isa<CastInst>(I) || isa<InvokeInst>(I) ||
453 isa<CmpInst>(I) || isa<VAArgInst>(I) || Opcode == 58));
455 if (!isa<GetElementPtrInst>(&I)) {
456 for (unsigned i = 0; i < NumArgs; ++i) {
457 int Slot = Table.getSlot(I->getOperand(i));
458 assert(Slot >= 0 && "No slot number for value!?!?");
459 output_vbr((unsigned)Slot);
462 if (isa<CastInst>(I) || isa<VAArgInst>(I)) {
463 int Slot = Table.getSlot(I->getType());
464 assert(Slot != -1 && "Cast return type unknown?");
465 output_typeid((unsigned)Slot);
466 } else if (isa<CmpInst>(I)) {
467 output_vbr(unsigned(cast<CmpInst>(I)->getPredicate()));
468 } else if (isa<InvokeInst>(I)) {
469 output_vbr(cast<InvokeInst>(I)->getCallingConv());
470 } else if (Opcode == 58) { // Call escape sequence
471 output_vbr((cast<CallInst>(I)->getCallingConv() << 1) |
472 unsigned(cast<CallInst>(I)->isTailCall()));
475 int Slot = Table.getSlot(I->getOperand(0));
476 assert(Slot >= 0 && "No slot number for value!?!?");
477 output_vbr(unsigned(Slot));
479 // We need to encode the type of sequential type indices into their slot #
481 for (gep_type_iterator TI = gep_type_begin(I), E = gep_type_end(I);
482 Idx != NumArgs; ++TI, ++Idx) {
483 Slot = Table.getSlot(I->getOperand(Idx));
484 assert(Slot >= 0 && "No slot number for value!?!?");
486 if (isa<SequentialType>(*TI)) {
488 switch (I->getOperand(Idx)->getType()->getTypeID()) {
489 default: assert(0 && "Unknown index type!");
490 case Type::Int32TyID: IdxId = 0; break;
491 case Type::Int64TyID: IdxId = 1; break;
493 Slot = (Slot << 1) | IdxId;
495 output_vbr(unsigned(Slot));
501 // outputInstrVarArgsCall - Output the absurdly annoying varargs function calls.
502 // This are more annoying than most because the signature of the call does not
503 // tell us anything about the types of the arguments in the varargs portion.
504 // Because of this, we encode (as type 0) all of the argument types explicitly
505 // before the argument value. This really sucks, but you shouldn't be using
506 // varargs functions in your code! *death to printf*!
508 // Format: [opcode] [type] [numargs] [arg0] [arg1] ... [arg<numargs-1>]
510 void BytecodeWriter::outputInstrVarArgsCall(const Instruction *I,
512 const SlotCalculator &Table,
514 assert(isa<CallInst>(I) || isa<InvokeInst>(I));
515 // Opcode must have top two bits clear...
516 output_vbr(Opcode << 2); // Instruction Opcode ID
517 output_typeid(Type); // Result type (varargs type)
519 const PointerType *PTy = cast<PointerType>(I->getOperand(0)->getType());
520 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
521 unsigned NumParams = FTy->getNumParams();
523 unsigned NumFixedOperands;
524 if (isa<CallInst>(I)) {
525 // Output an operand for the callee and each fixed argument, then two for
526 // each variable argument.
527 NumFixedOperands = 1+NumParams;
529 assert(isa<InvokeInst>(I) && "Not call or invoke??");
530 // Output an operand for the callee and destinations, then two for each
531 // variable argument.
532 NumFixedOperands = 3+NumParams;
534 output_vbr(2 * I->getNumOperands()-NumFixedOperands +
535 unsigned(Opcode == 58 || isa<InvokeInst>(I)));
537 // The type for the function has already been emitted in the type field of the
538 // instruction. Just emit the slot # now.
539 for (unsigned i = 0; i != NumFixedOperands; ++i) {
540 int Slot = Table.getSlot(I->getOperand(i));
541 assert(Slot >= 0 && "No slot number for value!?!?");
542 output_vbr((unsigned)Slot);
545 for (unsigned i = NumFixedOperands, e = I->getNumOperands(); i != e; ++i) {
546 // Output Arg Type ID
547 int Slot = Table.getSlot(I->getOperand(i)->getType());
548 assert(Slot >= 0 && "No slot number for value!?!?");
549 output_typeid((unsigned)Slot);
551 // Output arg ID itself
552 Slot = Table.getSlot(I->getOperand(i));
553 assert(Slot >= 0 && "No slot number for value!?!?");
554 output_vbr((unsigned)Slot);
557 if (isa<InvokeInst>(I)) {
558 // Emit the tail call/calling conv for invoke instructions
559 output_vbr(cast<InvokeInst>(I)->getCallingConv());
560 } else if (Opcode == 58) {
561 const CallInst *CI = cast<CallInst>(I);
562 output_vbr((CI->getCallingConv() << 1) | unsigned(CI->isTailCall()));
567 // outputInstructionFormat1 - Output one operand instructions, knowing that no
568 // operand index is >= 2^12.
570 inline void BytecodeWriter::outputInstructionFormat1(const Instruction *I,
574 // bits Instruction format:
575 // --------------------------
576 // 01-00: Opcode type, fixed to 1.
578 // 19-08: Resulting type plane
579 // 31-20: Operand #1 (if set to (2^12-1), then zero operands)
581 output(1 | (Opcode << 2) | (Type << 8) | (Slots[0] << 20));
585 // outputInstructionFormat2 - Output two operand instructions, knowing that no
586 // operand index is >= 2^8.
588 inline void BytecodeWriter::outputInstructionFormat2(const Instruction *I,
592 // bits Instruction format:
593 // --------------------------
594 // 01-00: Opcode type, fixed to 2.
596 // 15-08: Resulting type plane
600 output(2 | (Opcode << 2) | (Type << 8) | (Slots[0] << 16) | (Slots[1] << 24));
604 // outputInstructionFormat3 - Output three operand instructions, knowing that no
605 // operand index is >= 2^6.
607 inline void BytecodeWriter::outputInstructionFormat3(const Instruction *I,
611 // bits Instruction format:
612 // --------------------------
613 // 01-00: Opcode type, fixed to 3.
615 // 13-08: Resulting type plane
620 output(3 | (Opcode << 2) | (Type << 8) |
621 (Slots[0] << 14) | (Slots[1] << 20) | (Slots[2] << 26));
624 void BytecodeWriter::outputInstruction(const Instruction &I) {
625 assert(I.getOpcode() < 57 && "Opcode too big???");
626 unsigned Opcode = I.getOpcode();
627 unsigned NumOperands = I.getNumOperands();
629 // Encode 'tail call' as 61, 'volatile load' as 62, and 'volatile store' as
631 if (const CallInst *CI = dyn_cast<CallInst>(&I)) {
632 if (CI->getCallingConv() == CallingConv::C) {
633 if (CI->isTailCall())
634 Opcode = 61; // CCC + Tail Call
636 ; // Opcode = Instruction::Call
637 } else if (CI->getCallingConv() == CallingConv::Fast) {
638 if (CI->isTailCall())
639 Opcode = 59; // FastCC + TailCall
641 Opcode = 60; // FastCC + Not Tail Call
643 Opcode = 58; // Call escape sequence.
645 } else if (isa<LoadInst>(I) && cast<LoadInst>(I).isVolatile()) {
647 } else if (isa<StoreInst>(I) && cast<StoreInst>(I).isVolatile()) {
651 // Figure out which type to encode with the instruction. Typically we want
652 // the type of the first parameter, as opposed to the type of the instruction
653 // (for example, with setcc, we always know it returns bool, but the type of
654 // the first param is actually interesting). But if we have no arguments
655 // we take the type of the instruction itself.
658 switch (I.getOpcode()) {
659 case Instruction::Select:
660 case Instruction::Malloc:
661 case Instruction::Alloca:
662 Ty = I.getType(); // These ALWAYS want to encode the return type
664 case Instruction::Store:
665 Ty = I.getOperand(1)->getType(); // Encode the pointer type...
666 assert(isa<PointerType>(Ty) && "Store to nonpointer type!?!?");
668 default: // Otherwise use the default behavior...
669 Ty = NumOperands ? I.getOperand(0)->getType() : I.getType();
674 int Slot = Table.getSlot(Ty);
675 assert(Slot != -1 && "Type not available!!?!");
676 Type = (unsigned)Slot;
678 // Varargs calls and invokes are encoded entirely different from any other
680 if (const CallInst *CI = dyn_cast<CallInst>(&I)){
681 const PointerType *Ty =cast<PointerType>(CI->getCalledValue()->getType());
682 if (cast<FunctionType>(Ty->getElementType())->isVarArg()) {
683 outputInstrVarArgsCall(CI, Opcode, Table, Type);
686 } else if (const InvokeInst *II = dyn_cast<InvokeInst>(&I)) {
687 const PointerType *Ty =cast<PointerType>(II->getCalledValue()->getType());
688 if (cast<FunctionType>(Ty->getElementType())->isVarArg()) {
689 outputInstrVarArgsCall(II, Opcode, Table, Type);
694 if (NumOperands <= 3) {
695 // Make sure that we take the type number into consideration. We don't want
696 // to overflow the field size for the instruction format we select.
698 unsigned MaxOpSlot = Type;
699 unsigned Slots[3]; Slots[0] = (1 << 12)-1; // Marker to signify 0 operands
701 for (unsigned i = 0; i != NumOperands; ++i) {
702 int slot = Table.getSlot(I.getOperand(i));
703 assert(slot != -1 && "Broken bytecode!");
704 if (unsigned(slot) > MaxOpSlot) MaxOpSlot = unsigned(slot);
705 Slots[i] = unsigned(slot);
708 // Handle the special cases for various instructions...
709 if (isa<CastInst>(I) || isa<VAArgInst>(I)) {
710 // Cast has to encode the destination type as the second argument in the
711 // packet, or else we won't know what type to cast to!
712 Slots[1] = Table.getSlot(I.getType());
713 assert(Slots[1] != ~0U && "Cast return type unknown?");
714 if (Slots[1] > MaxOpSlot) MaxOpSlot = Slots[1];
716 } else if (const AllocationInst *AI = dyn_cast<AllocationInst>(&I)) {
717 assert(NumOperands == 1 && "Bogus allocation!");
718 if (AI->getAlignment()) {
719 Slots[1] = Log2_32(AI->getAlignment())+1;
720 if (Slots[1] > MaxOpSlot) MaxOpSlot = Slots[1];
723 } else if (isa<ICmpInst>(I) || isa<FCmpInst>(I)) {
724 // We need to encode the compare instruction's predicate as the third
725 // operand. Its not really a slot, but we don't want to break the
726 // instruction format for these instructions.
728 assert(NumOperands == 3 && "CmpInst with wrong number of operands?");
729 Slots[2] = unsigned(cast<CmpInst>(&I)->getPredicate());
730 if (Slots[2] > MaxOpSlot)
731 MaxOpSlot = Slots[2];
732 } else if (const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(&I)) {
733 // We need to encode the type of sequential type indices into their slot #
735 for (gep_type_iterator I = gep_type_begin(GEP), E = gep_type_end(GEP);
737 if (isa<SequentialType>(*I)) {
739 switch (GEP->getOperand(Idx)->getType()->getTypeID()) {
740 default: assert(0 && "Unknown index type!");
741 case Type::Int32TyID: IdxId = 0; break;
742 case Type::Int64TyID: IdxId = 1; break;
744 Slots[Idx] = (Slots[Idx] << 1) | IdxId;
745 if (Slots[Idx] > MaxOpSlot) MaxOpSlot = Slots[Idx];
747 } else if (Opcode == 58) {
748 // If this is the escape sequence for call, emit the tailcall/cc info.
749 const CallInst &CI = cast<CallInst>(I);
751 if (NumOperands <= 3) {
752 Slots[NumOperands-1] =
753 (CI.getCallingConv() << 1)|unsigned(CI.isTailCall());
754 if (Slots[NumOperands-1] > MaxOpSlot)
755 MaxOpSlot = Slots[NumOperands-1];
757 } else if (isa<InvokeInst>(I)) {
758 // Invoke escape seq has at least 4 operands to encode.
762 // Decide which instruction encoding to use. This is determined primarily
763 // by the number of operands, and secondarily by whether or not the max
764 // operand will fit into the instruction encoding. More operands == fewer
767 switch (NumOperands) {
770 if (MaxOpSlot < (1 << 12)-1) { // -1 because we use 4095 to indicate 0 ops
771 outputInstructionFormat1(&I, Opcode, Slots, Type);
777 if (MaxOpSlot < (1 << 8)) {
778 outputInstructionFormat2(&I, Opcode, Slots, Type);
784 if (MaxOpSlot < (1 << 6)) {
785 outputInstructionFormat3(&I, Opcode, Slots, Type);
794 // If we weren't handled before here, we either have a large number of
795 // operands or a large operand index that we are referring to.
796 outputInstructionFormat0(&I, Opcode, Table, Type);
799 //===----------------------------------------------------------------------===//
800 //=== Block Output ===//
801 //===----------------------------------------------------------------------===//
803 BytecodeWriter::BytecodeWriter(std::vector<unsigned char> &o, const Module *M)
806 // Emit the signature...
807 static const unsigned char *Sig = (const unsigned char*)"llvm";
808 output_data(Sig, Sig+4);
810 // Emit the top level CLASS block.
811 BytecodeBlock ModuleBlock(BytecodeFormat::ModuleBlockID, *this, false, true);
813 bool isBigEndian = M->getEndianness() == Module::BigEndian;
814 bool hasLongPointers = M->getPointerSize() == Module::Pointer64;
815 bool hasNoEndianness = M->getEndianness() == Module::AnyEndianness;
816 bool hasNoPointerSize = M->getPointerSize() == Module::AnyPointerSize;
818 // Output the version identifier and other information.
819 unsigned Version = (BCVersionNum << 4) |
820 (unsigned)isBigEndian | (hasLongPointers << 1) |
821 (hasNoEndianness << 2) |
822 (hasNoPointerSize << 3);
825 // The Global type plane comes first
827 BytecodeBlock CPool(BytecodeFormat::GlobalTypePlaneBlockID, *this);
828 outputTypes(Type::FirstDerivedTyID);
831 // The ModuleInfoBlock follows directly after the type information
832 outputModuleInfoBlock(M);
834 // Output module level constants, used for global variable initializers
835 outputConstants(false);
837 // Do the whole module now! Process each function at a time...
838 for (Module::const_iterator I = M->begin(), E = M->end(); I != E; ++I)
841 // Output the symbole table for types
842 outputTypeSymbolTable(M->getTypeSymbolTable());
844 // Output the symbol table for values
845 outputValueSymbolTable(M->getValueSymbolTable());
848 void BytecodeWriter::outputTypes(unsigned TypeNum) {
849 // Write the type plane for types first because earlier planes (e.g. for a
850 // primitive type like float) may have constants constructed using types
851 // coming later (e.g., via getelementptr from a pointer type). The type
852 // plane is needed before types can be fwd or bkwd referenced.
853 const std::vector<const Type*>& Types = Table.getTypes();
854 assert(!Types.empty() && "No types at all?");
855 assert(TypeNum <= Types.size() && "Invalid TypeNo index");
857 unsigned NumEntries = Types.size() - TypeNum;
859 // Output type header: [num entries]
860 output_vbr(NumEntries);
862 for (unsigned i = TypeNum; i < TypeNum+NumEntries; ++i)
863 outputType(Types[i]);
866 // Helper function for outputConstants().
867 // Writes out all the constants in the plane Plane starting at entry StartNo.
869 void BytecodeWriter::outputConstantsInPlane(const std::vector<const Value*>
870 &Plane, unsigned StartNo) {
871 unsigned ValNo = StartNo;
873 // Scan through and ignore function arguments, global values, and constant
875 for (; ValNo < Plane.size() &&
876 (isa<Argument>(Plane[ValNo]) || isa<GlobalValue>(Plane[ValNo]) ||
877 (isa<ConstantArray>(Plane[ValNo]) &&
878 cast<ConstantArray>(Plane[ValNo])->isString())); ValNo++)
881 unsigned NC = ValNo; // Number of constants
882 for (; NC < Plane.size() && (isa<Constant>(Plane[NC]) ||
883 isa<InlineAsm>(Plane[NC])); NC++)
885 NC -= ValNo; // Convert from index into count
886 if (NC == 0) return; // Skip empty type planes...
888 // FIXME: Most slabs only have 1 or 2 entries! We should encode this much
891 // Put out type header: [num entries][type id number]
895 // Put out the Type ID Number...
896 int Slot = Table.getSlot(Plane.front()->getType());
897 assert (Slot != -1 && "Type in constant pool but not in function!!");
898 output_typeid((unsigned)Slot);
900 for (unsigned i = ValNo; i < ValNo+NC; ++i) {
901 const Value *V = Plane[i];
902 if (const Constant *C = dyn_cast<Constant>(V))
905 outputInlineAsm(cast<InlineAsm>(V));
909 static inline bool hasNullValue(const Type *Ty) {
910 return Ty != Type::LabelTy && Ty != Type::VoidTy && !isa<OpaqueType>(Ty);
913 void BytecodeWriter::outputConstants(bool isFunction) {
914 BytecodeBlock CPool(BytecodeFormat::ConstantPoolBlockID, *this,
915 true /* Elide block if empty */);
917 unsigned NumPlanes = Table.getNumPlanes();
920 // Output the type plane before any constants!
921 outputTypes(Table.getModuleTypeLevel());
923 // Output module-level string constants before any other constants.
924 outputConstantStrings();
926 for (unsigned pno = 0; pno != NumPlanes; pno++) {
927 const std::vector<const Value*> &Plane = Table.getPlane(pno);
928 if (!Plane.empty()) { // Skip empty type planes...
930 if (isFunction) // Don't re-emit module constants
931 ValNo += Table.getModuleLevel(pno);
933 if (hasNullValue(Plane[0]->getType())) {
934 // Skip zero initializer
939 // Write out constants in the plane
940 outputConstantsInPlane(Plane, ValNo);
945 static unsigned getEncodedLinkage(const GlobalValue *GV) {
946 switch (GV->getLinkage()) {
947 default: assert(0 && "Invalid linkage!");
948 case GlobalValue::ExternalLinkage: return 0;
949 case GlobalValue::WeakLinkage: return 1;
950 case GlobalValue::AppendingLinkage: return 2;
951 case GlobalValue::InternalLinkage: return 3;
952 case GlobalValue::LinkOnceLinkage: return 4;
953 case GlobalValue::DLLImportLinkage: return 5;
954 case GlobalValue::DLLExportLinkage: return 6;
955 case GlobalValue::ExternalWeakLinkage: return 7;
959 void BytecodeWriter::outputModuleInfoBlock(const Module *M) {
960 BytecodeBlock ModuleInfoBlock(BytecodeFormat::ModuleGlobalInfoBlockID, *this);
962 // Give numbers to sections as we encounter them.
963 unsigned SectionIDCounter = 0;
964 std::vector<std::string> SectionNames;
965 std::map<std::string, unsigned> SectionID;
967 // Output the types for the global variables in the module...
968 for (Module::const_global_iterator I = M->global_begin(),
969 End = M->global_end(); I != End; ++I) {
970 int Slot = Table.getSlot(I->getType());
971 assert(Slot != -1 && "Module global vars is broken!");
973 assert((I->hasInitializer() || !I->hasInternalLinkage()) &&
974 "Global must have an initializer or have external linkage!");
976 // Fields: bit0 = isConstant, bit1 = hasInitializer, bit2-4=Linkage,
977 // bit5+ = Slot # for type.
978 bool HasExtensionWord = (I->getAlignment() != 0) || I->hasSection();
980 // If we need to use the extension byte, set linkage=3(internal) and
981 // initializer = 0 (impossible!).
982 if (!HasExtensionWord) {
983 unsigned oSlot = ((unsigned)Slot << 5) | (getEncodedLinkage(I) << 2) |
984 (I->hasInitializer() << 1) | (unsigned)I->isConstant();
987 unsigned oSlot = ((unsigned)Slot << 5) | (3 << 2) |
988 (0 << 1) | (unsigned)I->isConstant();
991 // The extension word has this format: bit 0 = has initializer, bit 1-3 =
992 // linkage, bit 4-8 = alignment (log2), bit 9 = has SectionID,
993 // bits 10+ = future use.
994 unsigned ExtWord = (unsigned)I->hasInitializer() |
995 (getEncodedLinkage(I) << 1) |
996 ((Log2_32(I->getAlignment())+1) << 4) |
997 ((unsigned)I->hasSection() << 9);
999 if (I->hasSection()) {
1000 // Give section names unique ID's.
1001 unsigned &Entry = SectionID[I->getSection()];
1003 Entry = ++SectionIDCounter;
1004 SectionNames.push_back(I->getSection());
1010 // If we have an initializer, output it now.
1011 if (I->hasInitializer()) {
1012 Slot = Table.getSlot((Value*)I->getInitializer());
1013 assert(Slot != -1 && "No slot for global var initializer!");
1014 output_vbr((unsigned)Slot);
1017 output_typeid((unsigned)Table.getSlot(Type::VoidTy));
1019 // Output the types of the functions in this module.
1020 for (Module::const_iterator I = M->begin(), End = M->end(); I != End; ++I) {
1021 int Slot = Table.getSlot(I->getType());
1022 assert(Slot != -1 && "Module slot calculator is broken!");
1023 assert(Slot >= Type::FirstDerivedTyID && "Derived type not in range!");
1024 assert(((Slot << 6) >> 6) == Slot && "Slot # too big!");
1025 unsigned CC = I->getCallingConv()+1;
1026 unsigned ID = (Slot << 5) | (CC & 15);
1028 if (I->isExternal()) // If external, we don't have an FunctionInfo block.
1031 if (I->getAlignment() || I->hasSection() || (CC & ~15) != 0 ||
1032 (I->isExternal() && I->hasDLLImportLinkage()) ||
1033 (I->isExternal() && I->hasExternalWeakLinkage())
1035 ID |= 1 << 31; // Do we need an extension word?
1039 if (ID & (1 << 31)) {
1040 // Extension byte: bits 0-4 = alignment, bits 5-9 = top nibble of calling
1041 // convention, bit 10 = hasSectionID., bits 11-12 = external linkage type
1042 unsigned extLinkage = 0;
1044 if (I->isExternal()) {
1045 if (I->hasDLLImportLinkage()) {
1047 } else if (I->hasExternalWeakLinkage()) {
1052 ID = (Log2_32(I->getAlignment())+1) | ((CC >> 4) << 5) |
1053 (I->hasSection() << 10) |
1054 ((extLinkage & 3) << 11);
1057 // Give section names unique ID's.
1058 if (I->hasSection()) {
1059 unsigned &Entry = SectionID[I->getSection()];
1061 Entry = ++SectionIDCounter;
1062 SectionNames.push_back(I->getSection());
1068 output_vbr((unsigned)Table.getSlot(Type::VoidTy) << 5);
1070 // Emit the list of dependent libraries for the Module.
1071 Module::lib_iterator LI = M->lib_begin();
1072 Module::lib_iterator LE = M->lib_end();
1073 output_vbr(unsigned(LE - LI)); // Emit the number of dependent libraries.
1074 for (; LI != LE; ++LI)
1077 // Output the target triple from the module
1078 output(M->getTargetTriple());
1080 // Emit the table of section names.
1081 output_vbr((unsigned)SectionNames.size());
1082 for (unsigned i = 0, e = SectionNames.size(); i != e; ++i)
1083 output(SectionNames[i]);
1085 // Output the inline asm string.
1086 output(M->getModuleInlineAsm());
1089 void BytecodeWriter::outputInstructions(const Function *F) {
1090 BytecodeBlock ILBlock(BytecodeFormat::InstructionListBlockID, *this);
1091 for (Function::const_iterator BB = F->begin(), E = F->end(); BB != E; ++BB)
1092 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I!=E; ++I)
1093 outputInstruction(*I);
1096 void BytecodeWriter::outputFunction(const Function *F) {
1097 // If this is an external function, there is nothing else to emit!
1098 if (F->isExternal()) return;
1100 BytecodeBlock FunctionBlock(BytecodeFormat::FunctionBlockID, *this);
1101 output_vbr(getEncodedLinkage(F));
1103 // Get slot information about the function...
1104 Table.incorporateFunction(F);
1106 if (Table.getCompactionTable().empty()) {
1107 // Output information about the constants in the function if the compaction
1108 // table is not being used.
1109 outputConstants(true);
1111 // Otherwise, emit the compaction table.
1112 outputCompactionTable();
1115 // Output all of the instructions in the body of the function
1116 outputInstructions(F);
1118 // If needed, output the symbol table for the function...
1119 outputValueSymbolTable(F->getValueSymbolTable());
1121 Table.purgeFunction();
1124 void BytecodeWriter::outputCompactionTablePlane(unsigned PlaneNo,
1125 const std::vector<const Value*> &Plane,
1127 unsigned End = Table.getModuleLevel(PlaneNo);
1128 if (Plane.empty() || StartNo == End || End == 0) return; // Nothing to emit
1129 assert(StartNo < End && "Cannot emit negative range!");
1130 assert(StartNo < Plane.size() && End <= Plane.size());
1132 // Do not emit the null initializer!
1135 // Figure out which encoding to use. By far the most common case we have is
1136 // to emit 0-2 entries in a compaction table plane.
1137 switch (End-StartNo) {
1138 case 0: // Avoid emitting two vbr's if possible.
1141 output_vbr((PlaneNo << 2) | End-StartNo);
1144 // Output the number of things.
1145 output_vbr((unsigned(End-StartNo) << 2) | 3);
1146 output_typeid(PlaneNo); // Emit the type plane this is
1150 for (unsigned i = StartNo; i != End; ++i)
1151 output_vbr(Table.getGlobalSlot(Plane[i]));
1154 void BytecodeWriter::outputCompactionTypes(unsigned StartNo) {
1155 // Get the compaction type table from the slot calculator
1156 const std::vector<const Type*> &CTypes = Table.getCompactionTypes();
1158 // The compaction types may have been uncompactified back to the
1159 // global types. If so, we just write an empty table
1160 if (CTypes.size() == 0) {
1165 assert(CTypes.size() >= StartNo && "Invalid compaction types start index");
1167 // Determine how many types to write
1168 unsigned NumTypes = CTypes.size() - StartNo;
1170 // Output the number of types.
1171 output_vbr(NumTypes);
1173 for (unsigned i = StartNo; i < StartNo+NumTypes; ++i)
1174 output_typeid(Table.getGlobalSlot(CTypes[i]));
1177 void BytecodeWriter::outputCompactionTable() {
1178 // Avoid writing the compaction table at all if there is no content.
1179 if (Table.getCompactionTypes().size() >= Type::FirstDerivedTyID ||
1180 (!Table.CompactionTableIsEmpty())) {
1181 BytecodeBlock CTB(BytecodeFormat::CompactionTableBlockID, *this,
1182 true/*ElideIfEmpty*/);
1183 const std::vector<std::vector<const Value*> > &CT =
1184 Table.getCompactionTable();
1186 // First things first, emit the type compaction table if there is one.
1187 outputCompactionTypes(Type::FirstDerivedTyID);
1189 for (unsigned i = 0, e = CT.size(); i != e; ++i)
1190 outputCompactionTablePlane(i, CT[i], 0);
1194 void BytecodeWriter::outputTypeSymbolTable(const TypeSymbolTable &TST) {
1195 // Do not output the block for an empty symbol table, it just wastes
1197 if (TST.empty()) return;
1199 // Create a header for the symbol table
1200 BytecodeBlock SymTabBlock(BytecodeFormat::TypeSymbolTableBlockID, *this,
1201 true/*ElideIfEmpty*/);
1202 // Write the number of types
1203 output_vbr(TST.size());
1205 // Write each of the types
1206 for (TypeSymbolTable::const_iterator TI = TST.begin(), TE = TST.end();
1208 // Symtab entry:[def slot #][name]
1209 output_typeid((unsigned)Table.getSlot(TI->second));
1214 void BytecodeWriter::outputValueSymbolTable(const SymbolTable &MST) {
1215 // Do not output the Bytecode block for an empty symbol table, it just wastes
1217 if (MST.isEmpty()) return;
1219 BytecodeBlock SymTabBlock(BytecodeFormat::ValueSymbolTableBlockID, *this,
1220 true/*ElideIfEmpty*/);
1222 // Now do each of the type planes in order.
1223 for (SymbolTable::plane_const_iterator PI = MST.plane_begin(),
1224 PE = MST.plane_end(); PI != PE; ++PI) {
1225 SymbolTable::value_const_iterator I = MST.value_begin(PI->first);
1226 SymbolTable::value_const_iterator End = MST.value_end(PI->first);
1229 if (I == End) continue; // Don't mess with an absent type...
1231 // Write the number of values in this plane
1232 output_vbr((unsigned)PI->second.size());
1234 // Write the slot number of the type for this plane
1235 Slot = Table.getSlot(PI->first);
1236 assert(Slot != -1 && "Type in symtab, but not in table!");
1237 output_typeid((unsigned)Slot);
1239 // Write each of the values in this plane
1240 for (; I != End; ++I) {
1241 // Symtab entry: [def slot #][name]
1242 Slot = Table.getSlot(I->second);
1243 assert(Slot != -1 && "Value in symtab but has no slot number!!");
1244 output_vbr((unsigned)Slot);
1250 void llvm::WriteBytecodeToFile(const Module *M, OStream &Out,
1252 assert(M && "You can't write a null module!!");
1254 // Make sure that std::cout is put into binary mode for systems
1257 sys::Program::ChangeStdoutToBinary();
1259 // Create a vector of unsigned char for the bytecode output. We
1260 // reserve 256KBytes of space in the vector so that we avoid doing
1261 // lots of little allocations. 256KBytes is sufficient for a large
1262 // proportion of the bytecode files we will encounter. Larger files
1263 // will be automatically doubled in size as needed (std::vector
1265 std::vector<unsigned char> Buffer;
1266 Buffer.reserve(256 * 1024);
1268 // The BytecodeWriter populates Buffer for us.
1269 BytecodeWriter BCW(Buffer, M);
1271 // Keep track of how much we've written
1272 BytesWritten += Buffer.size();
1274 // Determine start and end points of the Buffer
1275 const unsigned char *FirstByte = &Buffer.front();
1277 // If we're supposed to compress this mess ...
1280 // We signal compression by using an alternate magic number for the
1281 // file. The compressed bytecode file's magic number is "llvc" instead
1283 char compressed_magic[4];
1284 compressed_magic[0] = 'l';
1285 compressed_magic[1] = 'l';
1286 compressed_magic[2] = 'v';
1287 compressed_magic[3] = 'c';
1289 Out.stream()->write(compressed_magic,4);
1291 // Compress everything after the magic number (which we altered)
1292 Compressor::compressToStream(
1293 (char*)(FirstByte+4), // Skip the magic number
1294 Buffer.size()-4, // Skip the magic number
1295 *Out.stream() // Where to write compressed data
1300 // We're not compressing, so just write the entire block.
1301 Out.stream()->write((char*)FirstByte, Buffer.size());
1304 // make sure it hits disk now
1305 Out.stream()->flush();