blob: 68f0a0d163709ade4ca4e88c636c98d31ca427f9 [file] [log] [blame]
Chris Lattner1a9df8e2007-04-29 05:31:57 +00001//===--- Bitcode/Writer/BitcodeWriter.cpp - Bitcode Writer ----------------===//
Chris Lattnerfd57cec2007-04-22 06:24:45 +00002//
3// The LLVM Compiler Infrastructure
4//
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.
7//
8//===----------------------------------------------------------------------===//
9//
10// Bitcode writer implementation.
11//
12//===----------------------------------------------------------------------===//
13
14#include "llvm/Bitcode/ReaderWriter.h"
15#include "llvm/Bitcode/BitstreamWriter.h"
Chris Lattner47f96bf2007-04-23 01:01:37 +000016#include "llvm/Bitcode/LLVMBitCodes.h"
Chris Lattnerfd57cec2007-04-22 06:24:45 +000017#include "ValueEnumerator.h"
Chris Lattner2edd22b2007-04-24 00:16:04 +000018#include "llvm/Constants.h"
Chris Lattnerfd57cec2007-04-22 06:24:45 +000019#include "llvm/DerivedTypes.h"
Chris Lattnerb9d0c2a2007-04-26 05:53:54 +000020#include "llvm/Instructions.h"
Chris Lattnerfd57cec2007-04-22 06:24:45 +000021#include "llvm/Module.h"
22#include "llvm/TypeSymbolTable.h"
Chris Lattnerb992be12007-04-23 20:35:01 +000023#include "llvm/ValueSymbolTable.h"
Chris Lattnerfd57cec2007-04-22 06:24:45 +000024#include "llvm/Support/MathExtras.h"
25using namespace llvm;
26
27static const unsigned CurVersion = 0;
28
Chris Lattnerf581c3b2007-04-24 07:07:11 +000029static unsigned GetEncodedCastOpcode(unsigned Opcode) {
30 switch (Opcode) {
31 default: assert(0 && "Unknown cast instruction!");
32 case Instruction::Trunc : return bitc::CAST_TRUNC;
33 case Instruction::ZExt : return bitc::CAST_ZEXT;
34 case Instruction::SExt : return bitc::CAST_SEXT;
35 case Instruction::FPToUI : return bitc::CAST_FPTOUI;
36 case Instruction::FPToSI : return bitc::CAST_FPTOSI;
37 case Instruction::UIToFP : return bitc::CAST_UITOFP;
38 case Instruction::SIToFP : return bitc::CAST_SITOFP;
39 case Instruction::FPTrunc : return bitc::CAST_FPTRUNC;
40 case Instruction::FPExt : return bitc::CAST_FPEXT;
41 case Instruction::PtrToInt: return bitc::CAST_PTRTOINT;
42 case Instruction::IntToPtr: return bitc::CAST_INTTOPTR;
43 case Instruction::BitCast : return bitc::CAST_BITCAST;
44 }
45}
46
47static unsigned GetEncodedBinaryOpcode(unsigned Opcode) {
48 switch (Opcode) {
49 default: assert(0 && "Unknown binary instruction!");
50 case Instruction::Add: return bitc::BINOP_ADD;
51 case Instruction::Sub: return bitc::BINOP_SUB;
52 case Instruction::Mul: return bitc::BINOP_MUL;
53 case Instruction::UDiv: return bitc::BINOP_UDIV;
54 case Instruction::FDiv:
55 case Instruction::SDiv: return bitc::BINOP_SDIV;
56 case Instruction::URem: return bitc::BINOP_UREM;
57 case Instruction::FRem:
58 case Instruction::SRem: return bitc::BINOP_SREM;
59 case Instruction::Shl: return bitc::BINOP_SHL;
60 case Instruction::LShr: return bitc::BINOP_LSHR;
61 case Instruction::AShr: return bitc::BINOP_ASHR;
62 case Instruction::And: return bitc::BINOP_AND;
63 case Instruction::Or: return bitc::BINOP_OR;
64 case Instruction::Xor: return bitc::BINOP_XOR;
65 }
66}
67
68
69
Chris Lattnerfd57cec2007-04-22 06:24:45 +000070static void WriteStringRecord(unsigned Code, const std::string &Str,
71 unsigned AbbrevToUse, BitstreamWriter &Stream) {
72 SmallVector<unsigned, 64> Vals;
73
74 // Code: [strlen, strchar x N]
75 Vals.push_back(Str.size());
76 for (unsigned i = 0, e = Str.size(); i != e; ++i)
77 Vals.push_back(Str[i]);
78
79 // Emit the finished record.
80 Stream.EmitRecord(Code, Vals, AbbrevToUse);
81}
82
83
84/// WriteTypeTable - Write out the type table for a module.
85static void WriteTypeTable(const ValueEnumerator &VE, BitstreamWriter &Stream) {
86 const ValueEnumerator::TypeList &TypeList = VE.getTypes();
87
88 Stream.EnterSubblock(bitc::TYPE_BLOCK_ID, 4 /*count from # abbrevs */);
89 SmallVector<uint64_t, 64> TypeVals;
90
91 // FIXME: Set up abbrevs now that we know the width of the type fields, etc.
92
93 // Emit an entry count so the reader can reserve space.
94 TypeVals.push_back(TypeList.size());
95 Stream.EmitRecord(bitc::TYPE_CODE_NUMENTRY, TypeVals);
96 TypeVals.clear();
97
98 // Loop over all of the types, emitting each in turn.
99 for (unsigned i = 0, e = TypeList.size(); i != e; ++i) {
100 const Type *T = TypeList[i].first;
101 int AbbrevToUse = 0;
102 unsigned Code = 0;
103
104 switch (T->getTypeID()) {
105 case Type::PackedStructTyID: // FIXME: Delete Type::PackedStructTyID.
106 default: assert(0 && "Unknown type!");
107 case Type::VoidTyID: Code = bitc::TYPE_CODE_VOID; break;
108 case Type::FloatTyID: Code = bitc::TYPE_CODE_FLOAT; break;
109 case Type::DoubleTyID: Code = bitc::TYPE_CODE_DOUBLE; break;
110 case Type::LabelTyID: Code = bitc::TYPE_CODE_LABEL; break;
111 case Type::OpaqueTyID: Code = bitc::TYPE_CODE_OPAQUE; break;
112 case Type::IntegerTyID:
113 // INTEGER: [width]
114 Code = bitc::TYPE_CODE_INTEGER;
115 TypeVals.push_back(cast<IntegerType>(T)->getBitWidth());
116 break;
117 case Type::PointerTyID:
118 // POINTER: [pointee type]
119 Code = bitc::TYPE_CODE_POINTER;
120 TypeVals.push_back(VE.getTypeID(cast<PointerType>(T)->getElementType()));
121 break;
122
123 case Type::FunctionTyID: {
124 const FunctionType *FT = cast<FunctionType>(T);
125 // FUNCTION: [isvararg, #pararms, paramty x N]
126 Code = bitc::TYPE_CODE_FUNCTION;
127 TypeVals.push_back(FT->isVarArg());
128 TypeVals.push_back(VE.getTypeID(FT->getReturnType()));
129 // FIXME: PARAM ATTR ID!
130 TypeVals.push_back(FT->getNumParams());
131 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i)
132 TypeVals.push_back(VE.getTypeID(FT->getParamType(i)));
133 break;
134 }
135 case Type::StructTyID: {
136 const StructType *ST = cast<StructType>(T);
137 // STRUCT: [ispacked, #elts, eltty x N]
138 Code = bitc::TYPE_CODE_STRUCT;
139 TypeVals.push_back(ST->isPacked());
140 TypeVals.push_back(ST->getNumElements());
141 // Output all of the element types...
142 for (StructType::element_iterator I = ST->element_begin(),
143 E = ST->element_end(); I != E; ++I)
144 TypeVals.push_back(VE.getTypeID(*I));
145 break;
146 }
147 case Type::ArrayTyID: {
148 const ArrayType *AT = cast<ArrayType>(T);
149 // ARRAY: [numelts, eltty]
150 Code = bitc::TYPE_CODE_ARRAY;
151 TypeVals.push_back(AT->getNumElements());
152 TypeVals.push_back(VE.getTypeID(AT->getElementType()));
153 break;
154 }
155 case Type::VectorTyID: {
156 const VectorType *VT = cast<VectorType>(T);
157 // VECTOR [numelts, eltty]
158 Code = bitc::TYPE_CODE_VECTOR;
159 TypeVals.push_back(VT->getNumElements());
160 TypeVals.push_back(VE.getTypeID(VT->getElementType()));
161 break;
162 }
163 }
164
165 // Emit the finished record.
166 Stream.EmitRecord(Code, TypeVals, AbbrevToUse);
167 TypeVals.clear();
168 }
169
170 Stream.ExitBlock();
171}
172
Chris Lattnerfd57cec2007-04-22 06:24:45 +0000173static unsigned getEncodedLinkage(const GlobalValue *GV) {
174 switch (GV->getLinkage()) {
175 default: assert(0 && "Invalid linkage!");
176 case GlobalValue::ExternalLinkage: return 0;
177 case GlobalValue::WeakLinkage: return 1;
178 case GlobalValue::AppendingLinkage: return 2;
179 case GlobalValue::InternalLinkage: return 3;
180 case GlobalValue::LinkOnceLinkage: return 4;
181 case GlobalValue::DLLImportLinkage: return 5;
182 case GlobalValue::DLLExportLinkage: return 6;
183 case GlobalValue::ExternalWeakLinkage: return 7;
184 }
185}
186
187static unsigned getEncodedVisibility(const GlobalValue *GV) {
188 switch (GV->getVisibility()) {
189 default: assert(0 && "Invalid visibility!");
Anton Korobeynikov9cd3ccf2007-04-29 20:56:48 +0000190 case GlobalValue::DefaultVisibility: return 0;
191 case GlobalValue::HiddenVisibility: return 1;
192 case GlobalValue::ProtectedVisibility: return 2;
Chris Lattnerfd57cec2007-04-22 06:24:45 +0000193 }
194}
195
196// Emit top-level description of module, including target triple, inline asm,
197// descriptors for global variables, and function prototype info.
198static void WriteModuleInfo(const Module *M, const ValueEnumerator &VE,
199 BitstreamWriter &Stream) {
200 // Emit the list of dependent libraries for the Module.
201 for (Module::lib_iterator I = M->lib_begin(), E = M->lib_end(); I != E; ++I)
202 WriteStringRecord(bitc::MODULE_CODE_DEPLIB, *I, 0/*TODO*/, Stream);
203
204 // Emit various pieces of data attached to a module.
205 if (!M->getTargetTriple().empty())
206 WriteStringRecord(bitc::MODULE_CODE_TRIPLE, M->getTargetTriple(),
207 0/*TODO*/, Stream);
208 if (!M->getDataLayout().empty())
209 WriteStringRecord(bitc::MODULE_CODE_DATALAYOUT, M->getDataLayout(),
210 0/*TODO*/, Stream);
211 if (!M->getModuleInlineAsm().empty())
212 WriteStringRecord(bitc::MODULE_CODE_ASM, M->getModuleInlineAsm(),
213 0/*TODO*/, Stream);
214
Chris Lattner36d5e7d2007-04-23 16:04:05 +0000215 // Emit information about sections, computing how many there are. Also
216 // compute the maximum alignment value.
Chris Lattnerfd57cec2007-04-22 06:24:45 +0000217 std::map<std::string, unsigned> SectionMap;
Chris Lattner36d5e7d2007-04-23 16:04:05 +0000218 unsigned MaxAlignment = 0;
Chris Lattnerd127c1b2007-04-23 18:58:34 +0000219 unsigned MaxGlobalType = 0;
Chris Lattnerfd57cec2007-04-22 06:24:45 +0000220 for (Module::const_global_iterator GV = M->global_begin(),E = M->global_end();
221 GV != E; ++GV) {
Chris Lattner36d5e7d2007-04-23 16:04:05 +0000222 MaxAlignment = std::max(MaxAlignment, GV->getAlignment());
Chris Lattnerd127c1b2007-04-23 18:58:34 +0000223 MaxGlobalType = std::max(MaxGlobalType, VE.getTypeID(GV->getType()));
Chris Lattner36d5e7d2007-04-23 16:04:05 +0000224
Chris Lattnerfd57cec2007-04-22 06:24:45 +0000225 if (!GV->hasSection()) continue;
226 // Give section names unique ID's.
227 unsigned &Entry = SectionMap[GV->getSection()];
228 if (Entry != 0) continue;
229 WriteStringRecord(bitc::MODULE_CODE_SECTIONNAME, GV->getSection(),
230 0/*TODO*/, Stream);
231 Entry = SectionMap.size();
232 }
233 for (Module::const_iterator F = M->begin(), E = M->end(); F != E; ++F) {
Chris Lattner36d5e7d2007-04-23 16:04:05 +0000234 MaxAlignment = std::max(MaxAlignment, F->getAlignment());
Chris Lattnerfd57cec2007-04-22 06:24:45 +0000235 if (!F->hasSection()) continue;
236 // Give section names unique ID's.
237 unsigned &Entry = SectionMap[F->getSection()];
238 if (Entry != 0) continue;
239 WriteStringRecord(bitc::MODULE_CODE_SECTIONNAME, F->getSection(),
240 0/*TODO*/, Stream);
241 Entry = SectionMap.size();
242 }
243
Chris Lattner36d5e7d2007-04-23 16:04:05 +0000244 // Emit abbrev for globals, now that we know # sections and max alignment.
245 unsigned SimpleGVarAbbrev = 0;
Chris Lattnerd127c1b2007-04-23 18:58:34 +0000246 if (!M->global_empty()) {
Chris Lattner36d5e7d2007-04-23 16:04:05 +0000247 // Add an abbrev for common globals with no visibility or thread localness.
248 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
249 Abbv->Add(BitCodeAbbrevOp(bitc::MODULE_CODE_GLOBALVAR));
Chris Lattnerd127c1b2007-04-23 18:58:34 +0000250 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::FixedWidth,
251 Log2_32_Ceil(MaxGlobalType+1)));
Chris Lattner36d5e7d2007-04-23 16:04:05 +0000252 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::FixedWidth, 1)); // Constant.
253 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Initializer.
254 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::FixedWidth, 3)); // Linkage.
255 if (MaxAlignment == 0) // Alignment.
256 Abbv->Add(BitCodeAbbrevOp(0));
257 else {
258 unsigned MaxEncAlignment = Log2_32(MaxAlignment)+1;
259 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::FixedWidth,
Chris Lattnerd127c1b2007-04-23 18:58:34 +0000260 Log2_32_Ceil(MaxEncAlignment+1)));
Chris Lattner36d5e7d2007-04-23 16:04:05 +0000261 }
262 if (SectionMap.empty()) // Section.
263 Abbv->Add(BitCodeAbbrevOp(0));
264 else
265 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::FixedWidth,
Chris Lattner631a8ed2007-04-24 03:29:47 +0000266 Log2_32_Ceil(SectionMap.size()+1)));
Chris Lattner36d5e7d2007-04-23 16:04:05 +0000267 // Don't bother emitting vis + thread local.
268 SimpleGVarAbbrev = Stream.EmitAbbrev(Abbv);
269 }
Chris Lattnerfd57cec2007-04-22 06:24:45 +0000270
271 // Emit the global variable information.
272 SmallVector<unsigned, 64> Vals;
273 for (Module::const_global_iterator GV = M->global_begin(),E = M->global_end();
274 GV != E; ++GV) {
Chris Lattner36d5e7d2007-04-23 16:04:05 +0000275 unsigned AbbrevToUse = 0;
276
Chris Lattnerfd57cec2007-04-22 06:24:45 +0000277 // GLOBALVAR: [type, isconst, initid,
278 // linkage, alignment, section, visibility, threadlocal]
279 Vals.push_back(VE.getTypeID(GV->getType()));
280 Vals.push_back(GV->isConstant());
281 Vals.push_back(GV->isDeclaration() ? 0 :
282 (VE.getValueID(GV->getInitializer()) + 1));
283 Vals.push_back(getEncodedLinkage(GV));
284 Vals.push_back(Log2_32(GV->getAlignment())+1);
285 Vals.push_back(GV->hasSection() ? SectionMap[GV->getSection()] : 0);
Chris Lattner36d5e7d2007-04-23 16:04:05 +0000286 if (GV->isThreadLocal() ||
287 GV->getVisibility() != GlobalValue::DefaultVisibility) {
288 Vals.push_back(getEncodedVisibility(GV));
289 Vals.push_back(GV->isThreadLocal());
290 } else {
291 AbbrevToUse = SimpleGVarAbbrev;
292 }
Chris Lattnerfd57cec2007-04-22 06:24:45 +0000293
Chris Lattnerfd57cec2007-04-22 06:24:45 +0000294 Stream.EmitRecord(bitc::MODULE_CODE_GLOBALVAR, Vals, AbbrevToUse);
295 Vals.clear();
296 }
297
298 // Emit the function proto information.
299 for (Module::const_iterator F = M->begin(), E = M->end(); F != E; ++F) {
300 // FUNCTION: [type, callingconv, isproto, linkage, alignment, section,
301 // visibility]
302 Vals.push_back(VE.getTypeID(F->getType()));
303 Vals.push_back(F->getCallingConv());
304 Vals.push_back(F->isDeclaration());
305 Vals.push_back(getEncodedLinkage(F));
306 Vals.push_back(Log2_32(F->getAlignment())+1);
307 Vals.push_back(F->hasSection() ? SectionMap[F->getSection()] : 0);
308 Vals.push_back(getEncodedVisibility(F));
309
310 unsigned AbbrevToUse = 0;
311 Stream.EmitRecord(bitc::MODULE_CODE_FUNCTION, Vals, AbbrevToUse);
312 Vals.clear();
313 }
Chris Lattner07d98b42007-04-26 02:46:40 +0000314
315
316 // Emit the alias information.
317 for (Module::const_alias_iterator AI = M->alias_begin(), E = M->alias_end();
318 AI != E; ++AI) {
319 Vals.push_back(VE.getTypeID(AI->getType()));
320 Vals.push_back(VE.getValueID(AI->getAliasee()));
321 Vals.push_back(getEncodedLinkage(AI));
322 unsigned AbbrevToUse = 0;
323 Stream.EmitRecord(bitc::MODULE_CODE_ALIAS, Vals, AbbrevToUse);
324 Vals.clear();
325 }
Chris Lattnerfd57cec2007-04-22 06:24:45 +0000326}
327
328
Chris Lattner2edd22b2007-04-24 00:16:04 +0000329static void WriteConstants(unsigned FirstVal, unsigned LastVal,
330 const ValueEnumerator &VE,
331 BitstreamWriter &Stream) {
332 if (FirstVal == LastVal) return;
333
334 Stream.EnterSubblock(bitc::CONSTANTS_BLOCK_ID, 2);
Chris Lattnerb992be12007-04-23 20:35:01 +0000335
Chris Lattnerb9d0c2a2007-04-26 05:53:54 +0000336 // FIXME: Install and use abbrevs to reduce size. Install them globally so
337 // they don't need to be reemitted for each function body.
Chris Lattner2edd22b2007-04-24 00:16:04 +0000338
339 SmallVector<uint64_t, 64> Record;
340
341 const ValueEnumerator::ValueList &Vals = VE.getValues();
342 const Type *LastTy = 0;
343 for (unsigned i = FirstVal; i != LastVal; ++i) {
344 const Value *V = Vals[i].first;
345 // If we need to switch types, do so now.
346 if (V->getType() != LastTy) {
347 LastTy = V->getType();
348 Record.push_back(VE.getTypeID(LastTy));
349 Stream.EmitRecord(bitc::CST_CODE_SETTYPE, Record);
350 Record.clear();
351 }
352
353 if (const InlineAsm *IA = dyn_cast<InlineAsm>(V)) {
354 assert(0 && IA && "FIXME: Inline asm writing unimp!");
355 continue;
356 }
357 const Constant *C = cast<Constant>(V);
358 unsigned Code = -1U;
359 unsigned AbbrevToUse = 0;
360 if (C->isNullValue()) {
361 Code = bitc::CST_CODE_NULL;
362 } else if (isa<UndefValue>(C)) {
363 Code = bitc::CST_CODE_UNDEF;
364 } else if (const ConstantInt *IV = dyn_cast<ConstantInt>(C)) {
365 if (IV->getBitWidth() <= 64) {
366 int64_t V = IV->getSExtValue();
367 if (V >= 0)
368 Record.push_back(V << 1);
369 else
370 Record.push_back((-V << 1) | 1);
371 Code = bitc::CST_CODE_INTEGER;
372 } else { // Wide integers, > 64 bits in size.
373 // We have an arbitrary precision integer value to write whose
374 // bit width is > 64. However, in canonical unsigned integer
375 // format it is likely that the high bits are going to be zero.
376 // So, we only write the number of active words.
377 unsigned NWords = IV->getValue().getActiveWords();
378 const uint64_t *RawWords = IV->getValue().getRawData();
379 Record.push_back(NWords);
380 for (unsigned i = 0; i != NWords; ++i) {
381 int64_t V = RawWords[i];
382 if (V >= 0)
383 Record.push_back(V << 1);
384 else
385 Record.push_back((-V << 1) | 1);
386 }
387 Code = bitc::CST_CODE_WIDE_INTEGER;
388 }
389 } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
390 Code = bitc::CST_CODE_FLOAT;
391 if (CFP->getType() == Type::FloatTy) {
392 Record.push_back(FloatToBits((float)CFP->getValue()));
393 } else {
394 assert (CFP->getType() == Type::DoubleTy && "Unknown FP type!");
395 Record.push_back(DoubleToBits((double)CFP->getValue()));
396 }
397 } else if (isa<ConstantArray>(C) || isa<ConstantStruct>(V) ||
398 isa<ConstantVector>(V)) {
399 Code = bitc::CST_CODE_AGGREGATE;
400 Record.push_back(C->getNumOperands());
401 for (unsigned i = 0, e = C->getNumOperands(); i != e; ++i)
402 Record.push_back(VE.getValueID(C->getOperand(i)));
403 } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
Chris Lattnerf581c3b2007-04-24 07:07:11 +0000404 switch (CE->getOpcode()) {
405 default:
406 if (Instruction::isCast(CE->getOpcode())) {
407 Code = bitc::CST_CODE_CE_CAST;
408 Record.push_back(GetEncodedCastOpcode(CE->getOpcode()));
409 Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
410 Record.push_back(VE.getValueID(C->getOperand(0)));
411 } else {
412 assert(CE->getNumOperands() == 2 && "Unknown constant expr!");
413 Code = bitc::CST_CODE_CE_BINOP;
414 Record.push_back(GetEncodedBinaryOpcode(CE->getOpcode()));
415 Record.push_back(VE.getValueID(C->getOperand(0)));
416 Record.push_back(VE.getValueID(C->getOperand(1)));
417 }
418 break;
419 case Instruction::GetElementPtr:
420 Code = bitc::CST_CODE_CE_GEP;
421 Record.push_back(CE->getNumOperands());
422 for (unsigned i = 0, e = CE->getNumOperands(); i != e; ++i) {
423 Record.push_back(VE.getTypeID(C->getOperand(i)->getType()));
424 Record.push_back(VE.getValueID(C->getOperand(i)));
425 }
426 break;
427 case Instruction::Select:
428 Code = bitc::CST_CODE_CE_SELECT;
429 Record.push_back(VE.getValueID(C->getOperand(0)));
430 Record.push_back(VE.getValueID(C->getOperand(1)));
431 Record.push_back(VE.getValueID(C->getOperand(2)));
432 break;
433 case Instruction::ExtractElement:
434 Code = bitc::CST_CODE_CE_EXTRACTELT;
435 Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
436 Record.push_back(VE.getValueID(C->getOperand(0)));
437 Record.push_back(VE.getValueID(C->getOperand(1)));
438 break;
439 case Instruction::InsertElement:
440 Code = bitc::CST_CODE_CE_INSERTELT;
441 Record.push_back(VE.getValueID(C->getOperand(0)));
442 Record.push_back(VE.getValueID(C->getOperand(1)));
443 Record.push_back(VE.getValueID(C->getOperand(2)));
444 break;
445 case Instruction::ShuffleVector:
446 Code = bitc::CST_CODE_CE_SHUFFLEVEC;
447 Record.push_back(VE.getValueID(C->getOperand(0)));
448 Record.push_back(VE.getValueID(C->getOperand(1)));
449 Record.push_back(VE.getValueID(C->getOperand(2)));
450 break;
451 case Instruction::ICmp:
452 case Instruction::FCmp:
453 Code = bitc::CST_CODE_CE_CMP;
454 Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
455 Record.push_back(VE.getValueID(C->getOperand(0)));
456 Record.push_back(VE.getValueID(C->getOperand(1)));
457 Record.push_back(CE->getPredicate());
458 break;
459 }
Chris Lattner2edd22b2007-04-24 00:16:04 +0000460 } else {
461 assert(0 && "Unknown constant!");
462 }
463 Stream.EmitRecord(Code, Record, AbbrevToUse);
464 Record.clear();
465 }
466
467 Stream.ExitBlock();
468}
469
470static void WriteModuleConstants(const ValueEnumerator &VE,
471 BitstreamWriter &Stream) {
472 const ValueEnumerator::ValueList &Vals = VE.getValues();
473
474 // Find the first constant to emit, which is the first non-globalvalue value.
475 // We know globalvalues have been emitted by WriteModuleInfo.
476 for (unsigned i = 0, e = Vals.size(); i != e; ++i) {
477 if (!isa<GlobalValue>(Vals[i].first)) {
478 WriteConstants(i, Vals.size(), VE, Stream);
479 return;
480 }
481 }
482}
Chris Lattnerb992be12007-04-23 20:35:01 +0000483
Chris Lattnerb9d0c2a2007-04-26 05:53:54 +0000484/// WriteInstruction - Emit an instruction to the specified stream.
485static void WriteInstruction(const Instruction &I, ValueEnumerator &VE,
486 BitstreamWriter &Stream,
487 SmallVector<unsigned, 64> &Vals) {
Chris Lattnerb9d0c2a2007-04-26 05:53:54 +0000488 unsigned Code = 0;
489 unsigned AbbrevToUse = 0;
490 switch (I.getOpcode()) {
491 default:
492 if (Instruction::isCast(I.getOpcode())) {
Chris Lattnerd309c752007-05-01 02:13:26 +0000493 Code = bitc::FUNC_CODE_INST_CAST;
Chris Lattnerb9d0c2a2007-04-26 05:53:54 +0000494 Vals.push_back(GetEncodedCastOpcode(I.getOpcode()));
495 Vals.push_back(VE.getTypeID(I.getType()));
496 Vals.push_back(VE.getTypeID(I.getOperand(0)->getType()));
497 Vals.push_back(VE.getValueID(I.getOperand(0)));
498 } else {
499 assert(isa<BinaryOperator>(I) && "Unknown instruction!");
Chris Lattnerf6398752007-05-02 04:26:36 +0000500 Code = bitc::FUNC_CODE_INST_BINOP;
Chris Lattnerb9d0c2a2007-04-26 05:53:54 +0000501 Vals.push_back(GetEncodedBinaryOpcode(I.getOpcode()));
502 Vals.push_back(VE.getTypeID(I.getType()));
503 Vals.push_back(VE.getValueID(I.getOperand(0)));
504 Vals.push_back(VE.getValueID(I.getOperand(1)));
505 }
506 break;
Chris Lattnerd309c752007-05-01 02:13:26 +0000507
508 case Instruction::GetElementPtr:
509 Code = bitc::FUNC_CODE_INST_GEP;
Chris Lattnerd309c752007-05-01 02:13:26 +0000510 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
511 Vals.push_back(VE.getTypeID(I.getOperand(i)->getType()));
512 Vals.push_back(VE.getValueID(I.getOperand(i)));
513 }
514 break;
515 case Instruction::Select:
516 Code = bitc::FUNC_CODE_INST_SELECT;
517 Vals.push_back(VE.getTypeID(I.getType()));
518 Vals.push_back(VE.getValueID(I.getOperand(0)));
519 Vals.push_back(VE.getValueID(I.getOperand(1)));
520 Vals.push_back(VE.getValueID(I.getOperand(2)));
521 break;
522 case Instruction::ExtractElement:
523 Code = bitc::FUNC_CODE_INST_EXTRACTELT;
524 Vals.push_back(VE.getTypeID(I.getOperand(0)->getType()));
525 Vals.push_back(VE.getValueID(I.getOperand(0)));
526 Vals.push_back(VE.getValueID(I.getOperand(1)));
527 break;
528 case Instruction::InsertElement:
529 Code = bitc::FUNC_CODE_INST_INSERTELT;
530 Vals.push_back(VE.getTypeID(I.getType()));
531 Vals.push_back(VE.getValueID(I.getOperand(0)));
532 Vals.push_back(VE.getValueID(I.getOperand(1)));
533 Vals.push_back(VE.getValueID(I.getOperand(2)));
534 break;
535 case Instruction::ShuffleVector:
536 Code = bitc::FUNC_CODE_INST_SHUFFLEVEC;
537 Vals.push_back(VE.getTypeID(I.getType()));
538 Vals.push_back(VE.getValueID(I.getOperand(0)));
539 Vals.push_back(VE.getValueID(I.getOperand(1)));
540 Vals.push_back(VE.getValueID(I.getOperand(2)));
541 break;
542 case Instruction::ICmp:
543 case Instruction::FCmp:
544 Code = bitc::FUNC_CODE_INST_CMP;
545 Vals.push_back(VE.getTypeID(I.getOperand(0)->getType()));
546 Vals.push_back(VE.getValueID(I.getOperand(0)));
547 Vals.push_back(VE.getValueID(I.getOperand(1)));
548 Vals.push_back(cast<CmpInst>(I).getPredicate());
549 break;
550
551 case Instruction::Ret:
552 Code = bitc::FUNC_CODE_INST_RET;
553 if (I.getNumOperands()) {
554 Vals.push_back(VE.getTypeID(I.getOperand(0)->getType()));
555 Vals.push_back(VE.getValueID(I.getOperand(0)));
556 }
557 break;
558 case Instruction::Br:
559 Code = bitc::FUNC_CODE_INST_BR;
560 Vals.push_back(VE.getValueID(I.getOperand(0)));
561 if (cast<BranchInst>(I).isConditional()) {
562 Vals.push_back(VE.getValueID(I.getOperand(1)));
563 Vals.push_back(VE.getValueID(I.getOperand(2)));
564 }
565 break;
566 case Instruction::Switch:
567 Code = bitc::FUNC_CODE_INST_SWITCH;
568 Vals.push_back(VE.getTypeID(I.getOperand(0)->getType()));
Chris Lattnerd309c752007-05-01 02:13:26 +0000569 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
570 Vals.push_back(VE.getValueID(I.getOperand(i)));
571 break;
Chris Lattner60ce9b52007-05-01 07:03:37 +0000572 case Instruction::Invoke: {
Chris Lattnerd309c752007-05-01 02:13:26 +0000573 Code = bitc::FUNC_CODE_INST_INVOKE;
574 // FIXME: param attrs
575 Vals.push_back(VE.getTypeID(I.getOperand(0)->getType()));
576 Vals.push_back(VE.getValueID(I.getOperand(0))); // callee
577 Vals.push_back(VE.getValueID(I.getOperand(1))); // normal
578 Vals.push_back(VE.getValueID(I.getOperand(2))); // unwind
Chris Lattnerb9d0c2a2007-04-26 05:53:54 +0000579
Chris Lattnerd309c752007-05-01 02:13:26 +0000580 // Emit value #'s for the fixed parameters.
581 const PointerType *PTy = cast<PointerType>(I.getOperand(0)->getType());
582 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
583 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
584 Vals.push_back(VE.getValueID(I.getOperand(i+3))); // fixed param.
585
586 // Emit type/value pairs for varargs params.
587 if (FTy->isVarArg()) {
588 unsigned NumVarargs = I.getNumOperands()-3-FTy->getNumParams();
589 Vals.push_back(NumVarargs);
590 for (unsigned i = I.getNumOperands()-NumVarargs, e = I.getNumOperands();
591 i != e; ++i) {
592 Vals.push_back(VE.getTypeID(I.getOperand(i)->getType()));
593 Vals.push_back(VE.getValueID(I.getOperand(i)));
594 }
595 }
596 break;
Chris Lattner60ce9b52007-05-01 07:03:37 +0000597 }
Chris Lattnerb9d0c2a2007-04-26 05:53:54 +0000598 case Instruction::Unwind:
599 Code = bitc::FUNC_CODE_INST_UNWIND;
600 break;
601 case Instruction::Unreachable:
602 Code = bitc::FUNC_CODE_INST_UNREACHABLE;
603 break;
Chris Lattnerd309c752007-05-01 02:13:26 +0000604
605 case Instruction::PHI:
606 Code = bitc::FUNC_CODE_INST_PHI;
607 Vals.push_back(VE.getTypeID(I.getType()));
608 Vals.push_back(I.getNumOperands());
609 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
610 Vals.push_back(VE.getValueID(I.getOperand(i)));
611 break;
Chris Lattnerb9d0c2a2007-04-26 05:53:54 +0000612
Chris Lattnerd309c752007-05-01 02:13:26 +0000613 case Instruction::Malloc:
614 Code = bitc::FUNC_CODE_INST_MALLOC;
615 Vals.push_back(VE.getTypeID(I.getType()));
616 Vals.push_back(VE.getValueID(I.getOperand(0))); // size.
617 Vals.push_back(Log2_32(cast<MallocInst>(I).getAlignment())+1);
618 break;
619
620 case Instruction::Free:
621 Code = bitc::FUNC_CODE_INST_FREE;
622 Vals.push_back(VE.getTypeID(I.getOperand(0)->getType()));
623 Vals.push_back(VE.getValueID(I.getOperand(0)));
624 break;
625
626 case Instruction::Alloca:
627 Code = bitc::FUNC_CODE_INST_ALLOCA;
628 Vals.push_back(VE.getTypeID(I.getType()));
629 Vals.push_back(VE.getValueID(I.getOperand(0))); // size.
630 Vals.push_back(Log2_32(cast<AllocaInst>(I).getAlignment())+1);
631 break;
632
633 case Instruction::Load:
634 Code = bitc::FUNC_CODE_INST_LOAD;
635 Vals.push_back(VE.getTypeID(I.getOperand(0)->getType()));
636 Vals.push_back(VE.getValueID(I.getOperand(0))); // ptr.
637 Vals.push_back(Log2_32(cast<LoadInst>(I).getAlignment())+1);
638 Vals.push_back(cast<LoadInst>(I).isVolatile());
639 break;
640 case Instruction::Store:
641 Code = bitc::FUNC_CODE_INST_STORE;
642 Vals.push_back(VE.getTypeID(I.getOperand(1)->getType())); // Pointer
643 Vals.push_back(VE.getValueID(I.getOperand(0))); // val.
644 Vals.push_back(VE.getValueID(I.getOperand(1))); // ptr.
645 Vals.push_back(Log2_32(cast<StoreInst>(I).getAlignment())+1);
646 Vals.push_back(cast<StoreInst>(I).isVolatile());
647 break;
648 case Instruction::Call: {
649 Code = bitc::FUNC_CODE_INST_CALL;
650 // FIXME: param attrs
651 Vals.push_back(VE.getTypeID(I.getOperand(0)->getType()));
652 Vals.push_back(VE.getValueID(I.getOperand(0))); // callee
653
654 // Emit value #'s for the fixed parameters.
655 const PointerType *PTy = cast<PointerType>(I.getOperand(0)->getType());
656 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
657 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
658 Vals.push_back(VE.getValueID(I.getOperand(i+1))); // fixed param.
659
Chris Lattner60ce9b52007-05-01 07:03:37 +0000660 // Emit type/value pairs for varargs params.
661 if (FTy->isVarArg()) {
662 unsigned NumVarargs = I.getNumOperands()-1-FTy->getNumParams();
663 Vals.push_back(NumVarargs);
664 for (unsigned i = I.getNumOperands()-NumVarargs, e = I.getNumOperands();
665 i != e; ++i) {
666 Vals.push_back(VE.getTypeID(I.getOperand(i)->getType()));
667 Vals.push_back(VE.getValueID(I.getOperand(i)));
Chris Lattnerd309c752007-05-01 02:13:26 +0000668 }
669 }
670 break;
Chris Lattner60ce9b52007-05-01 07:03:37 +0000671 }
Chris Lattnerd309c752007-05-01 02:13:26 +0000672 case Instruction::VAArg:
673 Code = bitc::FUNC_CODE_INST_VAARG;
674 Vals.push_back(VE.getTypeID(I.getOperand(0)->getType())); // valistty
675 Vals.push_back(VE.getValueID(I.getOperand(0))); // valist.
676 Vals.push_back(VE.getTypeID(I.getType())); // restype.
677 break;
Chris Lattnerb9d0c2a2007-04-26 05:53:54 +0000678 }
679
680 Stream.EmitRecord(Code, Vals, AbbrevToUse);
681 Vals.clear();
682}
683
Chris Lattnerbe1f9932007-05-01 02:14:57 +0000684// Emit names for globals/functions etc.
685static void WriteValueSymbolTable(const ValueSymbolTable &VST,
686 const ValueEnumerator &VE,
687 BitstreamWriter &Stream) {
688 if (VST.empty()) return;
689 Stream.EnterSubblock(bitc::VALUE_SYMTAB_BLOCK_ID, 3);
690
691 // FIXME: Set up the abbrev, we know how many values there are!
692 // FIXME: We know if the type names can use 7-bit ascii.
693 SmallVector<unsigned, 64> NameVals;
694
695 for (ValueSymbolTable::const_iterator SI = VST.begin(), SE = VST.end();
696 SI != SE; ++SI) {
697 unsigned AbbrevToUse = 0;
698
Chris Lattnere825ed52007-05-03 22:18:21 +0000699 // VST_ENTRY: [valueid, namelen, namechar x N]
700 // VST_BBENTRY: [bbid, namelen, namechar x N]
701 unsigned Code;
702 if (isa<BasicBlock>(SI->getValue())) {
703 Code = bitc::VST_CODE_BBENTRY;
704 } else {
705 Code = bitc::VST_CODE_ENTRY;
706 }
Chris Lattnerbe1f9932007-05-01 02:14:57 +0000707
Chris Lattnere825ed52007-05-03 22:18:21 +0000708 NameVals.push_back(VE.getValueID(SI->getValue()));
Chris Lattnerbe1f9932007-05-01 02:14:57 +0000709 NameVals.push_back(SI->getKeyLength());
710 for (const char *P = SI->getKeyData(),
711 *E = SI->getKeyData()+SI->getKeyLength(); P != E; ++P)
712 NameVals.push_back((unsigned char)*P);
713
714 // Emit the finished record.
Chris Lattnere825ed52007-05-03 22:18:21 +0000715 Stream.EmitRecord(Code, NameVals, AbbrevToUse);
Chris Lattnerbe1f9932007-05-01 02:14:57 +0000716 NameVals.clear();
717 }
718 Stream.ExitBlock();
719}
720
Chris Lattner8d35c792007-04-26 03:50:57 +0000721/// WriteFunction - Emit a function body to the module stream.
Chris Lattner198f34a2007-04-26 03:27:58 +0000722static void WriteFunction(const Function &F, ValueEnumerator &VE,
723 BitstreamWriter &Stream) {
Chris Lattner01b27452007-04-29 05:49:09 +0000724 Stream.EnterSubblock(bitc::FUNCTION_BLOCK_ID, 3);
Chris Lattner8d35c792007-04-26 03:50:57 +0000725 VE.incorporateFunction(F);
Chris Lattnerb9d0c2a2007-04-26 05:53:54 +0000726
727 SmallVector<unsigned, 64> Vals;
728
729 // Emit the number of basic blocks, so the reader can create them ahead of
730 // time.
731 Vals.push_back(VE.getBasicBlocks().size());
732 Stream.EmitRecord(bitc::FUNC_CODE_DECLAREBLOCKS, Vals);
733 Vals.clear();
734
735 // FIXME: Function attributes?
736
737 // If there are function-local constants, emit them now.
738 unsigned CstStart, CstEnd;
739 VE.getFunctionConstantRange(CstStart, CstEnd);
740 WriteConstants(CstStart, CstEnd, VE, Stream);
741
742 // Finally, emit all the instructions, in order.
743 for (Function::const_iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
744 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I != E; ++I)
745 WriteInstruction(*I, VE, Stream, Vals);
Chris Lattner198f34a2007-04-26 03:27:58 +0000746
Chris Lattnerbe1f9932007-05-01 02:14:57 +0000747 // Emit names for all the instructions etc.
748 WriteValueSymbolTable(F.getValueSymbolTable(), VE, Stream);
749
Chris Lattner8d35c792007-04-26 03:50:57 +0000750 VE.purgeFunction();
Chris Lattnerb9d0c2a2007-04-26 05:53:54 +0000751 Stream.ExitBlock();
Chris Lattner198f34a2007-04-26 03:27:58 +0000752}
753
754/// WriteTypeSymbolTable - Emit a block for the specified type symtab.
755static void WriteTypeSymbolTable(const TypeSymbolTable &TST,
756 const ValueEnumerator &VE,
757 BitstreamWriter &Stream) {
758 if (TST.empty()) return;
759
760 Stream.EnterSubblock(bitc::TYPE_SYMTAB_BLOCK_ID, 3);
761
762 // FIXME: Set up the abbrev, we know how many types there are!
763 // FIXME: We know if the type names can use 7-bit ascii.
764
765 SmallVector<unsigned, 64> NameVals;
766
767 for (TypeSymbolTable::const_iterator TI = TST.begin(), TE = TST.end();
768 TI != TE; ++TI) {
769 unsigned AbbrevToUse = 0;
770
771 // TST_ENTRY: [typeid, namelen, namechar x N]
772 NameVals.push_back(VE.getTypeID(TI->second));
773
774 const std::string &Str = TI->first;
775 NameVals.push_back(Str.size());
776 for (unsigned i = 0, e = Str.size(); i != e; ++i)
777 NameVals.push_back(Str[i]);
778
779 // Emit the finished record.
780 Stream.EmitRecord(bitc::VST_CODE_ENTRY, NameVals, AbbrevToUse);
781 NameVals.clear();
782 }
783
784 Stream.ExitBlock();
785}
786
Chris Lattner198f34a2007-04-26 03:27:58 +0000787
Chris Lattnerfd57cec2007-04-22 06:24:45 +0000788/// WriteModule - Emit the specified module to the bitstream.
789static void WriteModule(const Module *M, BitstreamWriter &Stream) {
Chris Lattnerd127c1b2007-04-23 18:58:34 +0000790 Stream.EnterSubblock(bitc::MODULE_BLOCK_ID, 3);
Chris Lattnerfd57cec2007-04-22 06:24:45 +0000791
792 // Emit the version number if it is non-zero.
793 if (CurVersion) {
Chris Lattner198f34a2007-04-26 03:27:58 +0000794 SmallVector<unsigned, 1> Vals;
795 Vals.push_back(CurVersion);
796 Stream.EmitRecord(bitc::MODULE_CODE_VERSION, Vals);
Chris Lattnerfd57cec2007-04-22 06:24:45 +0000797 }
798
799 // Analyze the module, enumerating globals, functions, etc.
800 ValueEnumerator VE(M);
801
802 // Emit information describing all of the types in the module.
803 WriteTypeTable(VE, Stream);
804
Chris Lattnerfd57cec2007-04-22 06:24:45 +0000805 // Emit top-level description of module, including target triple, inline asm,
806 // descriptors for global variables, and function prototype info.
807 WriteModuleInfo(M, VE, Stream);
808
Chris Lattner2edd22b2007-04-24 00:16:04 +0000809 // Emit constants.
810 WriteModuleConstants(VE, Stream);
811
Chris Lattner51d5f292007-04-26 03:32:43 +0000812 // If we have any aggregate values in the value table, purge them - these can
813 // only be used to initialize global variables. Doing so makes the value
814 // namespace smaller for code in functions.
Chris Lattner198f34a2007-04-26 03:27:58 +0000815 int NumNonAggregates = VE.PurgeAggregateValues();
816 if (NumNonAggregates != -1) {
817 SmallVector<unsigned, 1> Vals;
818 Vals.push_back(NumNonAggregates);
819 Stream.EmitRecord(bitc::MODULE_CODE_PURGEVALS, Vals);
820 }
821
822 // Emit function bodies.
823 for (Module::const_iterator I = M->begin(), E = M->end(); I != E; ++I)
Chris Lattner51d5f292007-04-26 03:32:43 +0000824 if (!I->isDeclaration())
825 WriteFunction(*I, VE, Stream);
Chris Lattner198f34a2007-04-26 03:27:58 +0000826
Chris Lattnerfd57cec2007-04-22 06:24:45 +0000827 // Emit the type symbol table information.
828 WriteTypeSymbolTable(M->getTypeSymbolTable(), VE, Stream);
Chris Lattnerb992be12007-04-23 20:35:01 +0000829
830 // Emit names for globals/functions etc.
831 WriteValueSymbolTable(M->getValueSymbolTable(), VE, Stream);
832
Chris Lattnerfd57cec2007-04-22 06:24:45 +0000833 Stream.ExitBlock();
834}
835
836/// WriteBitcodeToFile - Write the specified module to the specified output
837/// stream.
838void llvm::WriteBitcodeToFile(const Module *M, std::ostream &Out) {
839 std::vector<unsigned char> Buffer;
840 BitstreamWriter Stream(Buffer);
841
842 Buffer.reserve(256*1024);
843
844 // Emit the file header.
845 Stream.Emit((unsigned)'B', 8);
846 Stream.Emit((unsigned)'C', 8);
847 Stream.Emit(0x0, 4);
848 Stream.Emit(0xC, 4);
849 Stream.Emit(0xE, 4);
850 Stream.Emit(0xD, 4);
851
852 // Emit the module.
853 WriteModule(M, Stream);
854
855 // Write the generated bitstream to "Out".
856 Out.write((char*)&Buffer.front(), Buffer.size());
857}