blob: 9249c70209fa2a922c26b484257954eac4df3153 [file] [log] [blame]
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001//===--- Bitcode/Writer/BitcodeWriter.cpp - Bitcode Writer ----------------===//
2//
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"
16#include "llvm/Bitcode/LLVMBitCodes.h"
17#include "ValueEnumerator.h"
18#include "llvm/Constants.h"
19#include "llvm/DerivedTypes.h"
20#include "llvm/InlineAsm.h"
21#include "llvm/Instructions.h"
22#include "llvm/Module.h"
23#include "llvm/ParameterAttributes.h"
24#include "llvm/TypeSymbolTable.h"
25#include "llvm/ValueSymbolTable.h"
26#include "llvm/Support/MathExtras.h"
27using namespace llvm;
28
29/// These are manifest constants used by the bitcode writer. They do not need to
30/// be kept in sync with the reader, but need to be consistent within this file.
31enum {
32 CurVersion = 0,
33
34 // VALUE_SYMTAB_BLOCK abbrev id's.
35 VST_ENTRY_8_ABBREV = bitc::FIRST_APPLICATION_ABBREV,
36 VST_ENTRY_7_ABBREV,
37 VST_ENTRY_6_ABBREV,
38 VST_BBENTRY_6_ABBREV,
39
40 // CONSTANTS_BLOCK abbrev id's.
41 CONSTANTS_SETTYPE_ABBREV = bitc::FIRST_APPLICATION_ABBREV,
42 CONSTANTS_INTEGER_ABBREV,
43 CONSTANTS_CE_CAST_Abbrev,
44 CONSTANTS_NULL_Abbrev,
45
46 // FUNCTION_BLOCK abbrev id's.
47 FUNCTION_INST_LOAD_ABBREV = bitc::FIRST_APPLICATION_ABBREV,
48 FUNCTION_INST_BINOP_ABBREV,
49 FUNCTION_INST_CAST_ABBREV,
50 FUNCTION_INST_RET_VOID_ABBREV,
51 FUNCTION_INST_RET_VAL_ABBREV,
52 FUNCTION_INST_UNREACHABLE_ABBREV
53};
54
55
56static unsigned GetEncodedCastOpcode(unsigned Opcode) {
57 switch (Opcode) {
58 default: assert(0 && "Unknown cast instruction!");
59 case Instruction::Trunc : return bitc::CAST_TRUNC;
60 case Instruction::ZExt : return bitc::CAST_ZEXT;
61 case Instruction::SExt : return bitc::CAST_SEXT;
62 case Instruction::FPToUI : return bitc::CAST_FPTOUI;
63 case Instruction::FPToSI : return bitc::CAST_FPTOSI;
64 case Instruction::UIToFP : return bitc::CAST_UITOFP;
65 case Instruction::SIToFP : return bitc::CAST_SITOFP;
66 case Instruction::FPTrunc : return bitc::CAST_FPTRUNC;
67 case Instruction::FPExt : return bitc::CAST_FPEXT;
68 case Instruction::PtrToInt: return bitc::CAST_PTRTOINT;
69 case Instruction::IntToPtr: return bitc::CAST_INTTOPTR;
70 case Instruction::BitCast : return bitc::CAST_BITCAST;
71 }
72}
73
74static unsigned GetEncodedBinaryOpcode(unsigned Opcode) {
75 switch (Opcode) {
76 default: assert(0 && "Unknown binary instruction!");
77 case Instruction::Add: return bitc::BINOP_ADD;
78 case Instruction::Sub: return bitc::BINOP_SUB;
79 case Instruction::Mul: return bitc::BINOP_MUL;
80 case Instruction::UDiv: return bitc::BINOP_UDIV;
81 case Instruction::FDiv:
82 case Instruction::SDiv: return bitc::BINOP_SDIV;
83 case Instruction::URem: return bitc::BINOP_UREM;
84 case Instruction::FRem:
85 case Instruction::SRem: return bitc::BINOP_SREM;
86 case Instruction::Shl: return bitc::BINOP_SHL;
87 case Instruction::LShr: return bitc::BINOP_LSHR;
88 case Instruction::AShr: return bitc::BINOP_ASHR;
89 case Instruction::And: return bitc::BINOP_AND;
90 case Instruction::Or: return bitc::BINOP_OR;
91 case Instruction::Xor: return bitc::BINOP_XOR;
92 }
93}
94
95
96
97static void WriteStringRecord(unsigned Code, const std::string &Str,
98 unsigned AbbrevToUse, BitstreamWriter &Stream) {
99 SmallVector<unsigned, 64> Vals;
100
101 // Code: [strchar x N]
102 for (unsigned i = 0, e = Str.size(); i != e; ++i)
103 Vals.push_back(Str[i]);
104
105 // Emit the finished record.
106 Stream.EmitRecord(Code, Vals, AbbrevToUse);
107}
108
109// Emit information about parameter attributes.
110static void WriteParamAttrTable(const ValueEnumerator &VE,
111 BitstreamWriter &Stream) {
112 const std::vector<const ParamAttrsList*> &Attrs = VE.getParamAttrs();
113 if (Attrs.empty()) return;
114
115 Stream.EnterSubblock(bitc::PARAMATTR_BLOCK_ID, 3);
116
117 SmallVector<uint64_t, 64> Record;
118 for (unsigned i = 0, e = Attrs.size(); i != e; ++i) {
119 const ParamAttrsList *A = Attrs[i];
120 for (unsigned op = 0, e = A->size(); op != e; ++op) {
121 Record.push_back(A->getParamIndex(op));
122 Record.push_back(A->getParamAttrsAtIndex(op));
123 }
124
125 Stream.EmitRecord(bitc::PARAMATTR_CODE_ENTRY, Record);
126 Record.clear();
127 }
128
129 Stream.ExitBlock();
130}
131
132/// WriteTypeTable - Write out the type table for a module.
133static void WriteTypeTable(const ValueEnumerator &VE, BitstreamWriter &Stream) {
134 const ValueEnumerator::TypeList &TypeList = VE.getTypes();
135
136 Stream.EnterSubblock(bitc::TYPE_BLOCK_ID, 4 /*count from # abbrevs */);
137 SmallVector<uint64_t, 64> TypeVals;
138
139 // Abbrev for TYPE_CODE_POINTER.
140 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
141 Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_POINTER));
142 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
143 Log2_32_Ceil(VE.getTypes().size()+1)));
144 unsigned PtrAbbrev = Stream.EmitAbbrev(Abbv);
145
146 // Abbrev for TYPE_CODE_FUNCTION.
147 Abbv = new BitCodeAbbrev();
148 Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_FUNCTION));
149 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // isvararg
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000150 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
151 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
152 Log2_32_Ceil(VE.getTypes().size()+1)));
153 unsigned FunctionAbbrev = Stream.EmitAbbrev(Abbv);
154
155 // Abbrev for TYPE_CODE_STRUCT.
156 Abbv = new BitCodeAbbrev();
157 Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_STRUCT));
158 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // ispacked
159 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
160 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
161 Log2_32_Ceil(VE.getTypes().size()+1)));
162 unsigned StructAbbrev = Stream.EmitAbbrev(Abbv);
163
164 // Abbrev for TYPE_CODE_ARRAY.
165 Abbv = new BitCodeAbbrev();
166 Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_ARRAY));
167 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // size
168 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
169 Log2_32_Ceil(VE.getTypes().size()+1)));
170 unsigned ArrayAbbrev = Stream.EmitAbbrev(Abbv);
171
172 // Emit an entry count so the reader can reserve space.
173 TypeVals.push_back(TypeList.size());
174 Stream.EmitRecord(bitc::TYPE_CODE_NUMENTRY, TypeVals);
175 TypeVals.clear();
176
177 // Loop over all of the types, emitting each in turn.
178 for (unsigned i = 0, e = TypeList.size(); i != e; ++i) {
179 const Type *T = TypeList[i].first;
180 int AbbrevToUse = 0;
181 unsigned Code = 0;
182
183 switch (T->getTypeID()) {
184 default: assert(0 && "Unknown type!");
185 case Type::VoidTyID: Code = bitc::TYPE_CODE_VOID; break;
186 case Type::FloatTyID: Code = bitc::TYPE_CODE_FLOAT; break;
187 case Type::DoubleTyID: Code = bitc::TYPE_CODE_DOUBLE; break;
Dale Johannesenf325d9f2007-08-03 01:03:46 +0000188 case Type::X86_FP80TyID: Code = bitc::TYPE_CODE_X86_FP80; break;
189 case Type::FP128TyID: Code = bitc::TYPE_CODE_FP128; break;
190 case Type::PPC_FP128TyID: Code = bitc::TYPE_CODE_PPC_FP128; break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000191 case Type::LabelTyID: Code = bitc::TYPE_CODE_LABEL; break;
192 case Type::OpaqueTyID: Code = bitc::TYPE_CODE_OPAQUE; break;
193 case Type::IntegerTyID:
194 // INTEGER: [width]
195 Code = bitc::TYPE_CODE_INTEGER;
196 TypeVals.push_back(cast<IntegerType>(T)->getBitWidth());
197 break;
198 case Type::PointerTyID:
199 // POINTER: [pointee type]
200 Code = bitc::TYPE_CODE_POINTER;
201 TypeVals.push_back(VE.getTypeID(cast<PointerType>(T)->getElementType()));
202 AbbrevToUse = PtrAbbrev;
203 break;
204
205 case Type::FunctionTyID: {
206 const FunctionType *FT = cast<FunctionType>(T);
Duncan Sandsf5588dc2007-11-27 13:23:08 +0000207 // FUNCTION: [isvararg, retty, paramty x N]
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000208 Code = bitc::TYPE_CODE_FUNCTION;
209 TypeVals.push_back(FT->isVarArg());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000210 TypeVals.push_back(VE.getTypeID(FT->getReturnType()));
211 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i)
212 TypeVals.push_back(VE.getTypeID(FT->getParamType(i)));
213 AbbrevToUse = FunctionAbbrev;
214 break;
215 }
216 case Type::StructTyID: {
217 const StructType *ST = cast<StructType>(T);
218 // STRUCT: [ispacked, eltty x N]
219 Code = bitc::TYPE_CODE_STRUCT;
220 TypeVals.push_back(ST->isPacked());
221 // Output all of the element types.
222 for (StructType::element_iterator I = ST->element_begin(),
223 E = ST->element_end(); I != E; ++I)
224 TypeVals.push_back(VE.getTypeID(*I));
225 AbbrevToUse = StructAbbrev;
226 break;
227 }
228 case Type::ArrayTyID: {
229 const ArrayType *AT = cast<ArrayType>(T);
230 // ARRAY: [numelts, eltty]
231 Code = bitc::TYPE_CODE_ARRAY;
232 TypeVals.push_back(AT->getNumElements());
233 TypeVals.push_back(VE.getTypeID(AT->getElementType()));
234 AbbrevToUse = ArrayAbbrev;
235 break;
236 }
237 case Type::VectorTyID: {
238 const VectorType *VT = cast<VectorType>(T);
239 // VECTOR [numelts, eltty]
240 Code = bitc::TYPE_CODE_VECTOR;
241 TypeVals.push_back(VT->getNumElements());
242 TypeVals.push_back(VE.getTypeID(VT->getElementType()));
243 break;
244 }
245 }
246
247 // Emit the finished record.
248 Stream.EmitRecord(Code, TypeVals, AbbrevToUse);
249 TypeVals.clear();
250 }
251
252 Stream.ExitBlock();
253}
254
255static unsigned getEncodedLinkage(const GlobalValue *GV) {
256 switch (GV->getLinkage()) {
257 default: assert(0 && "Invalid linkage!");
258 case GlobalValue::GhostLinkage: // Map ghost linkage onto external.
259 case GlobalValue::ExternalLinkage: return 0;
260 case GlobalValue::WeakLinkage: return 1;
261 case GlobalValue::AppendingLinkage: return 2;
262 case GlobalValue::InternalLinkage: return 3;
263 case GlobalValue::LinkOnceLinkage: return 4;
264 case GlobalValue::DLLImportLinkage: return 5;
265 case GlobalValue::DLLExportLinkage: return 6;
266 case GlobalValue::ExternalWeakLinkage: return 7;
267 }
268}
269
270static unsigned getEncodedVisibility(const GlobalValue *GV) {
271 switch (GV->getVisibility()) {
272 default: assert(0 && "Invalid visibility!");
273 case GlobalValue::DefaultVisibility: return 0;
274 case GlobalValue::HiddenVisibility: return 1;
275 case GlobalValue::ProtectedVisibility: return 2;
276 }
277}
278
279// Emit top-level description of module, including target triple, inline asm,
280// descriptors for global variables, and function prototype info.
281static void WriteModuleInfo(const Module *M, const ValueEnumerator &VE,
282 BitstreamWriter &Stream) {
283 // Emit the list of dependent libraries for the Module.
284 for (Module::lib_iterator I = M->lib_begin(), E = M->lib_end(); I != E; ++I)
285 WriteStringRecord(bitc::MODULE_CODE_DEPLIB, *I, 0/*TODO*/, Stream);
286
287 // Emit various pieces of data attached to a module.
288 if (!M->getTargetTriple().empty())
289 WriteStringRecord(bitc::MODULE_CODE_TRIPLE, M->getTargetTriple(),
290 0/*TODO*/, Stream);
291 if (!M->getDataLayout().empty())
292 WriteStringRecord(bitc::MODULE_CODE_DATALAYOUT, M->getDataLayout(),
293 0/*TODO*/, Stream);
294 if (!M->getModuleInlineAsm().empty())
295 WriteStringRecord(bitc::MODULE_CODE_ASM, M->getModuleInlineAsm(),
296 0/*TODO*/, Stream);
297
298 // Emit information about sections, computing how many there are. Also
299 // compute the maximum alignment value.
300 std::map<std::string, unsigned> SectionMap;
301 unsigned MaxAlignment = 0;
302 unsigned MaxGlobalType = 0;
303 for (Module::const_global_iterator GV = M->global_begin(),E = M->global_end();
304 GV != E; ++GV) {
305 MaxAlignment = std::max(MaxAlignment, GV->getAlignment());
306 MaxGlobalType = std::max(MaxGlobalType, VE.getTypeID(GV->getType()));
307
308 if (!GV->hasSection()) continue;
309 // Give section names unique ID's.
310 unsigned &Entry = SectionMap[GV->getSection()];
311 if (Entry != 0) continue;
312 WriteStringRecord(bitc::MODULE_CODE_SECTIONNAME, GV->getSection(),
313 0/*TODO*/, Stream);
314 Entry = SectionMap.size();
315 }
316 for (Module::const_iterator F = M->begin(), E = M->end(); F != E; ++F) {
317 MaxAlignment = std::max(MaxAlignment, F->getAlignment());
318 if (!F->hasSection()) continue;
319 // Give section names unique ID's.
320 unsigned &Entry = SectionMap[F->getSection()];
321 if (Entry != 0) continue;
322 WriteStringRecord(bitc::MODULE_CODE_SECTIONNAME, F->getSection(),
323 0/*TODO*/, Stream);
324 Entry = SectionMap.size();
325 }
326
327 // Emit abbrev for globals, now that we know # sections and max alignment.
328 unsigned SimpleGVarAbbrev = 0;
329 if (!M->global_empty()) {
330 // Add an abbrev for common globals with no visibility or thread localness.
331 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
332 Abbv->Add(BitCodeAbbrevOp(bitc::MODULE_CODE_GLOBALVAR));
333 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
334 Log2_32_Ceil(MaxGlobalType+1)));
335 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Constant.
336 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Initializer.
337 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 3)); // Linkage.
338 if (MaxAlignment == 0) // Alignment.
339 Abbv->Add(BitCodeAbbrevOp(0));
340 else {
341 unsigned MaxEncAlignment = Log2_32(MaxAlignment)+1;
342 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
343 Log2_32_Ceil(MaxEncAlignment+1)));
344 }
345 if (SectionMap.empty()) // Section.
346 Abbv->Add(BitCodeAbbrevOp(0));
347 else
348 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
349 Log2_32_Ceil(SectionMap.size()+1)));
350 // Don't bother emitting vis + thread local.
351 SimpleGVarAbbrev = Stream.EmitAbbrev(Abbv);
352 }
353
354 // Emit the global variable information.
355 SmallVector<unsigned, 64> Vals;
356 for (Module::const_global_iterator GV = M->global_begin(),E = M->global_end();
357 GV != E; ++GV) {
358 unsigned AbbrevToUse = 0;
359
360 // GLOBALVAR: [type, isconst, initid,
361 // linkage, alignment, section, visibility, threadlocal]
362 Vals.push_back(VE.getTypeID(GV->getType()));
363 Vals.push_back(GV->isConstant());
364 Vals.push_back(GV->isDeclaration() ? 0 :
365 (VE.getValueID(GV->getInitializer()) + 1));
366 Vals.push_back(getEncodedLinkage(GV));
367 Vals.push_back(Log2_32(GV->getAlignment())+1);
368 Vals.push_back(GV->hasSection() ? SectionMap[GV->getSection()] : 0);
369 if (GV->isThreadLocal() ||
370 GV->getVisibility() != GlobalValue::DefaultVisibility) {
371 Vals.push_back(getEncodedVisibility(GV));
372 Vals.push_back(GV->isThreadLocal());
373 } else {
374 AbbrevToUse = SimpleGVarAbbrev;
375 }
376
377 Stream.EmitRecord(bitc::MODULE_CODE_GLOBALVAR, Vals, AbbrevToUse);
378 Vals.clear();
379 }
380
381 // Emit the function proto information.
382 for (Module::const_iterator F = M->begin(), E = M->end(); F != E; ++F) {
Duncan Sandsf5588dc2007-11-27 13:23:08 +0000383 // FUNCTION: [type, callingconv, isproto, paramattr,
384 // linkage, alignment, section, visibility]
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000385 Vals.push_back(VE.getTypeID(F->getType()));
386 Vals.push_back(F->getCallingConv());
387 Vals.push_back(F->isDeclaration());
388 Vals.push_back(getEncodedLinkage(F));
Duncan Sandsf5588dc2007-11-27 13:23:08 +0000389 Vals.push_back(VE.getParamAttrID(F->getParamAttrs()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000390 Vals.push_back(Log2_32(F->getAlignment())+1);
391 Vals.push_back(F->hasSection() ? SectionMap[F->getSection()] : 0);
392 Vals.push_back(getEncodedVisibility(F));
393
394 unsigned AbbrevToUse = 0;
395 Stream.EmitRecord(bitc::MODULE_CODE_FUNCTION, Vals, AbbrevToUse);
396 Vals.clear();
397 }
398
399
400 // Emit the alias information.
401 for (Module::const_alias_iterator AI = M->alias_begin(), E = M->alias_end();
402 AI != E; ++AI) {
403 Vals.push_back(VE.getTypeID(AI->getType()));
404 Vals.push_back(VE.getValueID(AI->getAliasee()));
405 Vals.push_back(getEncodedLinkage(AI));
406 unsigned AbbrevToUse = 0;
407 Stream.EmitRecord(bitc::MODULE_CODE_ALIAS, Vals, AbbrevToUse);
408 Vals.clear();
409 }
410}
411
412
413static void WriteConstants(unsigned FirstVal, unsigned LastVal,
414 const ValueEnumerator &VE,
415 BitstreamWriter &Stream, bool isGlobal) {
416 if (FirstVal == LastVal) return;
417
418 Stream.EnterSubblock(bitc::CONSTANTS_BLOCK_ID, 4);
419
420 unsigned AggregateAbbrev = 0;
421 unsigned String8Abbrev = 0;
422 unsigned CString7Abbrev = 0;
423 unsigned CString6Abbrev = 0;
424 // If this is a constant pool for the module, emit module-specific abbrevs.
425 if (isGlobal) {
426 // Abbrev for CST_CODE_AGGREGATE.
427 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
428 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_AGGREGATE));
429 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
430 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, Log2_32_Ceil(LastVal+1)));
431 AggregateAbbrev = Stream.EmitAbbrev(Abbv);
432
433 // Abbrev for CST_CODE_STRING.
434 Abbv = new BitCodeAbbrev();
435 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_STRING));
436 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
437 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
438 String8Abbrev = Stream.EmitAbbrev(Abbv);
439 // Abbrev for CST_CODE_CSTRING.
440 Abbv = new BitCodeAbbrev();
441 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_CSTRING));
442 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
443 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7));
444 CString7Abbrev = Stream.EmitAbbrev(Abbv);
445 // Abbrev for CST_CODE_CSTRING.
446 Abbv = new BitCodeAbbrev();
447 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_CSTRING));
448 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
449 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
450 CString6Abbrev = Stream.EmitAbbrev(Abbv);
451 }
452
453 SmallVector<uint64_t, 64> Record;
454
455 const ValueEnumerator::ValueList &Vals = VE.getValues();
456 const Type *LastTy = 0;
457 for (unsigned i = FirstVal; i != LastVal; ++i) {
458 const Value *V = Vals[i].first;
459 // If we need to switch types, do so now.
460 if (V->getType() != LastTy) {
461 LastTy = V->getType();
462 Record.push_back(VE.getTypeID(LastTy));
463 Stream.EmitRecord(bitc::CST_CODE_SETTYPE, Record,
464 CONSTANTS_SETTYPE_ABBREV);
465 Record.clear();
466 }
467
468 if (const InlineAsm *IA = dyn_cast<InlineAsm>(V)) {
469 Record.push_back(unsigned(IA->hasSideEffects()));
470
471 // Add the asm string.
472 const std::string &AsmStr = IA->getAsmString();
473 Record.push_back(AsmStr.size());
474 for (unsigned i = 0, e = AsmStr.size(); i != e; ++i)
475 Record.push_back(AsmStr[i]);
476
477 // Add the constraint string.
478 const std::string &ConstraintStr = IA->getConstraintString();
479 Record.push_back(ConstraintStr.size());
480 for (unsigned i = 0, e = ConstraintStr.size(); i != e; ++i)
481 Record.push_back(ConstraintStr[i]);
482 Stream.EmitRecord(bitc::CST_CODE_INLINEASM, Record);
483 Record.clear();
484 continue;
485 }
486 const Constant *C = cast<Constant>(V);
487 unsigned Code = -1U;
488 unsigned AbbrevToUse = 0;
489 if (C->isNullValue()) {
490 Code = bitc::CST_CODE_NULL;
491 } else if (isa<UndefValue>(C)) {
492 Code = bitc::CST_CODE_UNDEF;
493 } else if (const ConstantInt *IV = dyn_cast<ConstantInt>(C)) {
494 if (IV->getBitWidth() <= 64) {
495 int64_t V = IV->getSExtValue();
496 if (V >= 0)
497 Record.push_back(V << 1);
498 else
499 Record.push_back((-V << 1) | 1);
500 Code = bitc::CST_CODE_INTEGER;
501 AbbrevToUse = CONSTANTS_INTEGER_ABBREV;
502 } else { // Wide integers, > 64 bits in size.
503 // We have an arbitrary precision integer value to write whose
504 // bit width is > 64. However, in canonical unsigned integer
505 // format it is likely that the high bits are going to be zero.
506 // So, we only write the number of active words.
507 unsigned NWords = IV->getValue().getActiveWords();
508 const uint64_t *RawWords = IV->getValue().getRawData();
509 for (unsigned i = 0; i != NWords; ++i) {
510 int64_t V = RawWords[i];
511 if (V >= 0)
512 Record.push_back(V << 1);
513 else
514 Record.push_back((-V << 1) | 1);
515 }
516 Code = bitc::CST_CODE_WIDE_INTEGER;
517 }
518 } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
519 Code = bitc::CST_CODE_FLOAT;
Dale Johannesene617f912007-08-09 22:51:36 +0000520 const Type *Ty = CFP->getType();
Dale Johannesenfbd9cda2007-09-12 03:30:33 +0000521 if (Ty == Type::FloatTy || Ty == Type::DoubleTy) {
522 Record.push_back(CFP->getValueAPF().convertToAPInt().getZExtValue());
Dale Johannesen1616e902007-09-11 18:32:33 +0000523 } else if (Ty == Type::X86_FP80Ty) {
Dale Johannesen693aa822007-09-26 23:20:33 +0000524 // api needed to prevent premature destruction
525 APInt api = CFP->getValueAPF().convertToAPInt();
526 const uint64_t *p = api.getRawData();
Dale Johannesen1616e902007-09-11 18:32:33 +0000527 Record.push_back(p[0]);
528 Record.push_back((uint16_t)p[1]);
Dale Johannesen2aef5692007-10-11 18:07:22 +0000529 } else if (Ty == Type::FP128Ty || Ty == Type::PPC_FP128Ty) {
Dale Johannesen693aa822007-09-26 23:20:33 +0000530 APInt api = CFP->getValueAPF().convertToAPInt();
531 const uint64_t *p = api.getRawData();
Dale Johannesen1616e902007-09-11 18:32:33 +0000532 Record.push_back(p[0]);
533 Record.push_back(p[1]);
Dale Johannesene617f912007-08-09 22:51:36 +0000534 } else {
535 assert (0 && "Unknown FP type!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000536 }
537 } else if (isa<ConstantArray>(C) && cast<ConstantArray>(C)->isString()) {
538 // Emit constant strings specially.
539 unsigned NumOps = C->getNumOperands();
540 // If this is a null-terminated string, use the denser CSTRING encoding.
541 if (C->getOperand(NumOps-1)->isNullValue()) {
542 Code = bitc::CST_CODE_CSTRING;
543 --NumOps; // Don't encode the null, which isn't allowed by char6.
544 } else {
545 Code = bitc::CST_CODE_STRING;
546 AbbrevToUse = String8Abbrev;
547 }
548 bool isCStr7 = Code == bitc::CST_CODE_CSTRING;
549 bool isCStrChar6 = Code == bitc::CST_CODE_CSTRING;
550 for (unsigned i = 0; i != NumOps; ++i) {
551 unsigned char V = cast<ConstantInt>(C->getOperand(i))->getZExtValue();
552 Record.push_back(V);
553 isCStr7 &= (V & 128) == 0;
554 if (isCStrChar6)
555 isCStrChar6 = BitCodeAbbrevOp::isChar6(V);
556 }
557
558 if (isCStrChar6)
559 AbbrevToUse = CString6Abbrev;
560 else if (isCStr7)
561 AbbrevToUse = CString7Abbrev;
562 } else if (isa<ConstantArray>(C) || isa<ConstantStruct>(V) ||
563 isa<ConstantVector>(V)) {
564 Code = bitc::CST_CODE_AGGREGATE;
565 for (unsigned i = 0, e = C->getNumOperands(); i != e; ++i)
566 Record.push_back(VE.getValueID(C->getOperand(i)));
567 AbbrevToUse = AggregateAbbrev;
568 } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
569 switch (CE->getOpcode()) {
570 default:
571 if (Instruction::isCast(CE->getOpcode())) {
572 Code = bitc::CST_CODE_CE_CAST;
573 Record.push_back(GetEncodedCastOpcode(CE->getOpcode()));
574 Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
575 Record.push_back(VE.getValueID(C->getOperand(0)));
576 AbbrevToUse = CONSTANTS_CE_CAST_Abbrev;
577 } else {
578 assert(CE->getNumOperands() == 2 && "Unknown constant expr!");
579 Code = bitc::CST_CODE_CE_BINOP;
580 Record.push_back(GetEncodedBinaryOpcode(CE->getOpcode()));
581 Record.push_back(VE.getValueID(C->getOperand(0)));
582 Record.push_back(VE.getValueID(C->getOperand(1)));
583 }
584 break;
585 case Instruction::GetElementPtr:
586 Code = bitc::CST_CODE_CE_GEP;
587 for (unsigned i = 0, e = CE->getNumOperands(); i != e; ++i) {
588 Record.push_back(VE.getTypeID(C->getOperand(i)->getType()));
589 Record.push_back(VE.getValueID(C->getOperand(i)));
590 }
591 break;
592 case Instruction::Select:
593 Code = bitc::CST_CODE_CE_SELECT;
594 Record.push_back(VE.getValueID(C->getOperand(0)));
595 Record.push_back(VE.getValueID(C->getOperand(1)));
596 Record.push_back(VE.getValueID(C->getOperand(2)));
597 break;
598 case Instruction::ExtractElement:
599 Code = bitc::CST_CODE_CE_EXTRACTELT;
600 Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
601 Record.push_back(VE.getValueID(C->getOperand(0)));
602 Record.push_back(VE.getValueID(C->getOperand(1)));
603 break;
604 case Instruction::InsertElement:
605 Code = bitc::CST_CODE_CE_INSERTELT;
606 Record.push_back(VE.getValueID(C->getOperand(0)));
607 Record.push_back(VE.getValueID(C->getOperand(1)));
608 Record.push_back(VE.getValueID(C->getOperand(2)));
609 break;
610 case Instruction::ShuffleVector:
611 Code = bitc::CST_CODE_CE_SHUFFLEVEC;
612 Record.push_back(VE.getValueID(C->getOperand(0)));
613 Record.push_back(VE.getValueID(C->getOperand(1)));
614 Record.push_back(VE.getValueID(C->getOperand(2)));
615 break;
616 case Instruction::ICmp:
617 case Instruction::FCmp:
618 Code = bitc::CST_CODE_CE_CMP;
619 Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
620 Record.push_back(VE.getValueID(C->getOperand(0)));
621 Record.push_back(VE.getValueID(C->getOperand(1)));
622 Record.push_back(CE->getPredicate());
623 break;
624 }
625 } else {
626 assert(0 && "Unknown constant!");
627 }
628 Stream.EmitRecord(Code, Record, AbbrevToUse);
629 Record.clear();
630 }
631
632 Stream.ExitBlock();
633}
634
635static void WriteModuleConstants(const ValueEnumerator &VE,
636 BitstreamWriter &Stream) {
637 const ValueEnumerator::ValueList &Vals = VE.getValues();
638
639 // Find the first constant to emit, which is the first non-globalvalue value.
640 // We know globalvalues have been emitted by WriteModuleInfo.
641 for (unsigned i = 0, e = Vals.size(); i != e; ++i) {
642 if (!isa<GlobalValue>(Vals[i].first)) {
643 WriteConstants(i, Vals.size(), VE, Stream, true);
644 return;
645 }
646 }
647}
648
649/// PushValueAndType - The file has to encode both the value and type id for
650/// many values, because we need to know what type to create for forward
651/// references. However, most operands are not forward references, so this type
652/// field is not needed.
653///
654/// This function adds V's value ID to Vals. If the value ID is higher than the
655/// instruction ID, then it is a forward reference, and it also includes the
656/// type ID.
657static bool PushValueAndType(Value *V, unsigned InstID,
658 SmallVector<unsigned, 64> &Vals,
659 ValueEnumerator &VE) {
660 unsigned ValID = VE.getValueID(V);
661 Vals.push_back(ValID);
662 if (ValID >= InstID) {
663 Vals.push_back(VE.getTypeID(V->getType()));
664 return true;
665 }
666 return false;
667}
668
669/// WriteInstruction - Emit an instruction to the specified stream.
670static void WriteInstruction(const Instruction &I, unsigned InstID,
671 ValueEnumerator &VE, BitstreamWriter &Stream,
672 SmallVector<unsigned, 64> &Vals) {
673 unsigned Code = 0;
674 unsigned AbbrevToUse = 0;
675 switch (I.getOpcode()) {
676 default:
677 if (Instruction::isCast(I.getOpcode())) {
678 Code = bitc::FUNC_CODE_INST_CAST;
679 if (!PushValueAndType(I.getOperand(0), InstID, Vals, VE))
680 AbbrevToUse = FUNCTION_INST_CAST_ABBREV;
681 Vals.push_back(VE.getTypeID(I.getType()));
682 Vals.push_back(GetEncodedCastOpcode(I.getOpcode()));
683 } else {
684 assert(isa<BinaryOperator>(I) && "Unknown instruction!");
685 Code = bitc::FUNC_CODE_INST_BINOP;
686 if (!PushValueAndType(I.getOperand(0), InstID, Vals, VE))
687 AbbrevToUse = FUNCTION_INST_BINOP_ABBREV;
688 Vals.push_back(VE.getValueID(I.getOperand(1)));
689 Vals.push_back(GetEncodedBinaryOpcode(I.getOpcode()));
690 }
691 break;
692
693 case Instruction::GetElementPtr:
694 Code = bitc::FUNC_CODE_INST_GEP;
695 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
696 PushValueAndType(I.getOperand(i), InstID, Vals, VE);
697 break;
698 case Instruction::Select:
699 Code = bitc::FUNC_CODE_INST_SELECT;
700 PushValueAndType(I.getOperand(1), InstID, Vals, VE);
701 Vals.push_back(VE.getValueID(I.getOperand(2)));
702 Vals.push_back(VE.getValueID(I.getOperand(0)));
703 break;
704 case Instruction::ExtractElement:
705 Code = bitc::FUNC_CODE_INST_EXTRACTELT;
706 PushValueAndType(I.getOperand(0), InstID, Vals, VE);
707 Vals.push_back(VE.getValueID(I.getOperand(1)));
708 break;
709 case Instruction::InsertElement:
710 Code = bitc::FUNC_CODE_INST_INSERTELT;
711 PushValueAndType(I.getOperand(0), InstID, Vals, VE);
712 Vals.push_back(VE.getValueID(I.getOperand(1)));
713 Vals.push_back(VE.getValueID(I.getOperand(2)));
714 break;
715 case Instruction::ShuffleVector:
716 Code = bitc::FUNC_CODE_INST_SHUFFLEVEC;
717 PushValueAndType(I.getOperand(0), InstID, Vals, VE);
718 Vals.push_back(VE.getValueID(I.getOperand(1)));
719 Vals.push_back(VE.getValueID(I.getOperand(2)));
720 break;
721 case Instruction::ICmp:
722 case Instruction::FCmp:
723 Code = bitc::FUNC_CODE_INST_CMP;
724 PushValueAndType(I.getOperand(0), InstID, Vals, VE);
725 Vals.push_back(VE.getValueID(I.getOperand(1)));
726 Vals.push_back(cast<CmpInst>(I).getPredicate());
727 break;
728
729 case Instruction::Ret:
730 Code = bitc::FUNC_CODE_INST_RET;
731 if (!I.getNumOperands())
732 AbbrevToUse = FUNCTION_INST_RET_VOID_ABBREV;
733 else if (!PushValueAndType(I.getOperand(0), InstID, Vals, VE))
734 AbbrevToUse = FUNCTION_INST_RET_VAL_ABBREV;
735 break;
736 case Instruction::Br:
737 Code = bitc::FUNC_CODE_INST_BR;
738 Vals.push_back(VE.getValueID(I.getOperand(0)));
739 if (cast<BranchInst>(I).isConditional()) {
740 Vals.push_back(VE.getValueID(I.getOperand(1)));
741 Vals.push_back(VE.getValueID(I.getOperand(2)));
742 }
743 break;
744 case Instruction::Switch:
745 Code = bitc::FUNC_CODE_INST_SWITCH;
746 Vals.push_back(VE.getTypeID(I.getOperand(0)->getType()));
747 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
748 Vals.push_back(VE.getValueID(I.getOperand(i)));
749 break;
750 case Instruction::Invoke: {
751 const PointerType *PTy = cast<PointerType>(I.getOperand(0)->getType());
752 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
753 Code = bitc::FUNC_CODE_INST_INVOKE;
754
Duncan Sandsf5588dc2007-11-27 13:23:08 +0000755 const InvokeInst *II = cast<InvokeInst>(&I);
756 Vals.push_back(VE.getParamAttrID(II->getParamAttrs()));
757 Vals.push_back(II->getCallingConv());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000758 Vals.push_back(VE.getValueID(I.getOperand(1))); // normal dest
759 Vals.push_back(VE.getValueID(I.getOperand(2))); // unwind dest
760 PushValueAndType(I.getOperand(0), InstID, Vals, VE); // callee
761
762 // Emit value #'s for the fixed parameters.
763 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
764 Vals.push_back(VE.getValueID(I.getOperand(i+3))); // fixed param.
765
766 // Emit type/value pairs for varargs params.
767 if (FTy->isVarArg()) {
768 for (unsigned i = 3+FTy->getNumParams(), e = I.getNumOperands();
769 i != e; ++i)
770 PushValueAndType(I.getOperand(i), InstID, Vals, VE); // vararg
771 }
772 break;
773 }
774 case Instruction::Unwind:
775 Code = bitc::FUNC_CODE_INST_UNWIND;
776 break;
777 case Instruction::Unreachable:
778 Code = bitc::FUNC_CODE_INST_UNREACHABLE;
779 AbbrevToUse = FUNCTION_INST_UNREACHABLE_ABBREV;
780 break;
781
782 case Instruction::PHI:
783 Code = bitc::FUNC_CODE_INST_PHI;
784 Vals.push_back(VE.getTypeID(I.getType()));
785 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
786 Vals.push_back(VE.getValueID(I.getOperand(i)));
787 break;
788
789 case Instruction::Malloc:
790 Code = bitc::FUNC_CODE_INST_MALLOC;
791 Vals.push_back(VE.getTypeID(I.getType()));
792 Vals.push_back(VE.getValueID(I.getOperand(0))); // size.
793 Vals.push_back(Log2_32(cast<MallocInst>(I).getAlignment())+1);
794 break;
795
796 case Instruction::Free:
797 Code = bitc::FUNC_CODE_INST_FREE;
798 PushValueAndType(I.getOperand(0), InstID, Vals, VE);
799 break;
800
801 case Instruction::Alloca:
802 Code = bitc::FUNC_CODE_INST_ALLOCA;
803 Vals.push_back(VE.getTypeID(I.getType()));
804 Vals.push_back(VE.getValueID(I.getOperand(0))); // size.
805 Vals.push_back(Log2_32(cast<AllocaInst>(I).getAlignment())+1);
806 break;
807
808 case Instruction::Load:
809 Code = bitc::FUNC_CODE_INST_LOAD;
810 if (!PushValueAndType(I.getOperand(0), InstID, Vals, VE)) // ptr
811 AbbrevToUse = FUNCTION_INST_LOAD_ABBREV;
812
813 Vals.push_back(Log2_32(cast<LoadInst>(I).getAlignment())+1);
814 Vals.push_back(cast<LoadInst>(I).isVolatile());
815 break;
816 case Instruction::Store:
817 Code = bitc::FUNC_CODE_INST_STORE;
818 PushValueAndType(I.getOperand(0), InstID, Vals, VE); // val.
819 Vals.push_back(VE.getValueID(I.getOperand(1))); // ptr.
820 Vals.push_back(Log2_32(cast<StoreInst>(I).getAlignment())+1);
821 Vals.push_back(cast<StoreInst>(I).isVolatile());
822 break;
823 case Instruction::Call: {
824 const PointerType *PTy = cast<PointerType>(I.getOperand(0)->getType());
825 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
826
827 Code = bitc::FUNC_CODE_INST_CALL;
828
Duncan Sandsf5588dc2007-11-27 13:23:08 +0000829 const CallInst *CI = cast<CallInst>(&I);
830 Vals.push_back(VE.getParamAttrID(CI->getParamAttrs()));
831 Vals.push_back((CI->getCallingConv() << 1) | unsigned(CI->isTailCall()));
832 PushValueAndType(CI->getOperand(0), InstID, Vals, VE); // Callee
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000833
834 // Emit value #'s for the fixed parameters.
835 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
836 Vals.push_back(VE.getValueID(I.getOperand(i+1))); // fixed param.
837
838 // Emit type/value pairs for varargs params.
839 if (FTy->isVarArg()) {
840 unsigned NumVarargs = I.getNumOperands()-1-FTy->getNumParams();
841 for (unsigned i = I.getNumOperands()-NumVarargs, e = I.getNumOperands();
842 i != e; ++i)
843 PushValueAndType(I.getOperand(i), InstID, Vals, VE); // varargs
844 }
845 break;
846 }
847 case Instruction::VAArg:
848 Code = bitc::FUNC_CODE_INST_VAARG;
849 Vals.push_back(VE.getTypeID(I.getOperand(0)->getType())); // valistty
850 Vals.push_back(VE.getValueID(I.getOperand(0))); // valist.
851 Vals.push_back(VE.getTypeID(I.getType())); // restype.
852 break;
853 }
854
855 Stream.EmitRecord(Code, Vals, AbbrevToUse);
856 Vals.clear();
857}
858
859// Emit names for globals/functions etc.
860static void WriteValueSymbolTable(const ValueSymbolTable &VST,
861 const ValueEnumerator &VE,
862 BitstreamWriter &Stream) {
863 if (VST.empty()) return;
864 Stream.EnterSubblock(bitc::VALUE_SYMTAB_BLOCK_ID, 4);
865
866 // FIXME: Set up the abbrev, we know how many values there are!
867 // FIXME: We know if the type names can use 7-bit ascii.
868 SmallVector<unsigned, 64> NameVals;
869
870 for (ValueSymbolTable::const_iterator SI = VST.begin(), SE = VST.end();
871 SI != SE; ++SI) {
872
873 const ValueName &Name = *SI;
874
875 // Figure out the encoding to use for the name.
876 bool is7Bit = true;
877 bool isChar6 = true;
878 for (const char *C = Name.getKeyData(), *E = C+Name.getKeyLength();
879 C != E; ++C) {
880 if (isChar6)
881 isChar6 = BitCodeAbbrevOp::isChar6(*C);
882 if ((unsigned char)*C & 128) {
883 is7Bit = false;
884 break; // don't bother scanning the rest.
885 }
886 }
887
888 unsigned AbbrevToUse = VST_ENTRY_8_ABBREV;
889
890 // VST_ENTRY: [valueid, namechar x N]
891 // VST_BBENTRY: [bbid, namechar x N]
892 unsigned Code;
893 if (isa<BasicBlock>(SI->getValue())) {
894 Code = bitc::VST_CODE_BBENTRY;
895 if (isChar6)
896 AbbrevToUse = VST_BBENTRY_6_ABBREV;
897 } else {
898 Code = bitc::VST_CODE_ENTRY;
899 if (isChar6)
900 AbbrevToUse = VST_ENTRY_6_ABBREV;
901 else if (is7Bit)
902 AbbrevToUse = VST_ENTRY_7_ABBREV;
903 }
904
905 NameVals.push_back(VE.getValueID(SI->getValue()));
906 for (const char *P = Name.getKeyData(),
907 *E = Name.getKeyData()+Name.getKeyLength(); P != E; ++P)
908 NameVals.push_back((unsigned char)*P);
909
910 // Emit the finished record.
911 Stream.EmitRecord(Code, NameVals, AbbrevToUse);
912 NameVals.clear();
913 }
914 Stream.ExitBlock();
915}
916
917/// WriteFunction - Emit a function body to the module stream.
918static void WriteFunction(const Function &F, ValueEnumerator &VE,
919 BitstreamWriter &Stream) {
920 Stream.EnterSubblock(bitc::FUNCTION_BLOCK_ID, 4);
921 VE.incorporateFunction(F);
922
923 SmallVector<unsigned, 64> Vals;
924
925 // Emit the number of basic blocks, so the reader can create them ahead of
926 // time.
927 Vals.push_back(VE.getBasicBlocks().size());
928 Stream.EmitRecord(bitc::FUNC_CODE_DECLAREBLOCKS, Vals);
929 Vals.clear();
930
931 // If there are function-local constants, emit them now.
932 unsigned CstStart, CstEnd;
933 VE.getFunctionConstantRange(CstStart, CstEnd);
934 WriteConstants(CstStart, CstEnd, VE, Stream, false);
935
936 // Keep a running idea of what the instruction ID is.
937 unsigned InstID = CstEnd;
938
939 // Finally, emit all the instructions, in order.
940 for (Function::const_iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
941 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end();
942 I != E; ++I) {
943 WriteInstruction(*I, InstID, VE, Stream, Vals);
944 if (I->getType() != Type::VoidTy)
945 ++InstID;
946 }
947
948 // Emit names for all the instructions etc.
949 WriteValueSymbolTable(F.getValueSymbolTable(), VE, Stream);
950
951 VE.purgeFunction();
952 Stream.ExitBlock();
953}
954
955/// WriteTypeSymbolTable - Emit a block for the specified type symtab.
956static void WriteTypeSymbolTable(const TypeSymbolTable &TST,
957 const ValueEnumerator &VE,
958 BitstreamWriter &Stream) {
959 if (TST.empty()) return;
960
961 Stream.EnterSubblock(bitc::TYPE_SYMTAB_BLOCK_ID, 3);
962
963 // 7-bit fixed width VST_CODE_ENTRY strings.
964 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
965 Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_ENTRY));
966 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
967 Log2_32_Ceil(VE.getTypes().size()+1)));
968 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
969 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7));
970 unsigned V7Abbrev = Stream.EmitAbbrev(Abbv);
971
972 SmallVector<unsigned, 64> NameVals;
973
974 for (TypeSymbolTable::const_iterator TI = TST.begin(), TE = TST.end();
975 TI != TE; ++TI) {
976 // TST_ENTRY: [typeid, namechar x N]
977 NameVals.push_back(VE.getTypeID(TI->second));
978
979 const std::string &Str = TI->first;
980 bool is7Bit = true;
981 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
982 NameVals.push_back((unsigned char)Str[i]);
983 if (Str[i] & 128)
984 is7Bit = false;
985 }
986
987 // Emit the finished record.
988 Stream.EmitRecord(bitc::VST_CODE_ENTRY, NameVals, is7Bit ? V7Abbrev : 0);
989 NameVals.clear();
990 }
991
992 Stream.ExitBlock();
993}
994
995// Emit blockinfo, which defines the standard abbreviations etc.
996static void WriteBlockInfo(const ValueEnumerator &VE, BitstreamWriter &Stream) {
997 // We only want to emit block info records for blocks that have multiple
998 // instances: CONSTANTS_BLOCK, FUNCTION_BLOCK and VALUE_SYMTAB_BLOCK. Other
999 // blocks can defined their abbrevs inline.
1000 Stream.EnterBlockInfoBlock(2);
1001
1002 { // 8-bit fixed-width VST_ENTRY/VST_BBENTRY strings.
1003 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1004 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 3));
1005 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
1006 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1007 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
1008 if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID,
1009 Abbv) != VST_ENTRY_8_ABBREV)
1010 assert(0 && "Unexpected abbrev ordering!");
1011 }
1012
1013 { // 7-bit fixed width VST_ENTRY strings.
1014 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1015 Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_ENTRY));
1016 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
1017 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1018 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7));
1019 if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID,
1020 Abbv) != VST_ENTRY_7_ABBREV)
1021 assert(0 && "Unexpected abbrev ordering!");
1022 }
1023 { // 6-bit char6 VST_ENTRY strings.
1024 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1025 Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_ENTRY));
1026 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
1027 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1028 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
1029 if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID,
1030 Abbv) != VST_ENTRY_6_ABBREV)
1031 assert(0 && "Unexpected abbrev ordering!");
1032 }
1033 { // 6-bit char6 VST_BBENTRY strings.
1034 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1035 Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_BBENTRY));
1036 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
1037 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1038 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
1039 if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID,
1040 Abbv) != VST_BBENTRY_6_ABBREV)
1041 assert(0 && "Unexpected abbrev ordering!");
1042 }
1043
1044
1045
1046 { // SETTYPE abbrev for CONSTANTS_BLOCK.
1047 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1048 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_SETTYPE));
1049 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
1050 Log2_32_Ceil(VE.getTypes().size()+1)));
1051 if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID,
1052 Abbv) != CONSTANTS_SETTYPE_ABBREV)
1053 assert(0 && "Unexpected abbrev ordering!");
1054 }
1055
1056 { // INTEGER abbrev for CONSTANTS_BLOCK.
1057 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1058 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_INTEGER));
1059 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
1060 if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID,
1061 Abbv) != CONSTANTS_INTEGER_ABBREV)
1062 assert(0 && "Unexpected abbrev ordering!");
1063 }
1064
1065 { // CE_CAST abbrev for CONSTANTS_BLOCK.
1066 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1067 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_CE_CAST));
1068 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // cast opc
1069 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, // typeid
1070 Log2_32_Ceil(VE.getTypes().size()+1)));
1071 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // value id
1072
1073 if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID,
1074 Abbv) != CONSTANTS_CE_CAST_Abbrev)
1075 assert(0 && "Unexpected abbrev ordering!");
1076 }
1077 { // NULL abbrev for CONSTANTS_BLOCK.
1078 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1079 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_NULL));
1080 if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID,
1081 Abbv) != CONSTANTS_NULL_Abbrev)
1082 assert(0 && "Unexpected abbrev ordering!");
1083 }
1084
1085 // FIXME: This should only use space for first class types!
1086
1087 { // INST_LOAD abbrev for FUNCTION_BLOCK.
1088 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1089 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_LOAD));
1090 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Ptr
1091 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // Align
1092 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // volatile
1093 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
1094 Abbv) != FUNCTION_INST_LOAD_ABBREV)
1095 assert(0 && "Unexpected abbrev ordering!");
1096 }
1097 { // INST_BINOP abbrev for FUNCTION_BLOCK.
1098 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1099 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_BINOP));
1100 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // LHS
1101 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // RHS
1102 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
1103 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
1104 Abbv) != FUNCTION_INST_BINOP_ABBREV)
1105 assert(0 && "Unexpected abbrev ordering!");
1106 }
1107 { // INST_CAST abbrev for FUNCTION_BLOCK.
1108 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1109 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_CAST));
1110 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // OpVal
1111 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, // dest ty
1112 Log2_32_Ceil(VE.getTypes().size()+1)));
1113 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
1114 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
1115 Abbv) != FUNCTION_INST_CAST_ABBREV)
1116 assert(0 && "Unexpected abbrev ordering!");
1117 }
1118
1119 { // INST_RET abbrev for FUNCTION_BLOCK.
1120 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1121 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_RET));
1122 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
1123 Abbv) != FUNCTION_INST_RET_VOID_ABBREV)
1124 assert(0 && "Unexpected abbrev ordering!");
1125 }
1126 { // INST_RET abbrev for FUNCTION_BLOCK.
1127 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1128 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_RET));
1129 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // ValID
1130 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
1131 Abbv) != FUNCTION_INST_RET_VAL_ABBREV)
1132 assert(0 && "Unexpected abbrev ordering!");
1133 }
1134 { // INST_UNREACHABLE abbrev for FUNCTION_BLOCK.
1135 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1136 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_UNREACHABLE));
1137 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
1138 Abbv) != FUNCTION_INST_UNREACHABLE_ABBREV)
1139 assert(0 && "Unexpected abbrev ordering!");
1140 }
1141
1142 Stream.ExitBlock();
1143}
1144
1145
1146/// WriteModule - Emit the specified module to the bitstream.
1147static void WriteModule(const Module *M, BitstreamWriter &Stream) {
1148 Stream.EnterSubblock(bitc::MODULE_BLOCK_ID, 3);
1149
1150 // Emit the version number if it is non-zero.
1151 if (CurVersion) {
1152 SmallVector<unsigned, 1> Vals;
1153 Vals.push_back(CurVersion);
1154 Stream.EmitRecord(bitc::MODULE_CODE_VERSION, Vals);
1155 }
1156
1157 // Analyze the module, enumerating globals, functions, etc.
1158 ValueEnumerator VE(M);
1159
1160 // Emit blockinfo, which defines the standard abbreviations etc.
1161 WriteBlockInfo(VE, Stream);
1162
1163 // Emit information about parameter attributes.
1164 WriteParamAttrTable(VE, Stream);
1165
1166 // Emit information describing all of the types in the module.
1167 WriteTypeTable(VE, Stream);
1168
1169 // Emit top-level description of module, including target triple, inline asm,
1170 // descriptors for global variables, and function prototype info.
1171 WriteModuleInfo(M, VE, Stream);
1172
1173 // Emit constants.
1174 WriteModuleConstants(VE, Stream);
1175
1176 // If we have any aggregate values in the value table, purge them - these can
1177 // only be used to initialize global variables. Doing so makes the value
1178 // namespace smaller for code in functions.
1179 int NumNonAggregates = VE.PurgeAggregateValues();
1180 if (NumNonAggregates != -1) {
1181 SmallVector<unsigned, 1> Vals;
1182 Vals.push_back(NumNonAggregates);
1183 Stream.EmitRecord(bitc::MODULE_CODE_PURGEVALS, Vals);
1184 }
1185
1186 // Emit function bodies.
1187 for (Module::const_iterator I = M->begin(), E = M->end(); I != E; ++I)
1188 if (!I->isDeclaration())
1189 WriteFunction(*I, VE, Stream);
1190
1191 // Emit the type symbol table information.
1192 WriteTypeSymbolTable(M->getTypeSymbolTable(), VE, Stream);
1193
1194 // Emit names for globals/functions etc.
1195 WriteValueSymbolTable(M->getValueSymbolTable(), VE, Stream);
1196
1197 Stream.ExitBlock();
1198}
1199
1200
1201/// WriteBitcodeToFile - Write the specified module to the specified output
1202/// stream.
1203void llvm::WriteBitcodeToFile(const Module *M, std::ostream &Out) {
1204 std::vector<unsigned char> Buffer;
1205 BitstreamWriter Stream(Buffer);
1206
1207 Buffer.reserve(256*1024);
1208
1209 // Emit the file header.
1210 Stream.Emit((unsigned)'B', 8);
1211 Stream.Emit((unsigned)'C', 8);
1212 Stream.Emit(0x0, 4);
1213 Stream.Emit(0xC, 4);
1214 Stream.Emit(0xE, 4);
1215 Stream.Emit(0xD, 4);
1216
1217 // Emit the module.
1218 WriteModule(M, Stream);
1219
1220 // Write the generated bitstream to "Out".
1221 Out.write((char*)&Buffer.front(), Buffer.size());
1222
1223 // Make sure it hits disk now.
1224 Out.flush();
1225}