Added llvmgcc version to allow tests to be xfailed by frontend version.
[llvm-complete.git] / lib / Bytecode / Writer / Writer.cpp
blob80abcacee97d6f09e4ea9ccddb2c24be123727ff
1 //===-- Writer.cpp - Library for writing LLVM bytecode files --------------===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
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/CallingConv.h"
23 #include "llvm/Constants.h"
24 #include "llvm/DerivedTypes.h"
25 #include "llvm/InlineAsm.h"
26 #include "llvm/Instructions.h"
27 #include "llvm/Module.h"
28 #include "llvm/SymbolTable.h"
29 #include "llvm/Support/GetElementPtrTypeIterator.h"
30 #include "llvm/Support/Compressor.h"
31 #include "llvm/Support/MathExtras.h"
32 #include "llvm/ADT/STLExtras.h"
33 #include "llvm/ADT/Statistic.h"
34 #include <cstring>
35 #include <algorithm>
36 using namespace llvm;
38 /// This value needs to be incremented every time the bytecode format changes
39 /// so that the reader can distinguish which format of the bytecode file has
40 /// been written.
41 /// @brief The bytecode version number
42 const unsigned BCVersionNum = 5;
44 static RegisterPass<WriteBytecodePass> X("emitbytecode", "Bytecode Writer");
46 static Statistic<>
47 BytesWritten("bytecodewriter", "Number of bytecode bytes written");
49 //===----------------------------------------------------------------------===//
50 //=== Output Primitives ===//
51 //===----------------------------------------------------------------------===//
53 // output - If a position is specified, it must be in the valid portion of the
54 // string... note that this should be inlined always so only the relevant IF
55 // body should be included.
56 inline void BytecodeWriter::output(unsigned i, int pos) {
57 if (pos == -1) { // Be endian clean, little endian is our friend
58 Out.push_back((unsigned char)i);
59 Out.push_back((unsigned char)(i >> 8));
60 Out.push_back((unsigned char)(i >> 16));
61 Out.push_back((unsigned char)(i >> 24));
62 } else {
63 Out[pos ] = (unsigned char)i;
64 Out[pos+1] = (unsigned char)(i >> 8);
65 Out[pos+2] = (unsigned char)(i >> 16);
66 Out[pos+3] = (unsigned char)(i >> 24);
70 inline void BytecodeWriter::output(int i) {
71 output((unsigned)i);
74 /// output_vbr - Output an unsigned value, by using the least number of bytes
75 /// possible. This is useful because many of our "infinite" values are really
76 /// very small most of the time; but can be large a few times.
77 /// Data format used: If you read a byte with the high bit set, use the low
78 /// seven bits as data and then read another byte.
79 inline void BytecodeWriter::output_vbr(uint64_t i) {
80 while (1) {
81 if (i < 0x80) { // done?
82 Out.push_back((unsigned char)i); // We know the high bit is clear...
83 return;
86 // Nope, we are bigger than a character, output the next 7 bits and set the
87 // high bit to say that there is more coming...
88 Out.push_back(0x80 | ((unsigned char)i & 0x7F));
89 i >>= 7; // Shift out 7 bits now...
93 inline void BytecodeWriter::output_vbr(unsigned i) {
94 while (1) {
95 if (i < 0x80) { // done?
96 Out.push_back((unsigned char)i); // We know the high bit is clear...
97 return;
100 // Nope, we are bigger than a character, output the next 7 bits and set the
101 // high bit to say that there is more coming...
102 Out.push_back(0x80 | ((unsigned char)i & 0x7F));
103 i >>= 7; // Shift out 7 bits now...
107 inline void BytecodeWriter::output_typeid(unsigned i) {
108 if (i <= 0x00FFFFFF)
109 this->output_vbr(i);
110 else {
111 this->output_vbr(0x00FFFFFF);
112 this->output_vbr(i);
116 inline void BytecodeWriter::output_vbr(int64_t i) {
117 if (i < 0)
118 output_vbr(((uint64_t)(-i) << 1) | 1); // Set low order sign bit...
119 else
120 output_vbr((uint64_t)i << 1); // Low order bit is clear.
124 inline void BytecodeWriter::output_vbr(int i) {
125 if (i < 0)
126 output_vbr(((unsigned)(-i) << 1) | 1); // Set low order sign bit...
127 else
128 output_vbr((unsigned)i << 1); // Low order bit is clear.
131 inline void BytecodeWriter::output(const std::string &s) {
132 unsigned Len = s.length();
133 output_vbr(Len ); // Strings may have an arbitrary length...
134 Out.insert(Out.end(), s.begin(), s.end());
137 inline void BytecodeWriter::output_data(const void *Ptr, const void *End) {
138 Out.insert(Out.end(), (const unsigned char*)Ptr, (const unsigned char*)End);
141 inline void BytecodeWriter::output_float(float& FloatVal) {
142 /// FIXME: This isn't optimal, it has size problems on some platforms
143 /// where FP is not IEEE.
144 uint32_t i = FloatToBits(FloatVal);
145 Out.push_back( static_cast<unsigned char>( (i & 0xFF )));
146 Out.push_back( static_cast<unsigned char>( (i >> 8) & 0xFF));
147 Out.push_back( static_cast<unsigned char>( (i >> 16) & 0xFF));
148 Out.push_back( static_cast<unsigned char>( (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.
154 uint64_t i = DoubleToBits(DoubleVal);
155 Out.push_back( static_cast<unsigned char>( (i & 0xFF )));
156 Out.push_back( static_cast<unsigned char>( (i >> 8) & 0xFF));
157 Out.push_back( static_cast<unsigned char>( (i >> 16) & 0xFF));
158 Out.push_back( static_cast<unsigned char>( (i >> 24) & 0xFF));
159 Out.push_back( static_cast<unsigned char>( (i >> 32) & 0xFF));
160 Out.push_back( static_cast<unsigned char>( (i >> 40) & 0xFF));
161 Out.push_back( static_cast<unsigned char>( (i >> 48) & 0xFF));
162 Out.push_back( static_cast<unsigned char>( (i >> 56) & 0xFF));
165 inline BytecodeBlock::BytecodeBlock(unsigned ID, BytecodeWriter &w,
166 bool elideIfEmpty, bool hasLongFormat)
167 : Id(ID), Writer(w), ElideIfEmpty(elideIfEmpty), HasLongFormat(hasLongFormat){
169 if (HasLongFormat) {
170 w.output(ID);
171 w.output(0U); // For length in long format
172 } else {
173 w.output(0U); /// Place holder for ID and length for this block
175 Loc = w.size();
178 inline BytecodeBlock::~BytecodeBlock() { // Do backpatch when block goes out
179 // of scope...
180 if (Loc == Writer.size() && ElideIfEmpty) {
181 // If the block is empty, and we are allowed to, do not emit the block at
182 // all!
183 Writer.resize(Writer.size()-(HasLongFormat?8:4));
184 return;
187 if (HasLongFormat)
188 Writer.output(unsigned(Writer.size()-Loc), int(Loc-4));
189 else
190 Writer.output(unsigned(Writer.size()-Loc) << 5 | (Id & 0x1F), int(Loc-4));
193 //===----------------------------------------------------------------------===//
194 //=== Constant Output ===//
195 //===----------------------------------------------------------------------===//
197 void BytecodeWriter::outputType(const Type *T) {
198 output_vbr((unsigned)T->getTypeID());
200 // That's all there is to handling primitive types...
201 if (T->isPrimitiveType()) {
202 return; // We might do this if we alias a prim type: %x = type int
205 switch (T->getTypeID()) { // Handle derived types now.
206 case Type::FunctionTyID: {
207 const FunctionType *MT = cast<FunctionType>(T);
208 int Slot = Table.getSlot(MT->getReturnType());
209 assert(Slot != -1 && "Type used but not available!!");
210 output_typeid((unsigned)Slot);
212 // Output the number of arguments to function (+1 if varargs):
213 output_vbr((unsigned)MT->getNumParams()+MT->isVarArg());
215 // Output all of the arguments...
216 FunctionType::param_iterator I = MT->param_begin();
217 for (; I != MT->param_end(); ++I) {
218 Slot = Table.getSlot(*I);
219 assert(Slot != -1 && "Type used but not available!!");
220 output_typeid((unsigned)Slot);
223 // Terminate list with VoidTy if we are a varargs function...
224 if (MT->isVarArg())
225 output_typeid((unsigned)Type::VoidTyID);
226 break;
229 case Type::ArrayTyID: {
230 const ArrayType *AT = cast<ArrayType>(T);
231 int Slot = Table.getSlot(AT->getElementType());
232 assert(Slot != -1 && "Type used but not available!!");
233 output_typeid((unsigned)Slot);
234 output_vbr(AT->getNumElements());
235 break;
238 case Type::PackedTyID: {
239 const PackedType *PT = cast<PackedType>(T);
240 int Slot = Table.getSlot(PT->getElementType());
241 assert(Slot != -1 && "Type used but not available!!");
242 output_typeid((unsigned)Slot);
243 output_vbr(PT->getNumElements());
244 break;
248 case Type::StructTyID: {
249 const StructType *ST = cast<StructType>(T);
251 // Output all of the element types...
252 for (StructType::element_iterator I = ST->element_begin(),
253 E = ST->element_end(); I != E; ++I) {
254 int Slot = Table.getSlot(*I);
255 assert(Slot != -1 && "Type used but not available!!");
256 output_typeid((unsigned)Slot);
259 // Terminate list with VoidTy
260 output_typeid((unsigned)Type::VoidTyID);
261 break;
264 case Type::PointerTyID: {
265 const PointerType *PT = cast<PointerType>(T);
266 int Slot = Table.getSlot(PT->getElementType());
267 assert(Slot != -1 && "Type used but not available!!");
268 output_typeid((unsigned)Slot);
269 break;
272 case Type::OpaqueTyID:
273 // No need to emit anything, just the count of opaque types is enough.
274 break;
276 default:
277 std::cerr << __FILE__ << ":" << __LINE__ << ": Don't know how to serialize"
278 << " Type '" << T->getDescription() << "'\n";
279 break;
283 void BytecodeWriter::outputConstant(const Constant *CPV) {
284 assert((CPV->getType()->isPrimitiveType() || !CPV->isNullValue()) &&
285 "Shouldn't output null constants!");
287 // We must check for a ConstantExpr before switching by type because
288 // a ConstantExpr can be of any type, and has no explicit value.
290 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CPV)) {
291 // FIXME: Encoding of constant exprs could be much more compact!
292 assert(CE->getNumOperands() > 0 && "ConstantExpr with 0 operands");
293 assert(CE->getNumOperands() != 1 || CE->getOpcode() == Instruction::Cast);
294 output_vbr(1+CE->getNumOperands()); // flags as an expr
295 output_vbr(CE->getOpcode()); // flags as an expr
297 for (User::const_op_iterator OI = CE->op_begin(); OI != CE->op_end(); ++OI){
298 int Slot = Table.getSlot(*OI);
299 assert(Slot != -1 && "Unknown constant used in ConstantExpr!!");
300 output_vbr((unsigned)Slot);
301 Slot = Table.getSlot((*OI)->getType());
302 output_typeid((unsigned)Slot);
304 return;
305 } else if (isa<UndefValue>(CPV)) {
306 output_vbr(1U); // 1 -> UndefValue constant.
307 return;
308 } else {
309 output_vbr(0U); // flag as not a ConstantExpr
312 switch (CPV->getType()->getTypeID()) {
313 case Type::BoolTyID: // Boolean Types
314 if (cast<ConstantBool>(CPV)->getValue())
315 output_vbr(1U);
316 else
317 output_vbr(0U);
318 break;
320 case Type::UByteTyID: // Unsigned integer types...
321 case Type::UShortTyID:
322 case Type::UIntTyID:
323 case Type::ULongTyID:
324 output_vbr(cast<ConstantUInt>(CPV)->getValue());
325 break;
327 case Type::SByteTyID: // Signed integer types...
328 case Type::ShortTyID:
329 case Type::IntTyID:
330 case Type::LongTyID:
331 output_vbr(cast<ConstantSInt>(CPV)->getValue());
332 break;
334 case Type::ArrayTyID: {
335 const ConstantArray *CPA = cast<ConstantArray>(CPV);
336 assert(!CPA->isString() && "Constant strings should be handled specially!");
338 for (unsigned i = 0, e = CPA->getNumOperands(); i != e; ++i) {
339 int Slot = Table.getSlot(CPA->getOperand(i));
340 assert(Slot != -1 && "Constant used but not available!!");
341 output_vbr((unsigned)Slot);
343 break;
346 case Type::PackedTyID: {
347 const ConstantPacked *CP = cast<ConstantPacked>(CPV);
349 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i) {
350 int Slot = Table.getSlot(CP->getOperand(i));
351 assert(Slot != -1 && "Constant used but not available!!");
352 output_vbr((unsigned)Slot);
354 break;
357 case Type::StructTyID: {
358 const ConstantStruct *CPS = cast<ConstantStruct>(CPV);
360 for (unsigned i = 0, e = CPS->getNumOperands(); i != e; ++i) {
361 int Slot = Table.getSlot(CPS->getOperand(i));
362 assert(Slot != -1 && "Constant used but not available!!");
363 output_vbr((unsigned)Slot);
365 break;
368 case Type::PointerTyID:
369 assert(0 && "No non-null, non-constant-expr constants allowed!");
370 abort();
372 case Type::FloatTyID: { // Floating point types...
373 float Tmp = (float)cast<ConstantFP>(CPV)->getValue();
374 output_float(Tmp);
375 break;
377 case Type::DoubleTyID: {
378 double Tmp = cast<ConstantFP>(CPV)->getValue();
379 output_double(Tmp);
380 break;
383 case Type::VoidTyID:
384 case Type::LabelTyID:
385 default:
386 std::cerr << __FILE__ << ":" << __LINE__ << ": Don't know how to serialize"
387 << " type '" << *CPV->getType() << "'\n";
388 break;
390 return;
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.
399 output_vbr(~0U);
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 int Slot = Table.getSlot(Str->getType());
420 assert(Slot != -1 && "Constant string of unknown type?");
421 output_typeid((unsigned)Slot);
423 // Now that we emitted the type (which indicates the size of the string),
424 // emit all of the characters.
425 std::string Val = Str->getAsString();
426 output_data(Val.c_str(), Val.c_str()+Val.size());
430 //===----------------------------------------------------------------------===//
431 //=== Instruction Output ===//
432 //===----------------------------------------------------------------------===//
434 // outputInstructionFormat0 - Output those weird instructions that have a large
435 // number of operands or have large operands themselves.
437 // Format: [opcode] [type] [numargs] [arg0] [arg1] ... [arg<numargs-1>]
439 void BytecodeWriter::outputInstructionFormat0(const Instruction *I,
440 unsigned Opcode,
441 const SlotCalculator &Table,
442 unsigned Type) {
443 // Opcode must have top two bits clear...
444 output_vbr(Opcode << 2); // Instruction Opcode ID
445 output_typeid(Type); // Result type
447 unsigned NumArgs = I->getNumOperands();
448 output_vbr(NumArgs + (isa<CastInst>(I) ||
449 isa<VAArgInst>(I) || Opcode == 56 || Opcode == 58));
451 if (!isa<GetElementPtrInst>(&I)) {
452 for (unsigned i = 0; i < NumArgs; ++i) {
453 int Slot = Table.getSlot(I->getOperand(i));
454 assert(Slot >= 0 && "No slot number for value!?!?");
455 output_vbr((unsigned)Slot);
458 if (isa<CastInst>(I) || isa<VAArgInst>(I)) {
459 int Slot = Table.getSlot(I->getType());
460 assert(Slot != -1 && "Cast return type unknown?");
461 output_typeid((unsigned)Slot);
462 } else if (Opcode == 56) { // Invoke escape sequence
463 output_vbr(cast<InvokeInst>(I)->getCallingConv());
464 } else if (Opcode == 58) { // Call escape sequence
465 output_vbr((cast<CallInst>(I)->getCallingConv() << 1) |
466 unsigned(cast<CallInst>(I)->isTailCall()));
468 } else {
469 int Slot = Table.getSlot(I->getOperand(0));
470 assert(Slot >= 0 && "No slot number for value!?!?");
471 output_vbr(unsigned(Slot));
473 // We need to encode the type of sequential type indices into their slot #
474 unsigned Idx = 1;
475 for (gep_type_iterator TI = gep_type_begin(I), E = gep_type_end(I);
476 Idx != NumArgs; ++TI, ++Idx) {
477 Slot = Table.getSlot(I->getOperand(Idx));
478 assert(Slot >= 0 && "No slot number for value!?!?");
480 if (isa<SequentialType>(*TI)) {
481 unsigned IdxId;
482 switch (I->getOperand(Idx)->getType()->getTypeID()) {
483 default: assert(0 && "Unknown index type!");
484 case Type::UIntTyID: IdxId = 0; break;
485 case Type::IntTyID: IdxId = 1; break;
486 case Type::ULongTyID: IdxId = 2; break;
487 case Type::LongTyID: IdxId = 3; break;
489 Slot = (Slot << 2) | IdxId;
491 output_vbr(unsigned(Slot));
497 // outputInstrVarArgsCall - Output the absurdly annoying varargs function calls.
498 // This are more annoying than most because the signature of the call does not
499 // tell us anything about the types of the arguments in the varargs portion.
500 // Because of this, we encode (as type 0) all of the argument types explicitly
501 // before the argument value. This really sucks, but you shouldn't be using
502 // varargs functions in your code! *death to printf*!
504 // Format: [opcode] [type] [numargs] [arg0] [arg1] ... [arg<numargs-1>]
506 void BytecodeWriter::outputInstrVarArgsCall(const Instruction *I,
507 unsigned Opcode,
508 const SlotCalculator &Table,
509 unsigned Type) {
510 assert(isa<CallInst>(I) || isa<InvokeInst>(I));
511 // Opcode must have top two bits clear...
512 output_vbr(Opcode << 2); // Instruction Opcode ID
513 output_typeid(Type); // Result type (varargs type)
515 const PointerType *PTy = cast<PointerType>(I->getOperand(0)->getType());
516 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
517 unsigned NumParams = FTy->getNumParams();
519 unsigned NumFixedOperands;
520 if (isa<CallInst>(I)) {
521 // Output an operand for the callee and each fixed argument, then two for
522 // each variable argument.
523 NumFixedOperands = 1+NumParams;
524 } else {
525 assert(isa<InvokeInst>(I) && "Not call or invoke??");
526 // Output an operand for the callee and destinations, then two for each
527 // variable argument.
528 NumFixedOperands = 3+NumParams;
530 output_vbr(2 * I->getNumOperands()-NumFixedOperands);
532 // The type for the function has already been emitted in the type field of the
533 // instruction. Just emit the slot # now.
534 for (unsigned i = 0; i != NumFixedOperands; ++i) {
535 int Slot = Table.getSlot(I->getOperand(i));
536 assert(Slot >= 0 && "No slot number for value!?!?");
537 output_vbr((unsigned)Slot);
540 for (unsigned i = NumFixedOperands, e = I->getNumOperands(); i != e; ++i) {
541 // Output Arg Type ID
542 int Slot = Table.getSlot(I->getOperand(i)->getType());
543 assert(Slot >= 0 && "No slot number for value!?!?");
544 output_typeid((unsigned)Slot);
546 // Output arg ID itself
547 Slot = Table.getSlot(I->getOperand(i));
548 assert(Slot >= 0 && "No slot number for value!?!?");
549 output_vbr((unsigned)Slot);
554 // outputInstructionFormat1 - Output one operand instructions, knowing that no
555 // operand index is >= 2^12.
557 inline void BytecodeWriter::outputInstructionFormat1(const Instruction *I,
558 unsigned Opcode,
559 unsigned *Slots,
560 unsigned Type) {
561 // bits Instruction format:
562 // --------------------------
563 // 01-00: Opcode type, fixed to 1.
564 // 07-02: Opcode
565 // 19-08: Resulting type plane
566 // 31-20: Operand #1 (if set to (2^12-1), then zero operands)
568 output(1 | (Opcode << 2) | (Type << 8) | (Slots[0] << 20));
572 // outputInstructionFormat2 - Output two operand instructions, knowing that no
573 // operand index is >= 2^8.
575 inline void BytecodeWriter::outputInstructionFormat2(const Instruction *I,
576 unsigned Opcode,
577 unsigned *Slots,
578 unsigned Type) {
579 // bits Instruction format:
580 // --------------------------
581 // 01-00: Opcode type, fixed to 2.
582 // 07-02: Opcode
583 // 15-08: Resulting type plane
584 // 23-16: Operand #1
585 // 31-24: Operand #2
587 output(2 | (Opcode << 2) | (Type << 8) | (Slots[0] << 16) | (Slots[1] << 24));
591 // outputInstructionFormat3 - Output three operand instructions, knowing that no
592 // operand index is >= 2^6.
594 inline void BytecodeWriter::outputInstructionFormat3(const Instruction *I,
595 unsigned Opcode,
596 unsigned *Slots,
597 unsigned Type) {
598 // bits Instruction format:
599 // --------------------------
600 // 01-00: Opcode type, fixed to 3.
601 // 07-02: Opcode
602 // 13-08: Resulting type plane
603 // 19-14: Operand #1
604 // 25-20: Operand #2
605 // 31-26: Operand #3
607 output(3 | (Opcode << 2) | (Type << 8) |
608 (Slots[0] << 14) | (Slots[1] << 20) | (Slots[2] << 26));
611 void BytecodeWriter::outputInstruction(const Instruction &I) {
612 assert(I.getOpcode() < 56 && "Opcode too big???");
613 unsigned Opcode = I.getOpcode();
614 unsigned NumOperands = I.getNumOperands();
616 // Encode 'tail call' as 61, 'volatile load' as 62, and 'volatile store' as
617 // 63.
618 if (const CallInst *CI = dyn_cast<CallInst>(&I)) {
619 if (CI->getCallingConv() == CallingConv::C) {
620 if (CI->isTailCall())
621 Opcode = 61; // CCC + Tail Call
622 else
623 ; // Opcode = Instruction::Call
624 } else if (CI->getCallingConv() == CallingConv::Fast) {
625 if (CI->isTailCall())
626 Opcode = 59; // FastCC + TailCall
627 else
628 Opcode = 60; // FastCC + Not Tail Call
629 } else {
630 Opcode = 58; // Call escape sequence.
632 } else if (const InvokeInst *II = dyn_cast<InvokeInst>(&I)) {
633 if (II->getCallingConv() == CallingConv::Fast)
634 Opcode = 57; // FastCC invoke.
635 else if (II->getCallingConv() != CallingConv::C)
636 Opcode = 56; // Invoke escape sequence.
638 } else if (isa<LoadInst>(I) && cast<LoadInst>(I).isVolatile()) {
639 Opcode = 62;
640 } else if (isa<StoreInst>(I) && cast<StoreInst>(I).isVolatile()) {
641 Opcode = 63;
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.
650 const Type *Ty;
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
656 break;
657 case Instruction::Store:
658 Ty = I.getOperand(1)->getType(); // Encode the pointer type...
659 assert(isa<PointerType>(Ty) && "Store to nonpointer type!?!?");
660 break;
661 default: // Otherwise use the default behavior...
662 Ty = NumOperands ? I.getOperand(0)->getType() : I.getType();
663 break;
666 unsigned Type;
667 int Slot = Table.getSlot(Ty);
668 assert(Slot != -1 && "Type not available!!?!");
669 Type = (unsigned)Slot;
671 // Varargs calls and invokes are encoded entirely different from any other
672 // instructions.
673 if (const CallInst *CI = dyn_cast<CallInst>(&I)){
674 const PointerType *Ty =cast<PointerType>(CI->getCalledValue()->getType());
675 if (cast<FunctionType>(Ty->getElementType())->isVarArg()) {
676 outputInstrVarArgsCall(CI, Opcode, Table, Type);
677 return;
679 } else if (const InvokeInst *II = dyn_cast<InvokeInst>(&I)) {
680 const PointerType *Ty =cast<PointerType>(II->getCalledValue()->getType());
681 if (cast<FunctionType>(Ty->getElementType())->isVarArg()) {
682 outputInstrVarArgsCall(II, Opcode, Table, Type);
683 return;
687 if (NumOperands <= 3) {
688 // Make sure that we take the type number into consideration. We don't want
689 // to overflow the field size for the instruction format we select.
691 unsigned MaxOpSlot = Type;
692 unsigned Slots[3]; Slots[0] = (1 << 12)-1; // Marker to signify 0 operands
694 for (unsigned i = 0; i != NumOperands; ++i) {
695 int slot = Table.getSlot(I.getOperand(i));
696 assert(slot != -1 && "Broken bytecode!");
697 if (unsigned(slot) > MaxOpSlot) MaxOpSlot = unsigned(slot);
698 Slots[i] = unsigned(slot);
701 // Handle the special cases for various instructions...
702 if (isa<CastInst>(I) || isa<VAArgInst>(I)) {
703 // Cast has to encode the destination type as the second argument in the
704 // packet, or else we won't know what type to cast to!
705 Slots[1] = Table.getSlot(I.getType());
706 assert(Slots[1] != ~0U && "Cast return type unknown?");
707 if (Slots[1] > MaxOpSlot) MaxOpSlot = Slots[1];
708 NumOperands++;
709 } else if (const AllocationInst *AI = dyn_cast<AllocationInst>(&I)) {
710 assert(NumOperands == 1 && "Bogus allocation!");
711 if (AI->getAlignment()) {
712 Slots[1] = Log2_32(AI->getAlignment())+1;
713 if (Slots[1] > MaxOpSlot) MaxOpSlot = Slots[1];
714 NumOperands = 2;
716 } else if (const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(&I)) {
717 // We need to encode the type of sequential type indices into their slot #
718 unsigned Idx = 1;
719 for (gep_type_iterator I = gep_type_begin(GEP), E = gep_type_end(GEP);
720 I != E; ++I, ++Idx)
721 if (isa<SequentialType>(*I)) {
722 unsigned IdxId;
723 switch (GEP->getOperand(Idx)->getType()->getTypeID()) {
724 default: assert(0 && "Unknown index type!");
725 case Type::UIntTyID: IdxId = 0; break;
726 case Type::IntTyID: IdxId = 1; break;
727 case Type::ULongTyID: IdxId = 2; break;
728 case Type::LongTyID: IdxId = 3; break;
730 Slots[Idx] = (Slots[Idx] << 2) | IdxId;
731 if (Slots[Idx] > MaxOpSlot) MaxOpSlot = Slots[Idx];
733 } else if (Opcode == 58) {
734 // If this is the escape sequence for call, emit the tailcall/cc info.
735 const CallInst &CI = cast<CallInst>(I);
736 ++NumOperands;
737 if (NumOperands < 3) {
738 Slots[NumOperands-1] = (CI.getCallingConv() << 1)|unsigned(CI.isTailCall());
739 if (Slots[NumOperands-1] > MaxOpSlot)
740 MaxOpSlot = Slots[NumOperands-1];
742 } else if (Opcode == 56) {
743 // Invoke escape seq has at least 4 operands to encode.
744 ++NumOperands;
747 // Decide which instruction encoding to use. This is determined primarily
748 // by the number of operands, and secondarily by whether or not the max
749 // operand will fit into the instruction encoding. More operands == fewer
750 // bits per operand.
752 switch (NumOperands) {
753 case 0:
754 case 1:
755 if (MaxOpSlot < (1 << 12)-1) { // -1 because we use 4095 to indicate 0 ops
756 outputInstructionFormat1(&I, Opcode, Slots, Type);
757 return;
759 break;
761 case 2:
762 if (MaxOpSlot < (1 << 8)) {
763 outputInstructionFormat2(&I, Opcode, Slots, Type);
764 return;
766 break;
768 case 3:
769 if (MaxOpSlot < (1 << 6)) {
770 outputInstructionFormat3(&I, Opcode, Slots, Type);
771 return;
773 break;
774 default:
775 break;
779 // If we weren't handled before here, we either have a large number of
780 // operands or a large operand index that we are referring to.
781 outputInstructionFormat0(&I, Opcode, Table, Type);
784 //===----------------------------------------------------------------------===//
785 //=== Block Output ===//
786 //===----------------------------------------------------------------------===//
788 BytecodeWriter::BytecodeWriter(std::vector<unsigned char> &o, const Module *M)
789 : Out(o), Table(M) {
791 // Emit the signature...
792 static const unsigned char *Sig = (const unsigned char*)"llvm";
793 output_data(Sig, Sig+4);
795 // Emit the top level CLASS block.
796 BytecodeBlock ModuleBlock(BytecodeFormat::ModuleBlockID, *this, false, true);
798 bool isBigEndian = M->getEndianness() == Module::BigEndian;
799 bool hasLongPointers = M->getPointerSize() == Module::Pointer64;
800 bool hasNoEndianness = M->getEndianness() == Module::AnyEndianness;
801 bool hasNoPointerSize = M->getPointerSize() == Module::AnyPointerSize;
803 // Output the version identifier and other information.
804 unsigned Version = (BCVersionNum << 4) |
805 (unsigned)isBigEndian | (hasLongPointers << 1) |
806 (hasNoEndianness << 2) |
807 (hasNoPointerSize << 3);
808 output_vbr(Version);
810 // The Global type plane comes first
812 BytecodeBlock CPool(BytecodeFormat::GlobalTypePlaneBlockID, *this );
813 outputTypes(Type::FirstDerivedTyID);
816 // The ModuleInfoBlock follows directly after the type information
817 outputModuleInfoBlock(M);
819 // Output module level constants, used for global variable initializers
820 outputConstants(false);
822 // Do the whole module now! Process each function at a time...
823 for (Module::const_iterator I = M->begin(), E = M->end(); I != E; ++I)
824 outputFunction(I);
826 // If needed, output the symbol table for the module...
827 outputSymbolTable(M->getSymbolTable());
830 void BytecodeWriter::outputTypes(unsigned TypeNum) {
831 // Write the type plane for types first because earlier planes (e.g. for a
832 // primitive type like float) may have constants constructed using types
833 // coming later (e.g., via getelementptr from a pointer type). The type
834 // plane is needed before types can be fwd or bkwd referenced.
835 const std::vector<const Type*>& Types = Table.getTypes();
836 assert(!Types.empty() && "No types at all?");
837 assert(TypeNum <= Types.size() && "Invalid TypeNo index");
839 unsigned NumEntries = Types.size() - TypeNum;
841 // Output type header: [num entries]
842 output_vbr(NumEntries);
844 for (unsigned i = TypeNum; i < TypeNum+NumEntries; ++i)
845 outputType(Types[i]);
848 // Helper function for outputConstants().
849 // Writes out all the constants in the plane Plane starting at entry StartNo.
851 void BytecodeWriter::outputConstantsInPlane(const std::vector<const Value*>
852 &Plane, unsigned StartNo) {
853 unsigned ValNo = StartNo;
855 // Scan through and ignore function arguments, global values, and constant
856 // strings.
857 for (; ValNo < Plane.size() &&
858 (isa<Argument>(Plane[ValNo]) || isa<GlobalValue>(Plane[ValNo]) ||
859 (isa<ConstantArray>(Plane[ValNo]) &&
860 cast<ConstantArray>(Plane[ValNo])->isString())); ValNo++)
861 /*empty*/;
863 unsigned NC = ValNo; // Number of constants
864 for (; NC < Plane.size() && (isa<Constant>(Plane[NC]) ||
865 isa<InlineAsm>(Plane[NC])); NC++)
866 /*empty*/;
867 NC -= ValNo; // Convert from index into count
868 if (NC == 0) return; // Skip empty type planes...
870 // FIXME: Most slabs only have 1 or 2 entries! We should encode this much
871 // more compactly.
873 // Output type header: [num entries][type id number]
875 output_vbr(NC);
877 // Output the Type ID Number...
878 int Slot = Table.getSlot(Plane.front()->getType());
879 assert (Slot != -1 && "Type in constant pool but not in function!!");
880 output_typeid((unsigned)Slot);
882 for (unsigned i = ValNo; i < ValNo+NC; ++i) {
883 const Value *V = Plane[i];
884 if (const Constant *C = dyn_cast<Constant>(V))
885 outputConstant(C);
886 else
887 outputInlineAsm(cast<InlineAsm>(V));
891 static inline bool hasNullValue(const Type *Ty) {
892 return Ty != Type::LabelTy && Ty != Type::VoidTy && !isa<OpaqueType>(Ty);
895 void BytecodeWriter::outputConstants(bool isFunction) {
896 BytecodeBlock CPool(BytecodeFormat::ConstantPoolBlockID, *this,
897 true /* Elide block if empty */);
899 unsigned NumPlanes = Table.getNumPlanes();
901 if (isFunction)
902 // Output the type plane before any constants!
903 outputTypes(Table.getModuleTypeLevel());
904 else
905 // Output module-level string constants before any other constants.
906 outputConstantStrings();
908 for (unsigned pno = 0; pno != NumPlanes; pno++) {
909 const std::vector<const Value*> &Plane = Table.getPlane(pno);
910 if (!Plane.empty()) { // Skip empty type planes...
911 unsigned ValNo = 0;
912 if (isFunction) // Don't re-emit module constants
913 ValNo += Table.getModuleLevel(pno);
915 if (hasNullValue(Plane[0]->getType())) {
916 // Skip zero initializer
917 if (ValNo == 0)
918 ValNo = 1;
921 // Write out constants in the plane
922 outputConstantsInPlane(Plane, ValNo);
927 static unsigned getEncodedLinkage(const GlobalValue *GV) {
928 switch (GV->getLinkage()) {
929 default: assert(0 && "Invalid linkage!");
930 case GlobalValue::ExternalLinkage: return 0;
931 case GlobalValue::WeakLinkage: return 1;
932 case GlobalValue::AppendingLinkage: return 2;
933 case GlobalValue::InternalLinkage: return 3;
934 case GlobalValue::LinkOnceLinkage: return 4;
938 void BytecodeWriter::outputModuleInfoBlock(const Module *M) {
939 BytecodeBlock ModuleInfoBlock(BytecodeFormat::ModuleGlobalInfoBlockID, *this);
941 // Give numbers to sections as we encounter them.
942 unsigned SectionIDCounter = 0;
943 std::vector<std::string> SectionNames;
944 std::map<std::string, unsigned> SectionID;
946 // Output the types for the global variables in the module...
947 for (Module::const_global_iterator I = M->global_begin(),
948 End = M->global_end(); I != End; ++I) {
949 int Slot = Table.getSlot(I->getType());
950 assert(Slot != -1 && "Module global vars is broken!");
952 assert((I->hasInitializer() || !I->hasInternalLinkage()) &&
953 "Global must have an initializer or have external linkage!");
955 // Fields: bit0 = isConstant, bit1 = hasInitializer, bit2-4=Linkage,
956 // bit5+ = Slot # for type.
957 bool HasExtensionWord = (I->getAlignment() != 0) || I->hasSection();
959 // If we need to use the extension byte, set linkage=3(internal) and
960 // initializer = 0 (impossible!).
961 if (!HasExtensionWord) {
962 unsigned oSlot = ((unsigned)Slot << 5) | (getEncodedLinkage(I) << 2) |
963 (I->hasInitializer() << 1) | (unsigned)I->isConstant();
964 output_vbr(oSlot);
965 } else {
966 unsigned oSlot = ((unsigned)Slot << 5) | (3 << 2) |
967 (0 << 1) | (unsigned)I->isConstant();
968 output_vbr(oSlot);
970 // The extension word has this format: bit 0 = has initializer, bit 1-3 =
971 // linkage, bit 4-8 = alignment (log2), bit 9 = has SectionID,
972 // bits 10+ = future use.
973 unsigned ExtWord = (unsigned)I->hasInitializer() |
974 (getEncodedLinkage(I) << 1) |
975 ((Log2_32(I->getAlignment())+1) << 4) |
976 ((unsigned)I->hasSection() << 9);
977 output_vbr(ExtWord);
978 if (I->hasSection()) {
979 // Give section names unique ID's.
980 unsigned &Entry = SectionID[I->getSection()];
981 if (Entry == 0) {
982 Entry = ++SectionIDCounter;
983 SectionNames.push_back(I->getSection());
985 output_vbr(Entry);
989 // If we have an initializer, output it now.
990 if (I->hasInitializer()) {
991 Slot = Table.getSlot((Value*)I->getInitializer());
992 assert(Slot != -1 && "No slot for global var initializer!");
993 output_vbr((unsigned)Slot);
996 output_typeid((unsigned)Table.getSlot(Type::VoidTy));
998 // Output the types of the functions in this module.
999 for (Module::const_iterator I = M->begin(), End = M->end(); I != End; ++I) {
1000 int Slot = Table.getSlot(I->getType());
1001 assert(Slot != -1 && "Module slot calculator is broken!");
1002 assert(Slot >= Type::FirstDerivedTyID && "Derived type not in range!");
1003 assert(((Slot << 6) >> 6) == Slot && "Slot # too big!");
1004 unsigned CC = I->getCallingConv()+1;
1005 unsigned ID = (Slot << 5) | (CC & 15);
1007 if (I->isExternal()) // If external, we don't have an FunctionInfo block.
1008 ID |= 1 << 4;
1010 if (I->getAlignment() || I->hasSection() || (CC & ~15) != 0)
1011 ID |= 1 << 31; // Do we need an extension word?
1013 output_vbr(ID);
1015 if (ID & (1 << 31)) {
1016 // Extension byte: bits 0-4 = alignment, bits 5-9 = top nibble of calling
1017 // convention, bit 10 = hasSectionID.
1018 ID = (Log2_32(I->getAlignment())+1) | ((CC >> 4) << 5) |
1019 (I->hasSection() << 10);
1020 output_vbr(ID);
1022 // Give section names unique ID's.
1023 if (I->hasSection()) {
1024 unsigned &Entry = SectionID[I->getSection()];
1025 if (Entry == 0) {
1026 Entry = ++SectionIDCounter;
1027 SectionNames.push_back(I->getSection());
1029 output_vbr(Entry);
1033 output_vbr((unsigned)Table.getSlot(Type::VoidTy) << 5);
1035 // Emit the list of dependent libraries for the Module.
1036 Module::lib_iterator LI = M->lib_begin();
1037 Module::lib_iterator LE = M->lib_end();
1038 output_vbr(unsigned(LE - LI)); // Emit the number of dependent libraries.
1039 for (; LI != LE; ++LI)
1040 output(*LI);
1042 // Output the target triple from the module
1043 output(M->getTargetTriple());
1045 // Emit the table of section names.
1046 output_vbr((unsigned)SectionNames.size());
1047 for (unsigned i = 0, e = SectionNames.size(); i != e; ++i)
1048 output(SectionNames[i]);
1050 // Output the inline asm string.
1051 output(M->getModuleInlineAsm());
1054 void BytecodeWriter::outputInstructions(const Function *F) {
1055 BytecodeBlock ILBlock(BytecodeFormat::InstructionListBlockID, *this);
1056 for (Function::const_iterator BB = F->begin(), E = F->end(); BB != E; ++BB)
1057 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I!=E; ++I)
1058 outputInstruction(*I);
1061 void BytecodeWriter::outputFunction(const Function *F) {
1062 // If this is an external function, there is nothing else to emit!
1063 if (F->isExternal()) return;
1065 BytecodeBlock FunctionBlock(BytecodeFormat::FunctionBlockID, *this);
1066 output_vbr(getEncodedLinkage(F));
1068 // Get slot information about the function...
1069 Table.incorporateFunction(F);
1071 if (Table.getCompactionTable().empty()) {
1072 // Output information about the constants in the function if the compaction
1073 // table is not being used.
1074 outputConstants(true);
1075 } else {
1076 // Otherwise, emit the compaction table.
1077 outputCompactionTable();
1080 // Output all of the instructions in the body of the function
1081 outputInstructions(F);
1083 // If needed, output the symbol table for the function...
1084 outputSymbolTable(F->getSymbolTable());
1086 Table.purgeFunction();
1089 void BytecodeWriter::outputCompactionTablePlane(unsigned PlaneNo,
1090 const std::vector<const Value*> &Plane,
1091 unsigned StartNo) {
1092 unsigned End = Table.getModuleLevel(PlaneNo);
1093 if (Plane.empty() || StartNo == End || End == 0) return; // Nothing to emit
1094 assert(StartNo < End && "Cannot emit negative range!");
1095 assert(StartNo < Plane.size() && End <= Plane.size());
1097 // Do not emit the null initializer!
1098 ++StartNo;
1100 // Figure out which encoding to use. By far the most common case we have is
1101 // to emit 0-2 entries in a compaction table plane.
1102 switch (End-StartNo) {
1103 case 0: // Avoid emitting two vbr's if possible.
1104 case 1:
1105 case 2:
1106 output_vbr((PlaneNo << 2) | End-StartNo);
1107 break;
1108 default:
1109 // Output the number of things.
1110 output_vbr((unsigned(End-StartNo) << 2) | 3);
1111 output_typeid(PlaneNo); // Emit the type plane this is
1112 break;
1115 for (unsigned i = StartNo; i != End; ++i)
1116 output_vbr(Table.getGlobalSlot(Plane[i]));
1119 void BytecodeWriter::outputCompactionTypes(unsigned StartNo) {
1120 // Get the compaction type table from the slot calculator
1121 const std::vector<const Type*> &CTypes = Table.getCompactionTypes();
1123 // The compaction types may have been uncompactified back to the
1124 // global types. If so, we just write an empty table
1125 if (CTypes.size() == 0 ) {
1126 output_vbr(0U);
1127 return;
1130 assert(CTypes.size() >= StartNo && "Invalid compaction types start index");
1132 // Determine how many types to write
1133 unsigned NumTypes = CTypes.size() - StartNo;
1135 // Output the number of types.
1136 output_vbr(NumTypes);
1138 for (unsigned i = StartNo; i < StartNo+NumTypes; ++i)
1139 output_typeid(Table.getGlobalSlot(CTypes[i]));
1142 void BytecodeWriter::outputCompactionTable() {
1143 // Avoid writing the compaction table at all if there is no content.
1144 if (Table.getCompactionTypes().size() >= Type::FirstDerivedTyID ||
1145 (!Table.CompactionTableIsEmpty())) {
1146 BytecodeBlock CTB(BytecodeFormat::CompactionTableBlockID, *this,
1147 true/*ElideIfEmpty*/);
1148 const std::vector<std::vector<const Value*> > &CT =
1149 Table.getCompactionTable();
1151 // First things first, emit the type compaction table if there is one.
1152 outputCompactionTypes(Type::FirstDerivedTyID);
1154 for (unsigned i = 0, e = CT.size(); i != e; ++i)
1155 outputCompactionTablePlane(i, CT[i], 0);
1159 void BytecodeWriter::outputSymbolTable(const SymbolTable &MST) {
1160 // Do not output the Bytecode block for an empty symbol table, it just wastes
1161 // space!
1162 if (MST.isEmpty()) return;
1164 BytecodeBlock SymTabBlock(BytecodeFormat::SymbolTableBlockID, *this,
1165 true/*ElideIfEmpty*/);
1167 // Write the number of types
1168 output_vbr(MST.num_types());
1170 // Write each of the types
1171 for (SymbolTable::type_const_iterator TI = MST.type_begin(),
1172 TE = MST.type_end(); TI != TE; ++TI ) {
1173 // Symtab entry:[def slot #][name]
1174 output_typeid((unsigned)Table.getSlot(TI->second));
1175 output(TI->first);
1178 // Now do each of the type planes in order.
1179 for (SymbolTable::plane_const_iterator PI = MST.plane_begin(),
1180 PE = MST.plane_end(); PI != PE; ++PI) {
1181 SymbolTable::value_const_iterator I = MST.value_begin(PI->first);
1182 SymbolTable::value_const_iterator End = MST.value_end(PI->first);
1183 int Slot;
1185 if (I == End) continue; // Don't mess with an absent type...
1187 // Write the number of values in this plane
1188 output_vbr((unsigned)PI->second.size());
1190 // Write the slot number of the type for this plane
1191 Slot = Table.getSlot(PI->first);
1192 assert(Slot != -1 && "Type in symtab, but not in table!");
1193 output_typeid((unsigned)Slot);
1195 // Write each of the values in this plane
1196 for (; I != End; ++I) {
1197 // Symtab entry: [def slot #][name]
1198 Slot = Table.getSlot(I->second);
1199 assert(Slot != -1 && "Value in symtab but has no slot number!!");
1200 output_vbr((unsigned)Slot);
1201 output(I->first);
1206 void llvm::WriteBytecodeToFile(const Module *M, std::ostream &Out,
1207 bool compress ) {
1208 assert(M && "You can't write a null module!!");
1210 // Create a vector of unsigned char for the bytecode output. We
1211 // reserve 256KBytes of space in the vector so that we avoid doing
1212 // lots of little allocations. 256KBytes is sufficient for a large
1213 // proportion of the bytecode files we will encounter. Larger files
1214 // will be automatically doubled in size as needed (std::vector
1215 // behavior).
1216 std::vector<unsigned char> Buffer;
1217 Buffer.reserve(256 * 1024);
1219 // The BytecodeWriter populates Buffer for us.
1220 BytecodeWriter BCW(Buffer, M);
1222 // Keep track of how much we've written
1223 BytesWritten += Buffer.size();
1225 // Determine start and end points of the Buffer
1226 const unsigned char *FirstByte = &Buffer.front();
1228 // If we're supposed to compress this mess ...
1229 if (compress) {
1231 // We signal compression by using an alternate magic number for the
1232 // file. The compressed bytecode file's magic number is "llvc" instead
1233 // of "llvm".
1234 char compressed_magic[4];
1235 compressed_magic[0] = 'l';
1236 compressed_magic[1] = 'l';
1237 compressed_magic[2] = 'v';
1238 compressed_magic[3] = 'c';
1240 Out.write(compressed_magic,4);
1242 // Compress everything after the magic number (which we altered)
1243 uint64_t zipSize = Compressor::compressToStream(
1244 (char*)(FirstByte+4), // Skip the magic number
1245 Buffer.size()-4, // Skip the magic number
1246 Out // Where to write compressed data
1249 } else {
1251 // We're not compressing, so just write the entire block.
1252 Out.write((char*)FirstByte, Buffer.size());
1255 // make sure it hits disk now
1256 Out.flush();