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 "bcwriter"
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/ParameterAttributes.h"
27 #include "llvm/InlineAsm.h"
28 #include "llvm/Instructions.h"
29 #include "llvm/Module.h"
30 #include "llvm/TypeSymbolTable.h"
31 #include "llvm/ValueSymbolTable.h"
32 #include "llvm/Support/GetElementPtrTypeIterator.h"
33 #include "llvm/Support/Compressor.h"
34 #include "llvm/Support/MathExtras.h"
35 #include "llvm/Support/Streams.h"
36 #include "llvm/System/Program.h"
37 #include "llvm/ADT/SmallVector.h"
38 #include "llvm/ADT/STLExtras.h"
39 #include "llvm/ADT/Statistic.h"
44 /// 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
47 /// @brief The bytecode version number
48 const unsigned BCVersionNum = 7;
50 static RegisterPass<WriteBytecodePass> X("emitbytecode", "Bytecode Writer");
52 STATISTIC(BytesWritten, "Number of bytecode bytes written");
54 //===----------------------------------------------------------------------===//
55 //=== Output Primitives ===//
56 //===----------------------------------------------------------------------===//
58 // output - If a position is specified, it must be in the valid portion of the
59 // string... note that this should be inlined always so only the relevant IF
60 // body should be included.
61 inline void BytecodeWriter::output(unsigned i, int pos) {
62 if (pos == -1) { // Be endian clean, little endian is our friend
63 Out.push_back((unsigned char)i);
64 Out.push_back((unsigned char)(i >> 8));
65 Out.push_back((unsigned char)(i >> 16));
66 Out.push_back((unsigned char)(i >> 24));
68 Out[pos ] = (unsigned char)i;
69 Out[pos+1] = (unsigned char)(i >> 8);
70 Out[pos+2] = (unsigned char)(i >> 16);
71 Out[pos+3] = (unsigned char)(i >> 24);
75 inline void BytecodeWriter::output(int32_t i) {
79 /// output_vbr - Output an unsigned value, by using the least number of bytes
80 /// possible. This is useful because many of our "infinite" values are really
81 /// very small most of the time; but can be large a few times.
82 /// Data format used: If you read a byte with the high bit set, use the low
83 /// seven bits as data and then read another byte.
84 inline void BytecodeWriter::output_vbr(uint64_t i) {
86 if (i < 0x80) { // done?
87 Out.push_back((unsigned char)i); // We know the high bit is clear...
91 // Nope, we are bigger than a character, output the next 7 bits and set the
92 // high bit to say that there is more coming...
93 Out.push_back(0x80 | ((unsigned char)i & 0x7F));
94 i >>= 7; // Shift out 7 bits now...
98 inline void BytecodeWriter::output_vbr(uint32_t i) {
100 if (i < 0x80) { // done?
101 Out.push_back((unsigned char)i); // We know the high bit is clear...
105 // Nope, we are bigger than a character, output the next 7 bits and set the
106 // high bit to say that there is more coming...
107 Out.push_back(0x80 | ((unsigned char)i & 0x7F));
108 i >>= 7; // Shift out 7 bits now...
112 inline void BytecodeWriter::output_typeid(unsigned i) {
116 this->output_vbr(0x00FFFFFF);
121 inline void BytecodeWriter::output_vbr(int64_t i) {
123 output_vbr(((uint64_t)(-i) << 1) | 1); // Set low order sign bit...
125 output_vbr((uint64_t)i << 1); // Low order bit is clear.
129 inline void BytecodeWriter::output_vbr(int i) {
131 output_vbr(((unsigned)(-i) << 1) | 1); // Set low order sign bit...
133 output_vbr((unsigned)i << 1); // Low order bit is clear.
136 inline void BytecodeWriter::output_str(const char *Str, unsigned Len) {
137 output_vbr(Len); // Strings may have an arbitrary length.
138 Out.insert(Out.end(), Str, Str+Len);
141 inline void BytecodeWriter::output_data(const void *Ptr, const void *End) {
142 Out.insert(Out.end(), (const unsigned char*)Ptr, (const unsigned char*)End);
145 inline void BytecodeWriter::output_float(float& FloatVal) {
146 /// FIXME: This isn't optimal, it has size problems on some platforms
147 /// where FP is not IEEE.
148 uint32_t i = FloatToBits(FloatVal);
149 Out.push_back( static_cast<unsigned char>( (i ) & 0xFF));
150 Out.push_back( static_cast<unsigned char>( (i >> 8 ) & 0xFF));
151 Out.push_back( static_cast<unsigned char>( (i >> 16) & 0xFF));
152 Out.push_back( static_cast<unsigned char>( (i >> 24) & 0xFF));
155 inline void BytecodeWriter::output_double(double& DoubleVal) {
156 /// FIXME: This isn't optimal, it has size problems on some platforms
157 /// where FP is not IEEE.
158 uint64_t i = DoubleToBits(DoubleVal);
159 Out.push_back( static_cast<unsigned char>( (i ) & 0xFF));
160 Out.push_back( static_cast<unsigned char>( (i >> 8 ) & 0xFF));
161 Out.push_back( static_cast<unsigned char>( (i >> 16) & 0xFF));
162 Out.push_back( static_cast<unsigned char>( (i >> 24) & 0xFF));
163 Out.push_back( static_cast<unsigned char>( (i >> 32) & 0xFF));
164 Out.push_back( static_cast<unsigned char>( (i >> 40) & 0xFF));
165 Out.push_back( static_cast<unsigned char>( (i >> 48) & 0xFF));
166 Out.push_back( static_cast<unsigned char>( (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));
192 Writer.output(unsigned(Writer.size()-Loc), int(Loc-4));
194 Writer.output(unsigned(Writer.size()-Loc) << 5 | (Id & 0x1F), int(Loc-4));
197 //===----------------------------------------------------------------------===//
198 //=== Constant Output ===//
199 //===----------------------------------------------------------------------===//
201 void BytecodeWriter::outputParamAttrsList(const ParamAttrsList *Attrs) {
203 output_vbr(unsigned(0));
206 unsigned numAttrs = Attrs->size();
207 output_vbr(numAttrs);
208 for (unsigned i = 0; i < numAttrs; ++i) {
209 uint16_t index = Attrs->getParamIndex(i);
210 uint16_t attrs = Attrs->getParamAttrs(index);
211 output_vbr(uint32_t(index));
212 output_vbr(uint32_t(attrs));
216 void BytecodeWriter::outputType(const Type *T) {
217 const StructType* STy = dyn_cast<StructType>(T);
218 if(STy && STy->isPacked())
219 output_vbr((unsigned)Type::PackedStructTyID);
221 output_vbr((unsigned)T->getTypeID());
223 // That's all there is to handling primitive types...
224 if (T->isPrimitiveType())
225 return; // We might do this if we alias a prim type: %x = type int
227 switch (T->getTypeID()) { // Handle derived types now.
228 case Type::IntegerTyID:
229 output_vbr(cast<IntegerType>(T)->getBitWidth());
231 case Type::FunctionTyID: {
232 const FunctionType *FT = cast<FunctionType>(T);
233 output_typeid(Table.getTypeSlot(FT->getReturnType()));
235 // Output the number of arguments to function (+1 if varargs):
236 output_vbr((unsigned)FT->getNumParams()+FT->isVarArg());
238 // Output all of the arguments...
239 FunctionType::param_iterator I = FT->param_begin();
240 for (; I != FT->param_end(); ++I)
241 output_typeid(Table.getTypeSlot(*I));
243 // Terminate list with VoidTy if we are a varargs function...
245 output_typeid((unsigned)Type::VoidTyID);
247 // Put out all the parameter attributes
248 outputParamAttrsList(FT->getParamAttrs());
252 case Type::ArrayTyID: {
253 const ArrayType *AT = cast<ArrayType>(T);
254 output_typeid(Table.getTypeSlot(AT->getElementType()));
255 output_vbr(AT->getNumElements());
259 case Type::VectorTyID: {
260 const VectorType *PT = cast<VectorType>(T);
261 output_typeid(Table.getTypeSlot(PT->getElementType()));
262 output_vbr(PT->getNumElements());
266 case Type::StructTyID: {
267 const StructType *ST = cast<StructType>(T);
268 // Output all of the element types...
269 for (StructType::element_iterator I = ST->element_begin(),
270 E = ST->element_end(); I != E; ++I) {
271 output_typeid(Table.getTypeSlot(*I));
274 // Terminate list with VoidTy
275 output_typeid((unsigned)Type::VoidTyID);
279 case Type::PointerTyID:
280 output_typeid(Table.getTypeSlot(cast<PointerType>(T)->getElementType()));
283 case Type::OpaqueTyID:
284 // No need to emit anything, just the count of opaque types is enough.
288 cerr << __FILE__ << ":" << __LINE__ << ": Don't know how to serialize"
289 << " Type '" << T->getDescription() << "'\n";
294 void BytecodeWriter::outputConstant(const Constant *CPV) {
295 assert(((CPV->getType()->isPrimitiveType() || CPV->getType()->isInteger()) ||
296 !CPV->isNullValue()) && "Shouldn't output null constants!");
298 // We must check for a ConstantExpr before switching by type because
299 // a ConstantExpr can be of any type, and has no explicit value.
301 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CPV)) {
302 // FIXME: Encoding of constant exprs could be much more compact!
303 assert(CE->getNumOperands() > 0 && "ConstantExpr with 0 operands");
304 assert(CE->getNumOperands() != 1 || CE->isCast());
305 output_vbr(1+CE->getNumOperands()); // flags as an expr
306 output_vbr(CE->getOpcode()); // Put out the CE op code
308 for (User::const_op_iterator OI = CE->op_begin(); OI != CE->op_end(); ++OI){
309 output_vbr(Table.getSlot(*OI));
310 output_typeid(Table.getTypeSlot((*OI)->getType()));
313 output_vbr((unsigned)CE->getPredicate());
315 } else if (isa<UndefValue>(CPV)) {
316 output_vbr(1U); // 1 -> UndefValue constant.
319 output_vbr(0U); // flag as not a ConstantExpr (i.e. 0 operands)
322 switch (CPV->getType()->getTypeID()) {
323 case Type::IntegerTyID: { // Integer types...
324 const ConstantInt *CI = cast<ConstantInt>(CPV);
325 unsigned NumBits = cast<IntegerType>(CPV->getType())->getBitWidth();
327 output_vbr(uint32_t(CI->getZExtValue()));
328 else if (NumBits <= 64)
329 output_vbr(uint64_t(CI->getZExtValue()));
331 // We have an arbitrary precision integer value to write whose
332 // bit width is > 64. However, in canonical unsigned integer
333 // format it is likely that the high bits are going to be zero.
334 // So, we only write the number of active words.
335 uint32_t activeWords = CI->getValue().getActiveWords();
336 const uint64_t *rawData = CI->getValue().getRawData();
337 output_vbr(activeWords);
338 for (uint32_t i = 0; i < activeWords; ++i)
339 output_vbr(rawData[i]);
344 case Type::ArrayTyID: {
345 const ConstantArray *CPA = cast<ConstantArray>(CPV);
346 assert(!CPA->isString() && "Constant strings should be handled specially!");
348 for (unsigned i = 0, e = CPA->getNumOperands(); i != e; ++i)
349 output_vbr(Table.getSlot(CPA->getOperand(i)));
353 case Type::VectorTyID: {
354 const ConstantVector *CP = cast<ConstantVector>(CPV);
355 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
356 output_vbr(Table.getSlot(CP->getOperand(i)));
360 case Type::StructTyID: {
361 const ConstantStruct *CPS = cast<ConstantStruct>(CPV);
363 for (unsigned i = 0, e = CPS->getNumOperands(); i != e; ++i)
364 output_vbr(Table.getSlot(CPS->getOperand(i)));
368 case Type::PointerTyID:
369 assert(0 && "No non-null, non-constant-expr constants allowed!");
372 case Type::FloatTyID: { // Floating point types...
373 float Tmp = (float)cast<ConstantFP>(CPV)->getValue();
377 case Type::DoubleTyID: {
378 double Tmp = cast<ConstantFP>(CPV)->getValue();
384 case Type::LabelTyID:
386 cerr << __FILE__ << ":" << __LINE__ << ": Don't know how to serialize"
387 << " type '" << *CPV->getType() << "'\n";
393 /// outputInlineAsm - InlineAsm's get emitted to the constant pool, so they can
394 /// be shared by multiple uses.
395 void BytecodeWriter::outputInlineAsm(const InlineAsm *IA) {
396 // Output a marker, so we know when we have one one parsing the constant pool.
397 // Note that this encoding is 5 bytes: not very efficient for a marker. Since
398 // unique inline asms are rare, this should hardly matter.
401 output(IA->getAsmString());
402 output(IA->getConstraintString());
403 output_vbr(unsigned(IA->hasSideEffects()));
406 void BytecodeWriter::outputConstantStrings() {
407 SlotCalculator::string_iterator I = Table.string_begin();
408 SlotCalculator::string_iterator E = Table.string_end();
409 if (I == E) return; // No strings to emit
411 // If we have != 0 strings to emit, output them now. Strings are emitted into
412 // the 'void' type plane.
413 output_vbr(unsigned(E-I));
414 output_typeid(Type::VoidTyID);
416 // Emit all of the strings.
417 for (I = Table.string_begin(); I != E; ++I) {
418 const ConstantArray *Str = *I;
419 output_typeid(Table.getTypeSlot(Str->getType()));
421 // Now that we emitted the type (which indicates the size of the string),
422 // emit all of the characters.
423 std::string Val = Str->getAsString();
424 output_data(Val.c_str(), Val.c_str()+Val.size());
428 //===----------------------------------------------------------------------===//
429 //=== Instruction Output ===//
430 //===----------------------------------------------------------------------===//
432 // outputInstructionFormat0 - Output those weird instructions that have a large
433 // number of operands or have large operands themselves.
435 // Format: [opcode] [type] [numargs] [arg0] [arg1] ... [arg<numargs-1>]
437 void BytecodeWriter::outputInstructionFormat0(const Instruction *I,
439 const SlotCalculator &Table,
441 // Opcode must have top two bits clear...
442 output_vbr(Opcode << 2); // Instruction Opcode ID
443 output_typeid(Type); // Result type
445 unsigned NumArgs = I->getNumOperands();
446 bool HasExtraArg = false;
447 if (isa<CastInst>(I) || isa<InvokeInst>(I) ||
448 isa<CmpInst>(I) || isa<VAArgInst>(I) || Opcode == 58 ||
449 Opcode == 62 || Opcode == 63)
451 if (const AllocationInst *AI = dyn_cast<AllocationInst>(I))
452 HasExtraArg = AI->getAlignment() != 0;
454 output_vbr(NumArgs + HasExtraArg);
456 if (!isa<GetElementPtrInst>(&I)) {
457 for (unsigned i = 0; i < NumArgs; ++i)
458 output_vbr(Table.getSlot(I->getOperand(i)));
460 if (isa<CastInst>(I) || isa<VAArgInst>(I)) {
461 output_typeid(Table.getTypeSlot(I->getType()));
462 } else if (isa<CmpInst>(I)) {
463 output_vbr(unsigned(cast<CmpInst>(I)->getPredicate()));
464 } else if (isa<InvokeInst>(I)) {
465 output_vbr(cast<InvokeInst>(I)->getCallingConv());
466 } else if (Opcode == 58) { // Call escape sequence
467 output_vbr((cast<CallInst>(I)->getCallingConv() << 1) |
468 unsigned(cast<CallInst>(I)->isTailCall()));
469 } else if (const AllocationInst *AI = dyn_cast<AllocationInst>(I)) {
470 if (AI->getAlignment())
471 output_vbr((unsigned)Log2_32(AI->getAlignment())+1);
472 } else if (Opcode == 62) { // Attributed load
473 output_vbr((unsigned)(((Log2_32(cast<LoadInst>(I)->getAlignment())+1)<<1)
474 + (cast<LoadInst>(I)->isVolatile() ? 1 : 0)));
475 } else if (Opcode == 63) { // Attributed store
476 output_vbr((unsigned)(((Log2_32(cast<StoreInst>(I)->getAlignment())+1)<<1)
477 + (cast<StoreInst>(I)->isVolatile() ? 1 : 0)));
480 output_vbr(Table.getSlot(I->getOperand(0)));
482 // We need to encode the type of sequential type indices into their slot #
484 for (gep_type_iterator TI = gep_type_begin(I), E = gep_type_end(I);
485 Idx != NumArgs; ++TI, ++Idx) {
486 unsigned Slot = Table.getSlot(I->getOperand(Idx));
488 if (isa<SequentialType>(*TI)) {
489 // These should be either 32-bits or 64-bits, however, with bit
490 // accurate types we just distinguish between less than or equal to
491 // 32-bits or greater than 32-bits.
493 cast<IntegerType>(I->getOperand(Idx)->getType())->getBitWidth();
494 assert(BitWidth == 32 || BitWidth == 64 &&
495 "Invalid bitwidth for GEP index");
496 unsigned IdxId = BitWidth == 32 ? 0 : 1;
497 Slot = (Slot << 1) | IdxId;
505 // outputInstrVarArgsCall - Output the absurdly annoying varargs function calls.
506 // This are more annoying than most because the signature of the call does not
507 // tell us anything about the types of the arguments in the varargs portion.
508 // Because of this, we encode (as type 0) all of the argument types explicitly
509 // before the argument value. This really sucks, but you shouldn't be using
510 // varargs functions in your code! *death to printf*!
512 // Format: [opcode] [type] [numargs] [arg0] [arg1] ... [arg<numargs-1>]
514 void BytecodeWriter::outputInstrVarArgsCall(const Instruction *I,
516 const SlotCalculator &Table,
518 assert(isa<CallInst>(I) || isa<InvokeInst>(I));
519 // Opcode must have top two bits clear...
520 output_vbr(Opcode << 2); // Instruction Opcode ID
521 output_typeid(Type); // Result type (varargs type)
523 const PointerType *PTy = cast<PointerType>(I->getOperand(0)->getType());
524 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
525 unsigned NumParams = FTy->getNumParams();
527 unsigned NumFixedOperands;
528 if (isa<CallInst>(I)) {
529 // Output an operand for the callee and each fixed argument, then two for
530 // each variable argument.
531 NumFixedOperands = 1+NumParams;
533 assert(isa<InvokeInst>(I) && "Not call or invoke??");
534 // Output an operand for the callee and destinations, then two for each
535 // variable argument.
536 NumFixedOperands = 3+NumParams;
538 output_vbr(2 * I->getNumOperands()-NumFixedOperands +
539 unsigned(Opcode == 58 || isa<InvokeInst>(I)));
541 // The type for the function has already been emitted in the type field of the
542 // instruction. Just emit the slot # now.
543 for (unsigned i = 0; i != NumFixedOperands; ++i)
544 output_vbr(Table.getSlot(I->getOperand(i)));
546 for (unsigned i = NumFixedOperands, e = I->getNumOperands(); i != e; ++i) {
547 // Output Arg Type ID
548 output_typeid(Table.getTypeSlot(I->getOperand(i)->getType()));
550 // Output arg ID itself
551 output_vbr(Table.getSlot(I->getOperand(i)));
554 if (isa<InvokeInst>(I)) {
555 // Emit the tail call/calling conv for invoke instructions
556 output_vbr(cast<InvokeInst>(I)->getCallingConv());
557 } else if (Opcode == 58) {
558 const CallInst *CI = cast<CallInst>(I);
559 output_vbr((CI->getCallingConv() << 1) | unsigned(CI->isTailCall()));
564 // outputInstructionFormat1 - Output one operand instructions, knowing that no
565 // operand index is >= 2^12.
567 inline void BytecodeWriter::outputInstructionFormat1(const Instruction *I,
571 // bits Instruction format:
572 // --------------------------
573 // 01-00: Opcode type, fixed to 1.
575 // 19-08: Resulting type plane
576 // 31-20: Operand #1 (if set to (2^12-1), then zero operands)
578 output(1 | (Opcode << 2) | (Type << 8) | (Slots[0] << 20));
582 // outputInstructionFormat2 - Output two operand instructions, knowing that no
583 // operand index is >= 2^8.
585 inline void BytecodeWriter::outputInstructionFormat2(const Instruction *I,
589 // bits Instruction format:
590 // --------------------------
591 // 01-00: Opcode type, fixed to 2.
593 // 15-08: Resulting type plane
597 output(2 | (Opcode << 2) | (Type << 8) | (Slots[0] << 16) | (Slots[1] << 24));
601 // outputInstructionFormat3 - Output three operand instructions, knowing that no
602 // operand index is >= 2^6.
604 inline void BytecodeWriter::outputInstructionFormat3(const Instruction *I,
608 // bits Instruction format:
609 // --------------------------
610 // 01-00: Opcode type, fixed to 3.
612 // 13-08: Resulting type plane
617 output(3 | (Opcode << 2) | (Type << 8) |
618 (Slots[0] << 14) | (Slots[1] << 20) | (Slots[2] << 26));
621 void BytecodeWriter::outputInstruction(const Instruction &I) {
622 assert(I.getOpcode() < 57 && "Opcode too big???");
623 unsigned Opcode = I.getOpcode();
624 unsigned NumOperands = I.getNumOperands();
626 // Encode 'tail call' as 61
628 if (const CallInst *CI = dyn_cast<CallInst>(&I)) {
629 if (CI->getCallingConv() == CallingConv::C) {
630 if (CI->isTailCall())
631 Opcode = 61; // CCC + Tail Call
633 ; // Opcode = Instruction::Call
634 } else if (CI->getCallingConv() == CallingConv::Fast) {
635 if (CI->isTailCall())
636 Opcode = 59; // FastCC + TailCall
638 Opcode = 60; // FastCC + Not Tail Call
640 Opcode = 58; // Call escape sequence.
644 // Figure out which type to encode with the instruction. Typically we want
645 // the type of the first parameter, as opposed to the type of the instruction
646 // (for example, with setcc, we always know it returns bool, but the type of
647 // the first param is actually interesting). But if we have no arguments
648 // we take the type of the instruction itself.
651 switch (I.getOpcode()) {
652 case Instruction::Select:
653 case Instruction::Malloc:
654 case Instruction::Alloca:
655 Ty = I.getType(); // These ALWAYS want to encode the return type
657 case Instruction::Store:
658 Ty = I.getOperand(1)->getType(); // Encode the pointer type...
659 assert(isa<PointerType>(Ty) && "Store to nonpointer type!?!?");
661 default: // Otherwise use the default behavior...
662 Ty = NumOperands ? I.getOperand(0)->getType() : I.getType();
666 unsigned Type = Table.getTypeSlot(Ty);
668 // Varargs calls and invokes are encoded entirely different from any other
670 if (const CallInst *CI = dyn_cast<CallInst>(&I)){
671 const PointerType *Ty =cast<PointerType>(CI->getCalledValue()->getType());
672 if (cast<FunctionType>(Ty->getElementType())->isVarArg()) {
673 outputInstrVarArgsCall(CI, Opcode, Table, Type);
676 } else if (const InvokeInst *II = dyn_cast<InvokeInst>(&I)) {
677 const PointerType *Ty =cast<PointerType>(II->getCalledValue()->getType());
678 if (cast<FunctionType>(Ty->getElementType())->isVarArg()) {
679 outputInstrVarArgsCall(II, Opcode, Table, Type);
684 if (NumOperands <= 3) {
685 // Make sure that we take the type number into consideration. We don't want
686 // to overflow the field size for the instruction format we select.
688 unsigned MaxOpSlot = Type;
689 unsigned Slots[3]; Slots[0] = (1 << 12)-1; // Marker to signify 0 operands
691 for (unsigned i = 0; i != NumOperands; ++i) {
692 unsigned Slot = Table.getSlot(I.getOperand(i));
693 if (Slot > MaxOpSlot) MaxOpSlot = Slot;
697 // Handle the special cases for various instructions...
698 if (isa<CastInst>(I) || isa<VAArgInst>(I)) {
699 // Cast has to encode the destination type as the second argument in the
700 // packet, or else we won't know what type to cast to!
701 Slots[1] = Table.getTypeSlot(I.getType());
702 if (Slots[1] > MaxOpSlot) MaxOpSlot = Slots[1];
704 } else if (const AllocationInst *AI = dyn_cast<AllocationInst>(&I)) {
705 assert(NumOperands == 1 && "Bogus allocation!");
706 if (AI->getAlignment()) {
707 Slots[1] = Log2_32(AI->getAlignment())+1;
708 if (Slots[1] > MaxOpSlot) MaxOpSlot = Slots[1];
711 } else if (isa<ICmpInst>(I) || isa<FCmpInst>(I)) {
712 // We need to encode the compare instruction's predicate as the third
713 // operand. Its not really a slot, but we don't want to break the
714 // instruction format for these instructions.
716 assert(NumOperands == 3 && "CmpInst with wrong number of operands?");
717 Slots[2] = unsigned(cast<CmpInst>(&I)->getPredicate());
718 if (Slots[2] > MaxOpSlot)
719 MaxOpSlot = Slots[2];
720 } else if (const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(&I)) {
721 // We need to encode the type of sequential type indices into their slot #
723 for (gep_type_iterator I = gep_type_begin(GEP), E = gep_type_end(GEP);
725 if (isa<SequentialType>(*I)) {
726 // These should be either 32-bits or 64-bits, however, with bit
727 // accurate types we just distinguish between less than or equal to
728 // 32-bits or greater than 32-bits.
730 cast<IntegerType>(GEP->getOperand(Idx)->getType())->getBitWidth();
731 assert(BitWidth == 32 || BitWidth == 64 &&
732 "Invalid bitwidth for GEP index");
733 unsigned IdxId = BitWidth == 32 ? 0 : 1;
734 Slots[Idx] = (Slots[Idx] << 1) | IdxId;
735 if (Slots[Idx] > MaxOpSlot) MaxOpSlot = Slots[Idx];
737 } else if (Opcode == 58) {
738 // If this is the escape sequence for call, emit the tailcall/cc info.
739 const CallInst &CI = cast<CallInst>(I);
741 if (NumOperands <= 3) {
742 Slots[NumOperands-1] =
743 (CI.getCallingConv() << 1)|unsigned(CI.isTailCall());
744 if (Slots[NumOperands-1] > MaxOpSlot)
745 MaxOpSlot = Slots[NumOperands-1];
747 } else if (isa<InvokeInst>(I)) {
748 // Invoke escape seq has at least 4 operands to encode.
750 } else if (const LoadInst *LI = dyn_cast<LoadInst>(&I)) {
751 // Encode attributed load as opcode 62
752 // We need to encode the attributes of the load instruction as the second
753 // operand. Its not really a slot, but we don't want to break the
754 // instruction format for these instructions.
755 if (LI->getAlignment() || LI->isVolatile()) {
757 Slots[1] = ((Log2_32(LI->getAlignment())+1)<<1) +
758 (LI->isVolatile() ? 1 : 0);
759 if (Slots[1] > MaxOpSlot)
760 MaxOpSlot = Slots[1];
763 } else if (const StoreInst *SI = dyn_cast<StoreInst>(&I)) {
764 // Encode attributed store as opcode 63
765 // We need to encode the attributes of the store instruction as the third
766 // operand. Its not really a slot, but we don't want to break the
767 // instruction format for these instructions.
768 if (SI->getAlignment() || SI->isVolatile()) {
770 Slots[2] = ((Log2_32(SI->getAlignment())+1)<<1) +
771 (SI->isVolatile() ? 1 : 0);
772 if (Slots[2] > MaxOpSlot)
773 MaxOpSlot = Slots[2];
778 // Decide which instruction encoding to use. This is determined primarily
779 // by the number of operands, and secondarily by whether or not the max
780 // operand will fit into the instruction encoding. More operands == fewer
783 switch (NumOperands) {
786 if (MaxOpSlot < (1 << 12)-1) { // -1 because we use 4095 to indicate 0 ops
787 outputInstructionFormat1(&I, Opcode, Slots, Type);
793 if (MaxOpSlot < (1 << 8)) {
794 outputInstructionFormat2(&I, Opcode, Slots, Type);
800 if (MaxOpSlot < (1 << 6)) {
801 outputInstructionFormat3(&I, Opcode, Slots, Type);
810 // If we weren't handled before here, we either have a large number of
811 // operands or a large operand index that we are referring to.
812 outputInstructionFormat0(&I, Opcode, Table, Type);
815 //===----------------------------------------------------------------------===//
816 //=== Block Output ===//
817 //===----------------------------------------------------------------------===//
819 BytecodeWriter::BytecodeWriter(std::vector<unsigned char> &o, const Module *M)
822 // Emit the signature...
823 static const unsigned char *Sig = (const unsigned char*)"llvm";
824 output_data(Sig, Sig+4);
826 // Emit the top level CLASS block.
827 BytecodeBlock ModuleBlock(BytecodeFormat::ModuleBlockID, *this, false, true);
829 // Output the version identifier
830 output_vbr(BCVersionNum);
832 // The Global type plane comes first
834 BytecodeBlock CPool(BytecodeFormat::GlobalTypePlaneBlockID, *this);
835 outputTypes(Type::FirstDerivedTyID);
838 // The ModuleInfoBlock follows directly after the type information
839 outputModuleInfoBlock(M);
841 // Output module level constants, used for global variable initializers
844 // Do the whole module now! Process each function at a time...
845 for (Module::const_iterator I = M->begin(), E = M->end(); I != E; ++I)
848 // Output the symbole table for types
849 outputTypeSymbolTable(M->getTypeSymbolTable());
851 // Output the symbol table for values
852 outputValueSymbolTable(M->getValueSymbolTable());
855 void BytecodeWriter::outputTypes(unsigned TypeNum) {
856 // Write the type plane for types first because earlier planes (e.g. for a
857 // primitive type like float) may have constants constructed using types
858 // coming later (e.g., via getelementptr from a pointer type). The type
859 // plane is needed before types can be fwd or bkwd referenced.
860 const std::vector<const Type*>& Types = Table.getTypes();
861 assert(!Types.empty() && "No types at all?");
862 assert(TypeNum <= Types.size() && "Invalid TypeNo index");
864 unsigned NumEntries = Types.size() - TypeNum;
866 // Output type header: [num entries]
867 output_vbr(NumEntries);
869 for (unsigned i = TypeNum; i < TypeNum+NumEntries; ++i)
870 outputType(Types[i]);
873 // Helper function for outputConstants().
874 // Writes out all the constants in the plane Plane starting at entry StartNo.
876 void BytecodeWriter::outputConstantsInPlane(const Value *const *Plane,
879 unsigned ValNo = StartNo;
881 // Scan through and ignore function arguments, global values, and constant
883 for (; ValNo < PlaneSize &&
884 (isa<Argument>(Plane[ValNo]) || isa<GlobalValue>(Plane[ValNo]) ||
885 (isa<ConstantArray>(Plane[ValNo]) &&
886 cast<ConstantArray>(Plane[ValNo])->isString())); ValNo++)
889 unsigned NC = ValNo; // Number of constants
890 for (; NC < PlaneSize && (isa<Constant>(Plane[NC]) ||
891 isa<InlineAsm>(Plane[NC])); NC++)
893 NC -= ValNo; // Convert from index into count
894 if (NC == 0) return; // Skip empty type planes...
896 // FIXME: Most slabs only have 1 or 2 entries! We should encode this much
899 // Put out type header: [num entries][type id number]
903 // Put out the Type ID Number.
904 output_typeid(Table.getTypeSlot(Plane[0]->getType()));
906 for (unsigned i = ValNo; i < ValNo+NC; ++i) {
907 const Value *V = Plane[i];
908 if (const Constant *C = dyn_cast<Constant>(V))
911 outputInlineAsm(cast<InlineAsm>(V));
915 static inline bool hasNullValue(const Type *Ty) {
916 return Ty != Type::LabelTy && Ty != Type::VoidTy && !isa<OpaqueType>(Ty);
919 void BytecodeWriter::outputConstants() {
920 BytecodeBlock CPool(BytecodeFormat::ConstantPoolBlockID, *this,
921 true /* Elide block if empty */);
923 unsigned NumPlanes = Table.getNumPlanes();
925 // Output module-level string constants before any other constants.
926 outputConstantStrings();
928 for (unsigned pno = 0; pno != NumPlanes; pno++) {
929 const SlotCalculator::TypePlane &Plane = Table.getPlane(pno);
930 if (!Plane.empty()) { // Skip empty type planes...
932 if (hasNullValue(Plane[0]->getType())) {
933 // Skip zero initializer
937 // Write out constants in the plane
938 outputConstantsInPlane(&Plane[0], Plane.size(), ValNo);
943 static unsigned getEncodedLinkage(const GlobalValue *GV) {
944 switch (GV->getLinkage()) {
945 default: assert(0 && "Invalid linkage!");
946 case GlobalValue::ExternalLinkage: return 0;
947 case GlobalValue::WeakLinkage: return 1;
948 case GlobalValue::AppendingLinkage: return 2;
949 case GlobalValue::InternalLinkage: return 3;
950 case GlobalValue::LinkOnceLinkage: return 4;
951 case GlobalValue::DLLImportLinkage: return 5;
952 case GlobalValue::DLLExportLinkage: return 6;
953 case GlobalValue::ExternalWeakLinkage: return 7;
957 static unsigned getEncodedVisibility(const GlobalValue *GV) {
958 switch (GV->getVisibility()) {
959 default: assert(0 && "Invalid visibility!");
960 case GlobalValue::DefaultVisibility: return 0;
961 case GlobalValue::HiddenVisibility: return 1;
965 void BytecodeWriter::outputModuleInfoBlock(const Module *M) {
966 BytecodeBlock ModuleInfoBlock(BytecodeFormat::ModuleGlobalInfoBlockID, *this);
968 // Give numbers to sections as we encounter them.
969 unsigned SectionIDCounter = 0;
970 std::vector<std::string> SectionNames;
971 std::map<std::string, unsigned> SectionID;
973 // Output the types for the global variables in the module...
974 for (Module::const_global_iterator I = M->global_begin(),
975 End = M->global_end(); I != End; ++I) {
976 unsigned Slot = Table.getTypeSlot(I->getType());
978 assert((I->hasInitializer() || !I->hasInternalLinkage()) &&
979 "Global must have an initializer or have external linkage!");
981 // Fields: bit0 = isConstant, bit1 = hasInitializer, bit2-4=Linkage,
982 // bit5 = isThreadLocal, bit6+ = Slot # for type.
983 bool HasExtensionWord = (I->getAlignment() != 0) ||
985 (I->getVisibility() != GlobalValue::DefaultVisibility);
987 // If we need to use the extension byte, set linkage=3(internal) and
988 // initializer = 0 (impossible!).
989 if (!HasExtensionWord) {
990 unsigned oSlot = (Slot << 6)| (((unsigned)I->isThreadLocal()) << 5) |
991 (getEncodedLinkage(I) << 2) | (I->hasInitializer() << 1)
992 | (unsigned)I->isConstant();
995 unsigned oSlot = (Slot << 6) | (((unsigned)I->isThreadLocal()) << 5) |
996 (3 << 2) | (0 << 1) | (unsigned)I->isConstant();
999 // The extension word has this format: bit 0 = has initializer, bit 1-3 =
1000 // linkage, bit 4-8 = alignment (log2), bit 9 = has SectionID,
1001 // bits 10-12 = visibility, bits 13+ = future use.
1002 unsigned ExtWord = (unsigned)I->hasInitializer() |
1003 (getEncodedLinkage(I) << 1) |
1004 ((Log2_32(I->getAlignment())+1) << 4) |
1005 ((unsigned)I->hasSection() << 9) |
1006 (getEncodedVisibility(I) << 10);
1007 output_vbr(ExtWord);
1008 if (I->hasSection()) {
1009 // Give section names unique ID's.
1010 unsigned &Entry = SectionID[I->getSection()];
1012 Entry = ++SectionIDCounter;
1013 SectionNames.push_back(I->getSection());
1019 // If we have an initializer, output it now.
1020 if (I->hasInitializer())
1021 output_vbr(Table.getSlot((Value*)I->getInitializer()));
1023 output_typeid(Table.getTypeSlot(Type::VoidTy));
1025 // Output the types of the functions in this module.
1026 for (Module::const_iterator I = M->begin(), End = M->end(); I != End; ++I) {
1027 unsigned Slot = Table.getTypeSlot(I->getType());
1028 assert(((Slot << 6) >> 6) == Slot && "Slot # too big!");
1029 unsigned CC = I->getCallingConv()+1;
1030 unsigned ID = (Slot << 5) | (CC & 15);
1032 if (I->isDeclaration()) // If external, we don't have an FunctionInfo block.
1035 if (I->getAlignment() || I->hasSection() || (CC & ~15) != 0 ||
1036 (I->isDeclaration() && I->hasDLLImportLinkage()) ||
1037 (I->isDeclaration() && I->hasExternalWeakLinkage())
1039 ID |= 1 << 31; // Do we need an extension word?
1043 if (ID & (1 << 31)) {
1044 // Extension byte: bits 0-4 = alignment, bits 5-9 = top nibble of calling
1045 // convention, bit 10 = hasSectionID., bits 11-12 = external linkage type
1046 unsigned extLinkage = 0;
1048 if (I->isDeclaration()) {
1049 if (I->hasDLLImportLinkage()) {
1051 } else if (I->hasExternalWeakLinkage()) {
1056 ID = (Log2_32(I->getAlignment())+1) | ((CC >> 4) << 5) |
1057 (I->hasSection() << 10) |
1058 ((extLinkage & 3) << 11);
1061 // Give section names unique ID's.
1062 if (I->hasSection()) {
1063 unsigned &Entry = SectionID[I->getSection()];
1065 Entry = ++SectionIDCounter;
1066 SectionNames.push_back(I->getSection());
1072 output_vbr(Table.getTypeSlot(Type::VoidTy) << 5);
1074 // Emit the list of dependent libraries for the Module.
1075 Module::lib_iterator LI = M->lib_begin();
1076 Module::lib_iterator LE = M->lib_end();
1077 output_vbr(unsigned(LE - LI)); // Emit the number of dependent libraries.
1078 for (; LI != LE; ++LI)
1081 // Output the target triple from the module
1082 output(M->getTargetTriple());
1084 // Output the data layout from the module
1085 output(M->getDataLayout());
1087 // Emit the table of section names.
1088 output_vbr((unsigned)SectionNames.size());
1089 for (unsigned i = 0, e = SectionNames.size(); i != e; ++i)
1090 output(SectionNames[i]);
1092 // Output the inline asm string.
1093 output(M->getModuleInlineAsm());
1096 void BytecodeWriter::outputInstructions(const Function *F) {
1097 BytecodeBlock ILBlock(BytecodeFormat::InstructionListBlockID, *this);
1098 for (Function::const_iterator BB = F->begin(), E = F->end(); BB != E; ++BB)
1099 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I!=E; ++I)
1100 outputInstruction(*I);
1103 void BytecodeWriter::outputFunction(const Function *F) {
1104 // If this is an external function, there is nothing else to emit!
1105 if (F->isDeclaration()) return;
1107 BytecodeBlock FunctionBlock(BytecodeFormat::FunctionBlockID, *this);
1108 unsigned rWord = (getEncodedVisibility(F) << 16) | getEncodedLinkage(F);
1111 // Get slot information about the function...
1112 Table.incorporateFunction(F);
1114 // Output all of the instructions in the body of the function
1115 outputInstructions(F);
1117 // If needed, output the symbol table for the function...
1118 outputValueSymbolTable(F->getValueSymbolTable());
1120 Table.purgeFunction();
1124 void BytecodeWriter::outputTypeSymbolTable(const TypeSymbolTable &TST) {
1125 // Do not output the block for an empty symbol table, it just wastes
1127 if (TST.empty()) return;
1129 // Create a header for the symbol table
1130 BytecodeBlock SymTabBlock(BytecodeFormat::TypeSymbolTableBlockID, *this,
1131 true/*ElideIfEmpty*/);
1132 // Write the number of types
1133 output_vbr(TST.size());
1135 // Write each of the types
1136 for (TypeSymbolTable::const_iterator TI = TST.begin(), TE = TST.end();
1138 // Symtab entry:[def slot #][name]
1139 output_typeid(Table.getTypeSlot(TI->second));
1144 void BytecodeWriter::outputValueSymbolTable(const ValueSymbolTable &VST) {
1145 // Do not output the Bytecode block for an empty symbol table, it just wastes
1147 if (VST.empty()) return;
1149 BytecodeBlock SymTabBlock(BytecodeFormat::ValueSymbolTableBlockID, *this,
1150 true/*ElideIfEmpty*/);
1152 // Organize the symbol table by type
1153 typedef SmallVector<const ValueName*, 8> PlaneMapVector;
1154 typedef DenseMap<const Type*, PlaneMapVector> PlaneMap;
1156 for (ValueSymbolTable::const_iterator SI = VST.begin(), SE = VST.end();
1158 Planes[SI->getValue()->getType()].push_back(&*SI);
1160 for (PlaneMap::iterator PI = Planes.begin(), PE = Planes.end();
1162 PlaneMapVector::const_iterator I = PI->second.begin();
1163 PlaneMapVector::const_iterator End = PI->second.end();
1165 if (I == End) continue; // Don't mess with an absent type...
1167 // Write the number of values in this plane
1168 output_vbr((unsigned)PI->second.size());
1170 // Write the slot number of the type for this plane
1171 output_typeid(Table.getTypeSlot(PI->first));
1173 // Write each of the values in this plane
1174 for (; I != End; ++I) {
1175 // Symtab entry: [def slot #][name]
1176 output_vbr(Table.getSlot((*I)->getValue()));
1177 output_str((*I)->getKeyData(), (*I)->getKeyLength());
1182 void llvm::WriteBytecodeToFile(const Module *M, OStream &Out,
1184 assert(M && "You can't write a null module!!");
1186 // Make sure that std::cout is put into binary mode for systems
1189 sys::Program::ChangeStdoutToBinary();
1191 // Create a vector of unsigned char for the bytecode output. We
1192 // reserve 256KBytes of space in the vector so that we avoid doing
1193 // lots of little allocations. 256KBytes is sufficient for a large
1194 // proportion of the bytecode files we will encounter. Larger files
1195 // will be automatically doubled in size as needed (std::vector
1197 std::vector<unsigned char> Buffer;
1198 Buffer.reserve(256 * 1024);
1200 // The BytecodeWriter populates Buffer for us.
1201 BytecodeWriter BCW(Buffer, M);
1203 // Keep track of how much we've written
1204 BytesWritten += Buffer.size();
1206 // Determine start and end points of the Buffer
1207 const unsigned char *FirstByte = &Buffer.front();
1209 // If we're supposed to compress this mess ...
1212 // We signal compression by using an alternate magic number for the
1213 // file. The compressed bytecode file's magic number is "llvc" instead
1215 char compressed_magic[4];
1216 compressed_magic[0] = 'l';
1217 compressed_magic[1] = 'l';
1218 compressed_magic[2] = 'v';
1219 compressed_magic[3] = 'c';
1221 Out.stream()->write(compressed_magic,4);
1223 // Compress everything after the magic number (which we altered)
1224 Compressor::compressToStream(
1225 (char*)(FirstByte+4), // Skip the magic number
1226 Buffer.size()-4, // Skip the magic number
1227 *Out.stream() // Where to write compressed data
1232 // We're not compressing, so just write the entire block.
1233 Out.stream()->write((char*)FirstByte, Buffer.size());
1236 // make sure it hits disk now
1237 Out.stream()->flush();