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