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