1 //===--- Bitcode/Writer/BitcodeWriter.cpp - Bitcode Writer ----------------===//
3 // The LLVM Compiler Infrastructure
5 // This file was developed by Chris Lattner and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // Bitcode writer implementation.
12 //===----------------------------------------------------------------------===//
14 #include "llvm/Bitcode/ReaderWriter.h"
15 #include "llvm/Bitcode/BitstreamWriter.h"
16 #include "llvm/Bitcode/LLVMBitCodes.h"
17 #include "ValueEnumerator.h"
18 #include "llvm/Constants.h"
19 #include "llvm/DerivedTypes.h"
20 #include "llvm/Instructions.h"
21 #include "llvm/Module.h"
22 #include "llvm/ParameterAttributes.h"
23 #include "llvm/TypeSymbolTable.h"
24 #include "llvm/ValueSymbolTable.h"
25 #include "llvm/Support/MathExtras.h"
28 /// These are manifest constants used by the bitcode writer. They do not need to
29 /// be kept in sync with the reader, but need to be consistent within this file.
33 // VALUE_SYMTAB_BLOCK abbrev id's.
34 VST_ENTRY_8_ABBREV = bitc::FIRST_APPLICATION_ABBREV,
41 static unsigned GetEncodedCastOpcode(unsigned Opcode) {
43 default: assert(0 && "Unknown cast instruction!");
44 case Instruction::Trunc : return bitc::CAST_TRUNC;
45 case Instruction::ZExt : return bitc::CAST_ZEXT;
46 case Instruction::SExt : return bitc::CAST_SEXT;
47 case Instruction::FPToUI : return bitc::CAST_FPTOUI;
48 case Instruction::FPToSI : return bitc::CAST_FPTOSI;
49 case Instruction::UIToFP : return bitc::CAST_UITOFP;
50 case Instruction::SIToFP : return bitc::CAST_SITOFP;
51 case Instruction::FPTrunc : return bitc::CAST_FPTRUNC;
52 case Instruction::FPExt : return bitc::CAST_FPEXT;
53 case Instruction::PtrToInt: return bitc::CAST_PTRTOINT;
54 case Instruction::IntToPtr: return bitc::CAST_INTTOPTR;
55 case Instruction::BitCast : return bitc::CAST_BITCAST;
59 static unsigned GetEncodedBinaryOpcode(unsigned Opcode) {
61 default: assert(0 && "Unknown binary instruction!");
62 case Instruction::Add: return bitc::BINOP_ADD;
63 case Instruction::Sub: return bitc::BINOP_SUB;
64 case Instruction::Mul: return bitc::BINOP_MUL;
65 case Instruction::UDiv: return bitc::BINOP_UDIV;
66 case Instruction::FDiv:
67 case Instruction::SDiv: return bitc::BINOP_SDIV;
68 case Instruction::URem: return bitc::BINOP_UREM;
69 case Instruction::FRem:
70 case Instruction::SRem: return bitc::BINOP_SREM;
71 case Instruction::Shl: return bitc::BINOP_SHL;
72 case Instruction::LShr: return bitc::BINOP_LSHR;
73 case Instruction::AShr: return bitc::BINOP_ASHR;
74 case Instruction::And: return bitc::BINOP_AND;
75 case Instruction::Or: return bitc::BINOP_OR;
76 case Instruction::Xor: return bitc::BINOP_XOR;
82 static void WriteStringRecord(unsigned Code, const std::string &Str,
83 unsigned AbbrevToUse, BitstreamWriter &Stream) {
84 SmallVector<unsigned, 64> Vals;
86 // Code: [strchar x N]
87 for (unsigned i = 0, e = Str.size(); i != e; ++i)
88 Vals.push_back(Str[i]);
90 // Emit the finished record.
91 Stream.EmitRecord(Code, Vals, AbbrevToUse);
94 // Emit information about parameter attributes.
95 static void WriteParamAttrTable(const ValueEnumerator &VE,
96 BitstreamWriter &Stream) {
97 const std::vector<const ParamAttrsList*> &Attrs = VE.getParamAttrs();
98 if (Attrs.empty()) return;
100 Stream.EnterSubblock(bitc::PARAMATTR_BLOCK_ID, 3);
102 SmallVector<uint64_t, 64> Record;
103 for (unsigned i = 0, e = Attrs.size(); i != e; ++i) {
104 const ParamAttrsList *A = Attrs[i];
105 for (unsigned op = 0, e = A->size(); op != e; ++op) {
106 Record.push_back(A->getParamIndex(op));
107 Record.push_back(A->getParamAttrsAtIndex(op));
110 Stream.EmitRecord(bitc::PARAMATTR_CODE_ENTRY, Record);
117 /// WriteTypeTable - Write out the type table for a module.
118 static void WriteTypeTable(const ValueEnumerator &VE, BitstreamWriter &Stream) {
119 const ValueEnumerator::TypeList &TypeList = VE.getTypes();
121 Stream.EnterSubblock(bitc::TYPE_BLOCK_ID, 4 /*count from # abbrevs */);
122 SmallVector<uint64_t, 64> TypeVals;
124 // Abbrev for TYPE_CODE_POINTER.
125 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
126 Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_POINTER));
127 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
128 Log2_32_Ceil(VE.getTypes().size()+1)));
129 unsigned PtrAbbrev = Stream.EmitAbbrev(Abbv);
131 // Abbrev for TYPE_CODE_FUNCTION.
132 Abbv = new BitCodeAbbrev();
133 Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_FUNCTION));
134 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // isvararg
135 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
136 Log2_32_Ceil(VE.getParamAttrs().size()+1)));
137 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
138 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
139 Log2_32_Ceil(VE.getTypes().size()+1)));
140 unsigned FunctionAbbrev = Stream.EmitAbbrev(Abbv);
142 // Abbrev for TYPE_CODE_STRUCT.
143 Abbv = new BitCodeAbbrev();
144 Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_STRUCT));
145 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // ispacked
146 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
147 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
148 Log2_32_Ceil(VE.getTypes().size()+1)));
149 unsigned StructAbbrev = Stream.EmitAbbrev(Abbv);
151 // Abbrev for TYPE_CODE_ARRAY.
152 Abbv = new BitCodeAbbrev();
153 Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_ARRAY));
154 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // size
155 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
156 Log2_32_Ceil(VE.getTypes().size()+1)));
157 unsigned ArrayAbbrev = Stream.EmitAbbrev(Abbv);
159 // Emit an entry count so the reader can reserve space.
160 TypeVals.push_back(TypeList.size());
161 Stream.EmitRecord(bitc::TYPE_CODE_NUMENTRY, TypeVals);
164 // Loop over all of the types, emitting each in turn.
165 for (unsigned i = 0, e = TypeList.size(); i != e; ++i) {
166 const Type *T = TypeList[i].first;
170 switch (T->getTypeID()) {
171 case Type::PackedStructTyID: // FIXME: Delete Type::PackedStructTyID.
172 default: assert(0 && "Unknown type!");
173 case Type::VoidTyID: Code = bitc::TYPE_CODE_VOID; break;
174 case Type::FloatTyID: Code = bitc::TYPE_CODE_FLOAT; break;
175 case Type::DoubleTyID: Code = bitc::TYPE_CODE_DOUBLE; break;
176 case Type::LabelTyID: Code = bitc::TYPE_CODE_LABEL; break;
177 case Type::OpaqueTyID: Code = bitc::TYPE_CODE_OPAQUE; break;
178 case Type::IntegerTyID:
180 Code = bitc::TYPE_CODE_INTEGER;
181 TypeVals.push_back(cast<IntegerType>(T)->getBitWidth());
183 case Type::PointerTyID:
184 // POINTER: [pointee type]
185 Code = bitc::TYPE_CODE_POINTER;
186 TypeVals.push_back(VE.getTypeID(cast<PointerType>(T)->getElementType()));
187 AbbrevToUse = PtrAbbrev;
190 case Type::FunctionTyID: {
191 const FunctionType *FT = cast<FunctionType>(T);
192 // FUNCTION: [isvararg, attrid, retty, paramty x N]
193 Code = bitc::TYPE_CODE_FUNCTION;
194 TypeVals.push_back(FT->isVarArg());
195 TypeVals.push_back(VE.getParamAttrID(FT->getParamAttrs()));
196 TypeVals.push_back(VE.getTypeID(FT->getReturnType()));
197 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i)
198 TypeVals.push_back(VE.getTypeID(FT->getParamType(i)));
199 AbbrevToUse = FunctionAbbrev;
202 case Type::StructTyID: {
203 const StructType *ST = cast<StructType>(T);
204 // STRUCT: [ispacked, eltty x N]
205 Code = bitc::TYPE_CODE_STRUCT;
206 TypeVals.push_back(ST->isPacked());
207 // Output all of the element types.
208 for (StructType::element_iterator I = ST->element_begin(),
209 E = ST->element_end(); I != E; ++I)
210 TypeVals.push_back(VE.getTypeID(*I));
211 AbbrevToUse = StructAbbrev;
214 case Type::ArrayTyID: {
215 const ArrayType *AT = cast<ArrayType>(T);
216 // ARRAY: [numelts, eltty]
217 Code = bitc::TYPE_CODE_ARRAY;
218 TypeVals.push_back(AT->getNumElements());
219 TypeVals.push_back(VE.getTypeID(AT->getElementType()));
220 AbbrevToUse = ArrayAbbrev;
223 case Type::VectorTyID: {
224 const VectorType *VT = cast<VectorType>(T);
225 // VECTOR [numelts, eltty]
226 Code = bitc::TYPE_CODE_VECTOR;
227 TypeVals.push_back(VT->getNumElements());
228 TypeVals.push_back(VE.getTypeID(VT->getElementType()));
233 // Emit the finished record.
234 Stream.EmitRecord(Code, TypeVals, AbbrevToUse);
241 static unsigned getEncodedLinkage(const GlobalValue *GV) {
242 switch (GV->getLinkage()) {
243 default: assert(0 && "Invalid linkage!");
244 case GlobalValue::ExternalLinkage: return 0;
245 case GlobalValue::WeakLinkage: return 1;
246 case GlobalValue::AppendingLinkage: return 2;
247 case GlobalValue::InternalLinkage: return 3;
248 case GlobalValue::LinkOnceLinkage: return 4;
249 case GlobalValue::DLLImportLinkage: return 5;
250 case GlobalValue::DLLExportLinkage: return 6;
251 case GlobalValue::ExternalWeakLinkage: return 7;
255 static unsigned getEncodedVisibility(const GlobalValue *GV) {
256 switch (GV->getVisibility()) {
257 default: assert(0 && "Invalid visibility!");
258 case GlobalValue::DefaultVisibility: return 0;
259 case GlobalValue::HiddenVisibility: return 1;
260 case GlobalValue::ProtectedVisibility: return 2;
264 // Emit top-level description of module, including target triple, inline asm,
265 // descriptors for global variables, and function prototype info.
266 static void WriteModuleInfo(const Module *M, const ValueEnumerator &VE,
267 BitstreamWriter &Stream) {
268 // Emit the list of dependent libraries for the Module.
269 for (Module::lib_iterator I = M->lib_begin(), E = M->lib_end(); I != E; ++I)
270 WriteStringRecord(bitc::MODULE_CODE_DEPLIB, *I, 0/*TODO*/, Stream);
272 // Emit various pieces of data attached to a module.
273 if (!M->getTargetTriple().empty())
274 WriteStringRecord(bitc::MODULE_CODE_TRIPLE, M->getTargetTriple(),
276 if (!M->getDataLayout().empty())
277 WriteStringRecord(bitc::MODULE_CODE_DATALAYOUT, M->getDataLayout(),
279 if (!M->getModuleInlineAsm().empty())
280 WriteStringRecord(bitc::MODULE_CODE_ASM, M->getModuleInlineAsm(),
283 // Emit information about sections, computing how many there are. Also
284 // compute the maximum alignment value.
285 std::map<std::string, unsigned> SectionMap;
286 unsigned MaxAlignment = 0;
287 unsigned MaxGlobalType = 0;
288 for (Module::const_global_iterator GV = M->global_begin(),E = M->global_end();
290 MaxAlignment = std::max(MaxAlignment, GV->getAlignment());
291 MaxGlobalType = std::max(MaxGlobalType, VE.getTypeID(GV->getType()));
293 if (!GV->hasSection()) continue;
294 // Give section names unique ID's.
295 unsigned &Entry = SectionMap[GV->getSection()];
296 if (Entry != 0) continue;
297 WriteStringRecord(bitc::MODULE_CODE_SECTIONNAME, GV->getSection(),
299 Entry = SectionMap.size();
301 for (Module::const_iterator F = M->begin(), E = M->end(); F != E; ++F) {
302 MaxAlignment = std::max(MaxAlignment, F->getAlignment());
303 if (!F->hasSection()) continue;
304 // Give section names unique ID's.
305 unsigned &Entry = SectionMap[F->getSection()];
306 if (Entry != 0) continue;
307 WriteStringRecord(bitc::MODULE_CODE_SECTIONNAME, F->getSection(),
309 Entry = SectionMap.size();
312 // Emit abbrev for globals, now that we know # sections and max alignment.
313 unsigned SimpleGVarAbbrev = 0;
314 if (!M->global_empty()) {
315 // Add an abbrev for common globals with no visibility or thread localness.
316 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
317 Abbv->Add(BitCodeAbbrevOp(bitc::MODULE_CODE_GLOBALVAR));
318 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
319 Log2_32_Ceil(MaxGlobalType+1)));
320 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Constant.
321 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Initializer.
322 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 3)); // Linkage.
323 if (MaxAlignment == 0) // Alignment.
324 Abbv->Add(BitCodeAbbrevOp(0));
326 unsigned MaxEncAlignment = Log2_32(MaxAlignment)+1;
327 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
328 Log2_32_Ceil(MaxEncAlignment+1)));
330 if (SectionMap.empty()) // Section.
331 Abbv->Add(BitCodeAbbrevOp(0));
333 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
334 Log2_32_Ceil(SectionMap.size()+1)));
335 // Don't bother emitting vis + thread local.
336 SimpleGVarAbbrev = Stream.EmitAbbrev(Abbv);
339 // Emit the global variable information.
340 SmallVector<unsigned, 64> Vals;
341 for (Module::const_global_iterator GV = M->global_begin(),E = M->global_end();
343 unsigned AbbrevToUse = 0;
345 // GLOBALVAR: [type, isconst, initid,
346 // linkage, alignment, section, visibility, threadlocal]
347 Vals.push_back(VE.getTypeID(GV->getType()));
348 Vals.push_back(GV->isConstant());
349 Vals.push_back(GV->isDeclaration() ? 0 :
350 (VE.getValueID(GV->getInitializer()) + 1));
351 Vals.push_back(getEncodedLinkage(GV));
352 Vals.push_back(Log2_32(GV->getAlignment())+1);
353 Vals.push_back(GV->hasSection() ? SectionMap[GV->getSection()] : 0);
354 if (GV->isThreadLocal() ||
355 GV->getVisibility() != GlobalValue::DefaultVisibility) {
356 Vals.push_back(getEncodedVisibility(GV));
357 Vals.push_back(GV->isThreadLocal());
359 AbbrevToUse = SimpleGVarAbbrev;
362 Stream.EmitRecord(bitc::MODULE_CODE_GLOBALVAR, Vals, AbbrevToUse);
366 // Emit the function proto information.
367 for (Module::const_iterator F = M->begin(), E = M->end(); F != E; ++F) {
368 // FUNCTION: [type, callingconv, isproto, linkage, alignment, section,
370 Vals.push_back(VE.getTypeID(F->getType()));
371 Vals.push_back(F->getCallingConv());
372 Vals.push_back(F->isDeclaration());
373 Vals.push_back(getEncodedLinkage(F));
374 Vals.push_back(Log2_32(F->getAlignment())+1);
375 Vals.push_back(F->hasSection() ? SectionMap[F->getSection()] : 0);
376 Vals.push_back(getEncodedVisibility(F));
378 unsigned AbbrevToUse = 0;
379 Stream.EmitRecord(bitc::MODULE_CODE_FUNCTION, Vals, AbbrevToUse);
384 // Emit the alias information.
385 for (Module::const_alias_iterator AI = M->alias_begin(), E = M->alias_end();
387 Vals.push_back(VE.getTypeID(AI->getType()));
388 Vals.push_back(VE.getValueID(AI->getAliasee()));
389 Vals.push_back(getEncodedLinkage(AI));
390 unsigned AbbrevToUse = 0;
391 Stream.EmitRecord(bitc::MODULE_CODE_ALIAS, Vals, AbbrevToUse);
397 static void WriteConstants(unsigned FirstVal, unsigned LastVal,
398 const ValueEnumerator &VE,
399 BitstreamWriter &Stream) {
400 if (FirstVal == LastVal) return;
402 Stream.EnterSubblock(bitc::CONSTANTS_BLOCK_ID, 2);
404 // FIXME: Install and use abbrevs to reduce size. Install them globally so
405 // they don't need to be reemitted for each function body.
407 SmallVector<uint64_t, 64> Record;
409 const ValueEnumerator::ValueList &Vals = VE.getValues();
410 const Type *LastTy = 0;
411 for (unsigned i = FirstVal; i != LastVal; ++i) {
412 const Value *V = Vals[i].first;
413 // If we need to switch types, do so now.
414 if (V->getType() != LastTy) {
415 LastTy = V->getType();
416 Record.push_back(VE.getTypeID(LastTy));
417 Stream.EmitRecord(bitc::CST_CODE_SETTYPE, Record);
421 if (const InlineAsm *IA = dyn_cast<InlineAsm>(V)) {
422 assert(0 && IA && "FIXME: Inline asm writing unimp!");
425 const Constant *C = cast<Constant>(V);
427 unsigned AbbrevToUse = 0;
428 if (C->isNullValue()) {
429 Code = bitc::CST_CODE_NULL;
430 } else if (isa<UndefValue>(C)) {
431 Code = bitc::CST_CODE_UNDEF;
432 } else if (const ConstantInt *IV = dyn_cast<ConstantInt>(C)) {
433 if (IV->getBitWidth() <= 64) {
434 int64_t V = IV->getSExtValue();
436 Record.push_back(V << 1);
438 Record.push_back((-V << 1) | 1);
439 Code = bitc::CST_CODE_INTEGER;
440 } else { // Wide integers, > 64 bits in size.
441 // We have an arbitrary precision integer value to write whose
442 // bit width is > 64. However, in canonical unsigned integer
443 // format it is likely that the high bits are going to be zero.
444 // So, we only write the number of active words.
445 unsigned NWords = IV->getValue().getActiveWords();
446 const uint64_t *RawWords = IV->getValue().getRawData();
447 for (unsigned i = 0; i != NWords; ++i) {
448 int64_t V = RawWords[i];
450 Record.push_back(V << 1);
452 Record.push_back((-V << 1) | 1);
454 Code = bitc::CST_CODE_WIDE_INTEGER;
456 } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
457 Code = bitc::CST_CODE_FLOAT;
458 if (CFP->getType() == Type::FloatTy) {
459 Record.push_back(FloatToBits((float)CFP->getValue()));
461 assert (CFP->getType() == Type::DoubleTy && "Unknown FP type!");
462 Record.push_back(DoubleToBits((double)CFP->getValue()));
464 } else if (isa<ConstantArray>(C) || isa<ConstantStruct>(V) ||
465 isa<ConstantVector>(V)) {
466 Code = bitc::CST_CODE_AGGREGATE;
467 for (unsigned i = 0, e = C->getNumOperands(); i != e; ++i)
468 Record.push_back(VE.getValueID(C->getOperand(i)));
469 } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
470 switch (CE->getOpcode()) {
472 if (Instruction::isCast(CE->getOpcode())) {
473 Code = bitc::CST_CODE_CE_CAST;
474 Record.push_back(GetEncodedCastOpcode(CE->getOpcode()));
475 Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
476 Record.push_back(VE.getValueID(C->getOperand(0)));
478 assert(CE->getNumOperands() == 2 && "Unknown constant expr!");
479 Code = bitc::CST_CODE_CE_BINOP;
480 Record.push_back(GetEncodedBinaryOpcode(CE->getOpcode()));
481 Record.push_back(VE.getValueID(C->getOperand(0)));
482 Record.push_back(VE.getValueID(C->getOperand(1)));
485 case Instruction::GetElementPtr:
486 Code = bitc::CST_CODE_CE_GEP;
487 for (unsigned i = 0, e = CE->getNumOperands(); i != e; ++i) {
488 Record.push_back(VE.getTypeID(C->getOperand(i)->getType()));
489 Record.push_back(VE.getValueID(C->getOperand(i)));
492 case Instruction::Select:
493 Code = bitc::CST_CODE_CE_SELECT;
494 Record.push_back(VE.getValueID(C->getOperand(0)));
495 Record.push_back(VE.getValueID(C->getOperand(1)));
496 Record.push_back(VE.getValueID(C->getOperand(2)));
498 case Instruction::ExtractElement:
499 Code = bitc::CST_CODE_CE_EXTRACTELT;
500 Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
501 Record.push_back(VE.getValueID(C->getOperand(0)));
502 Record.push_back(VE.getValueID(C->getOperand(1)));
504 case Instruction::InsertElement:
505 Code = bitc::CST_CODE_CE_INSERTELT;
506 Record.push_back(VE.getValueID(C->getOperand(0)));
507 Record.push_back(VE.getValueID(C->getOperand(1)));
508 Record.push_back(VE.getValueID(C->getOperand(2)));
510 case Instruction::ShuffleVector:
511 Code = bitc::CST_CODE_CE_SHUFFLEVEC;
512 Record.push_back(VE.getValueID(C->getOperand(0)));
513 Record.push_back(VE.getValueID(C->getOperand(1)));
514 Record.push_back(VE.getValueID(C->getOperand(2)));
516 case Instruction::ICmp:
517 case Instruction::FCmp:
518 Code = bitc::CST_CODE_CE_CMP;
519 Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
520 Record.push_back(VE.getValueID(C->getOperand(0)));
521 Record.push_back(VE.getValueID(C->getOperand(1)));
522 Record.push_back(CE->getPredicate());
526 assert(0 && "Unknown constant!");
528 Stream.EmitRecord(Code, Record, AbbrevToUse);
535 static void WriteModuleConstants(const ValueEnumerator &VE,
536 BitstreamWriter &Stream) {
537 const ValueEnumerator::ValueList &Vals = VE.getValues();
539 // Find the first constant to emit, which is the first non-globalvalue value.
540 // We know globalvalues have been emitted by WriteModuleInfo.
541 for (unsigned i = 0, e = Vals.size(); i != e; ++i) {
542 if (!isa<GlobalValue>(Vals[i].first)) {
543 WriteConstants(i, Vals.size(), VE, Stream);
549 /// WriteInstruction - Emit an instruction to the specified stream.
550 static void WriteInstruction(const Instruction &I, ValueEnumerator &VE,
551 BitstreamWriter &Stream,
552 SmallVector<unsigned, 64> &Vals) {
554 unsigned AbbrevToUse = 0;
555 switch (I.getOpcode()) {
557 if (Instruction::isCast(I.getOpcode())) {
558 Code = bitc::FUNC_CODE_INST_CAST;
559 Vals.push_back(GetEncodedCastOpcode(I.getOpcode()));
560 Vals.push_back(VE.getTypeID(I.getType()));
561 Vals.push_back(VE.getTypeID(I.getOperand(0)->getType()));
562 Vals.push_back(VE.getValueID(I.getOperand(0)));
564 assert(isa<BinaryOperator>(I) && "Unknown instruction!");
565 Code = bitc::FUNC_CODE_INST_BINOP;
566 Vals.push_back(GetEncodedBinaryOpcode(I.getOpcode()));
567 Vals.push_back(VE.getTypeID(I.getType()));
568 Vals.push_back(VE.getValueID(I.getOperand(0)));
569 Vals.push_back(VE.getValueID(I.getOperand(1)));
573 case Instruction::GetElementPtr:
574 Code = bitc::FUNC_CODE_INST_GEP;
575 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
576 Vals.push_back(VE.getTypeID(I.getOperand(i)->getType()));
577 Vals.push_back(VE.getValueID(I.getOperand(i)));
580 case Instruction::Select:
581 Code = bitc::FUNC_CODE_INST_SELECT;
582 Vals.push_back(VE.getTypeID(I.getType()));
583 Vals.push_back(VE.getValueID(I.getOperand(0)));
584 Vals.push_back(VE.getValueID(I.getOperand(1)));
585 Vals.push_back(VE.getValueID(I.getOperand(2)));
587 case Instruction::ExtractElement:
588 Code = bitc::FUNC_CODE_INST_EXTRACTELT;
589 Vals.push_back(VE.getTypeID(I.getOperand(0)->getType()));
590 Vals.push_back(VE.getValueID(I.getOperand(0)));
591 Vals.push_back(VE.getValueID(I.getOperand(1)));
593 case Instruction::InsertElement:
594 Code = bitc::FUNC_CODE_INST_INSERTELT;
595 Vals.push_back(VE.getTypeID(I.getType()));
596 Vals.push_back(VE.getValueID(I.getOperand(0)));
597 Vals.push_back(VE.getValueID(I.getOperand(1)));
598 Vals.push_back(VE.getValueID(I.getOperand(2)));
600 case Instruction::ShuffleVector:
601 Code = bitc::FUNC_CODE_INST_SHUFFLEVEC;
602 Vals.push_back(VE.getTypeID(I.getType()));
603 Vals.push_back(VE.getValueID(I.getOperand(0)));
604 Vals.push_back(VE.getValueID(I.getOperand(1)));
605 Vals.push_back(VE.getValueID(I.getOperand(2)));
607 case Instruction::ICmp:
608 case Instruction::FCmp:
609 Code = bitc::FUNC_CODE_INST_CMP;
610 Vals.push_back(VE.getTypeID(I.getOperand(0)->getType()));
611 Vals.push_back(VE.getValueID(I.getOperand(0)));
612 Vals.push_back(VE.getValueID(I.getOperand(1)));
613 Vals.push_back(cast<CmpInst>(I).getPredicate());
616 case Instruction::Ret:
617 Code = bitc::FUNC_CODE_INST_RET;
618 if (I.getNumOperands()) {
619 Vals.push_back(VE.getTypeID(I.getOperand(0)->getType()));
620 Vals.push_back(VE.getValueID(I.getOperand(0)));
623 case Instruction::Br:
624 Code = bitc::FUNC_CODE_INST_BR;
625 Vals.push_back(VE.getValueID(I.getOperand(0)));
626 if (cast<BranchInst>(I).isConditional()) {
627 Vals.push_back(VE.getValueID(I.getOperand(1)));
628 Vals.push_back(VE.getValueID(I.getOperand(2)));
631 case Instruction::Switch:
632 Code = bitc::FUNC_CODE_INST_SWITCH;
633 Vals.push_back(VE.getTypeID(I.getOperand(0)->getType()));
634 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
635 Vals.push_back(VE.getValueID(I.getOperand(i)));
637 case Instruction::Invoke: {
638 Code = bitc::FUNC_CODE_INST_INVOKE;
639 Vals.push_back(cast<InvokeInst>(I).getCallingConv());
640 Vals.push_back(VE.getTypeID(I.getOperand(0)->getType()));
641 Vals.push_back(VE.getValueID(I.getOperand(0))); // callee
642 Vals.push_back(VE.getValueID(I.getOperand(1))); // normal
643 Vals.push_back(VE.getValueID(I.getOperand(2))); // unwind
645 // Emit value #'s for the fixed parameters.
646 const PointerType *PTy = cast<PointerType>(I.getOperand(0)->getType());
647 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
648 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
649 Vals.push_back(VE.getValueID(I.getOperand(i+3))); // fixed param.
651 // Emit type/value pairs for varargs params.
652 if (FTy->isVarArg()) {
653 unsigned NumVarargs = I.getNumOperands()-3-FTy->getNumParams();
654 for (unsigned i = I.getNumOperands()-NumVarargs, e = I.getNumOperands();
656 Vals.push_back(VE.getTypeID(I.getOperand(i)->getType()));
657 Vals.push_back(VE.getValueID(I.getOperand(i)));
662 case Instruction::Unwind:
663 Code = bitc::FUNC_CODE_INST_UNWIND;
665 case Instruction::Unreachable:
666 Code = bitc::FUNC_CODE_INST_UNREACHABLE;
669 case Instruction::PHI:
670 Code = bitc::FUNC_CODE_INST_PHI;
671 Vals.push_back(VE.getTypeID(I.getType()));
672 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
673 Vals.push_back(VE.getValueID(I.getOperand(i)));
676 case Instruction::Malloc:
677 Code = bitc::FUNC_CODE_INST_MALLOC;
678 Vals.push_back(VE.getTypeID(I.getType()));
679 Vals.push_back(VE.getValueID(I.getOperand(0))); // size.
680 Vals.push_back(Log2_32(cast<MallocInst>(I).getAlignment())+1);
683 case Instruction::Free:
684 Code = bitc::FUNC_CODE_INST_FREE;
685 Vals.push_back(VE.getTypeID(I.getOperand(0)->getType()));
686 Vals.push_back(VE.getValueID(I.getOperand(0)));
689 case Instruction::Alloca:
690 Code = bitc::FUNC_CODE_INST_ALLOCA;
691 Vals.push_back(VE.getTypeID(I.getType()));
692 Vals.push_back(VE.getValueID(I.getOperand(0))); // size.
693 Vals.push_back(Log2_32(cast<AllocaInst>(I).getAlignment())+1);
696 case Instruction::Load:
697 Code = bitc::FUNC_CODE_INST_LOAD;
698 Vals.push_back(VE.getTypeID(I.getOperand(0)->getType()));
699 Vals.push_back(VE.getValueID(I.getOperand(0))); // ptr.
700 Vals.push_back(Log2_32(cast<LoadInst>(I).getAlignment())+1);
701 Vals.push_back(cast<LoadInst>(I).isVolatile());
703 case Instruction::Store:
704 Code = bitc::FUNC_CODE_INST_STORE;
705 Vals.push_back(VE.getTypeID(I.getOperand(1)->getType())); // Pointer
706 Vals.push_back(VE.getValueID(I.getOperand(0))); // val.
707 Vals.push_back(VE.getValueID(I.getOperand(1))); // ptr.
708 Vals.push_back(Log2_32(cast<StoreInst>(I).getAlignment())+1);
709 Vals.push_back(cast<StoreInst>(I).isVolatile());
711 case Instruction::Call: {
712 Code = bitc::FUNC_CODE_INST_CALL;
713 Vals.push_back((cast<CallInst>(I).getCallingConv() << 1) |
714 cast<CallInst>(I).isTailCall());
715 Vals.push_back(VE.getTypeID(I.getOperand(0)->getType()));
716 Vals.push_back(VE.getValueID(I.getOperand(0))); // callee
718 // Emit value #'s for the fixed parameters.
719 const PointerType *PTy = cast<PointerType>(I.getOperand(0)->getType());
720 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
721 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
722 Vals.push_back(VE.getValueID(I.getOperand(i+1))); // fixed param.
724 // Emit type/value pairs for varargs params.
725 if (FTy->isVarArg()) {
726 unsigned NumVarargs = I.getNumOperands()-1-FTy->getNumParams();
727 for (unsigned i = I.getNumOperands()-NumVarargs, e = I.getNumOperands();
729 Vals.push_back(VE.getTypeID(I.getOperand(i)->getType()));
730 Vals.push_back(VE.getValueID(I.getOperand(i)));
735 case Instruction::VAArg:
736 Code = bitc::FUNC_CODE_INST_VAARG;
737 Vals.push_back(VE.getTypeID(I.getOperand(0)->getType())); // valistty
738 Vals.push_back(VE.getValueID(I.getOperand(0))); // valist.
739 Vals.push_back(VE.getTypeID(I.getType())); // restype.
743 Stream.EmitRecord(Code, Vals, AbbrevToUse);
747 // Emit names for globals/functions etc.
748 static void WriteValueSymbolTable(const ValueSymbolTable &VST,
749 const ValueEnumerator &VE,
750 BitstreamWriter &Stream) {
751 if (VST.empty()) return;
752 Stream.EnterSubblock(bitc::VALUE_SYMTAB_BLOCK_ID, 4);
754 // FIXME: Set up the abbrev, we know how many values there are!
755 // FIXME: We know if the type names can use 7-bit ascii.
756 SmallVector<unsigned, 64> NameVals;
758 for (ValueSymbolTable::const_iterator SI = VST.begin(), SE = VST.end();
761 const ValueName &Name = *SI;
763 // Figure out the encoding to use for the name.
766 for (const char *C = Name.getKeyData(), *E = C+Name.getKeyLength();
769 isChar6 = BitCodeAbbrevOp::isChar6(*C);
770 if ((unsigned char)*C & 128) {
772 break; // don't bother scanning the rest.
776 unsigned AbbrevToUse = VST_ENTRY_8_ABBREV;
778 // VST_ENTRY: [valueid, namechar x N]
779 // VST_BBENTRY: [bbid, namechar x N]
781 if (isa<BasicBlock>(SI->getValue())) {
782 Code = bitc::VST_CODE_BBENTRY;
784 AbbrevToUse = VST_BBENTRY_6_ABBREV;
786 Code = bitc::VST_CODE_ENTRY;
788 AbbrevToUse = VST_ENTRY_6_ABBREV;
790 AbbrevToUse = VST_ENTRY_7_ABBREV;
793 NameVals.push_back(VE.getValueID(SI->getValue()));
794 for (const char *P = Name.getKeyData(),
795 *E = Name.getKeyData()+Name.getKeyLength(); P != E; ++P)
796 NameVals.push_back((unsigned char)*P);
798 // Emit the finished record.
799 Stream.EmitRecord(Code, NameVals, AbbrevToUse);
805 /// WriteFunction - Emit a function body to the module stream.
806 static void WriteFunction(const Function &F, ValueEnumerator &VE,
807 BitstreamWriter &Stream) {
808 Stream.EnterSubblock(bitc::FUNCTION_BLOCK_ID, 3);
809 VE.incorporateFunction(F);
811 SmallVector<unsigned, 64> Vals;
813 // Emit the number of basic blocks, so the reader can create them ahead of
815 Vals.push_back(VE.getBasicBlocks().size());
816 Stream.EmitRecord(bitc::FUNC_CODE_DECLAREBLOCKS, Vals);
819 // FIXME: Function attributes?
821 // If there are function-local constants, emit them now.
822 unsigned CstStart, CstEnd;
823 VE.getFunctionConstantRange(CstStart, CstEnd);
824 WriteConstants(CstStart, CstEnd, VE, Stream);
826 // Finally, emit all the instructions, in order.
827 for (Function::const_iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
828 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I != E; ++I)
829 WriteInstruction(*I, VE, Stream, Vals);
831 // Emit names for all the instructions etc.
832 WriteValueSymbolTable(F.getValueSymbolTable(), VE, Stream);
838 /// WriteTypeSymbolTable - Emit a block for the specified type symtab.
839 static void WriteTypeSymbolTable(const TypeSymbolTable &TST,
840 const ValueEnumerator &VE,
841 BitstreamWriter &Stream) {
842 if (TST.empty()) return;
844 Stream.EnterSubblock(bitc::TYPE_SYMTAB_BLOCK_ID, 3);
846 // 7-bit fixed width VST_CODE_ENTRY strings.
847 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
848 Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_ENTRY));
849 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
850 Log2_32_Ceil(VE.getTypes().size()+1)));
851 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
852 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7));
853 unsigned V7Abbrev = Stream.EmitAbbrev(Abbv);
855 SmallVector<unsigned, 64> NameVals;
857 for (TypeSymbolTable::const_iterator TI = TST.begin(), TE = TST.end();
859 // TST_ENTRY: [typeid, namechar x N]
860 NameVals.push_back(VE.getTypeID(TI->second));
862 const std::string &Str = TI->first;
864 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
865 NameVals.push_back((unsigned char)Str[i]);
870 // Emit the finished record.
871 Stream.EmitRecord(bitc::VST_CODE_ENTRY, NameVals, is7Bit ? V7Abbrev : 0);
879 /// WriteModule - Emit the specified module to the bitstream.
880 static void WriteModule(const Module *M, BitstreamWriter &Stream) {
881 Stream.EnterSubblock(bitc::MODULE_BLOCK_ID, 3);
883 // Emit the version number if it is non-zero.
885 SmallVector<unsigned, 1> Vals;
886 Vals.push_back(CurVersion);
887 Stream.EmitRecord(bitc::MODULE_CODE_VERSION, Vals);
890 // Analyze the module, enumerating globals, functions, etc.
891 ValueEnumerator VE(M);
893 // Emit information about parameter attributes.
894 WriteParamAttrTable(VE, Stream);
896 // Emit information describing all of the types in the module.
897 WriteTypeTable(VE, Stream);
899 // Emit top-level description of module, including target triple, inline asm,
900 // descriptors for global variables, and function prototype info.
901 WriteModuleInfo(M, VE, Stream);
904 WriteModuleConstants(VE, Stream);
906 // If we have any aggregate values in the value table, purge them - these can
907 // only be used to initialize global variables. Doing so makes the value
908 // namespace smaller for code in functions.
909 int NumNonAggregates = VE.PurgeAggregateValues();
910 if (NumNonAggregates != -1) {
911 SmallVector<unsigned, 1> Vals;
912 Vals.push_back(NumNonAggregates);
913 Stream.EmitRecord(bitc::MODULE_CODE_PURGEVALS, Vals);
916 // Emit function bodies.
917 for (Module::const_iterator I = M->begin(), E = M->end(); I != E; ++I)
918 if (!I->isDeclaration())
919 WriteFunction(*I, VE, Stream);
921 // Emit the type symbol table information.
922 WriteTypeSymbolTable(M->getTypeSymbolTable(), VE, Stream);
924 // Emit names for globals/functions etc.
925 WriteValueSymbolTable(M->getValueSymbolTable(), VE, Stream);
930 // Emit blockinfo, which defines the standard abbreviations etc.
931 static void WriteBlockInfo(BitstreamWriter &Stream) {
932 // We only want to emit block info records for blocks that have multiple
933 // instances: CONSTANTS_BLOCK, FUNCTION_BLOCK and VALUE_SYMTAB_BLOCK. Other
934 // blocks can defined their abbrevs inline.
935 Stream.EnterBlockInfoBlock(2);
937 { // 8-bit fixed-width VST_ENTRY/VST_BBENTRY strings.
938 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
939 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 3));
940 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
941 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
942 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
943 if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID,
944 Abbv) != VST_ENTRY_8_ABBREV)
945 assert(0 && "Unexpected abbrev ordering!");
948 { // 7-bit fixed width VST_ENTRY strings.
949 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
950 Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_ENTRY));
951 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
952 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
953 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7));
954 if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID,
955 Abbv) != VST_ENTRY_7_ABBREV)
956 assert(0 && "Unexpected abbrev ordering!");
958 { // 6-bit char6 VST_ENTRY strings.
959 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
960 Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_ENTRY));
961 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
962 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
963 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
964 if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID,
965 Abbv) != VST_ENTRY_6_ABBREV)
966 assert(0 && "Unexpected abbrev ordering!");
968 { // 6-bit char6 VST_BBENTRY strings.
969 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
970 Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_BBENTRY));
971 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
972 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
973 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
974 if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID,
975 Abbv) != VST_BBENTRY_6_ABBREV)
976 assert(0 && "Unexpected abbrev ordering!");
983 /// WriteBitcodeToFile - Write the specified module to the specified output
985 void llvm::WriteBitcodeToFile(const Module *M, std::ostream &Out) {
986 std::vector<unsigned char> Buffer;
987 BitstreamWriter Stream(Buffer);
989 Buffer.reserve(256*1024);
991 // Emit the file header.
992 Stream.Emit((unsigned)'B', 8);
993 Stream.Emit((unsigned)'C', 8);
999 // Emit blockinfo, which defines the standard abbreviations etc.
1000 WriteBlockInfo(Stream);
1003 WriteModule(M, Stream);
1005 // Write the generated bitstream to "Out".
1006 Out.write((char*)&Buffer.front(), Buffer.size());