Improved bitcode support for insertvalue/extractvalue.
[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   case GlobalValue::CommonLinkage:       return 8;
274   }
275 }
276
277 static unsigned getEncodedVisibility(const GlobalValue *GV) {
278   switch (GV->getVisibility()) {
279   default: assert(0 && "Invalid visibility!");
280   case GlobalValue::DefaultVisibility:   return 0;
281   case GlobalValue::HiddenVisibility:    return 1;
282   case GlobalValue::ProtectedVisibility: return 2;
283   }
284 }
285
286 // Emit top-level description of module, including target triple, inline asm,
287 // descriptors for global variables, and function prototype info.
288 static void WriteModuleInfo(const Module *M, const ValueEnumerator &VE,
289                             BitstreamWriter &Stream) {
290   // Emit the list of dependent libraries for the Module.
291   for (Module::lib_iterator I = M->lib_begin(), E = M->lib_end(); I != E; ++I)
292     WriteStringRecord(bitc::MODULE_CODE_DEPLIB, *I, 0/*TODO*/, Stream);
293
294   // Emit various pieces of data attached to a module.
295   if (!M->getTargetTriple().empty())
296     WriteStringRecord(bitc::MODULE_CODE_TRIPLE, M->getTargetTriple(),
297                       0/*TODO*/, Stream);
298   if (!M->getDataLayout().empty())
299     WriteStringRecord(bitc::MODULE_CODE_DATALAYOUT, M->getDataLayout(),
300                       0/*TODO*/, Stream);
301   if (!M->getModuleInlineAsm().empty())
302     WriteStringRecord(bitc::MODULE_CODE_ASM, M->getModuleInlineAsm(),
303                       0/*TODO*/, Stream);
304
305   // Emit information about sections and collectors, computing how many there
306   // are.  Also compute the maximum alignment value.
307   std::map<std::string, unsigned> SectionMap;
308   std::map<std::string, unsigned> CollectorMap;
309   unsigned MaxAlignment = 0;
310   unsigned MaxGlobalType = 0;
311   for (Module::const_global_iterator GV = M->global_begin(),E = M->global_end();
312        GV != E; ++GV) {
313     MaxAlignment = std::max(MaxAlignment, GV->getAlignment());
314     MaxGlobalType = std::max(MaxGlobalType, VE.getTypeID(GV->getType()));
315     
316     if (!GV->hasSection()) continue;
317     // Give section names unique ID's.
318     unsigned &Entry = SectionMap[GV->getSection()];
319     if (Entry != 0) continue;
320     WriteStringRecord(bitc::MODULE_CODE_SECTIONNAME, GV->getSection(),
321                       0/*TODO*/, Stream);
322     Entry = SectionMap.size();
323   }
324   for (Module::const_iterator F = M->begin(), E = M->end(); F != E; ++F) {
325     MaxAlignment = std::max(MaxAlignment, F->getAlignment());
326     if (F->hasSection()) {
327       // Give section names unique ID's.
328       unsigned &Entry = SectionMap[F->getSection()];
329       if (!Entry) {
330         WriteStringRecord(bitc::MODULE_CODE_SECTIONNAME, F->getSection(),
331                           0/*TODO*/, Stream);
332         Entry = SectionMap.size();
333       }
334     }
335     if (F->hasCollector()) {
336       // Same for collector names.
337       unsigned &Entry = CollectorMap[F->getCollector()];
338       if (!Entry) {
339         WriteStringRecord(bitc::MODULE_CODE_COLLECTORNAME, F->getCollector(),
340                           0/*TODO*/, Stream);
341         Entry = CollectorMap.size();
342       }
343     }
344   }
345   
346   // Emit abbrev for globals, now that we know # sections and max alignment.
347   unsigned SimpleGVarAbbrev = 0;
348   if (!M->global_empty()) { 
349     // Add an abbrev for common globals with no visibility or thread localness.
350     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
351     Abbv->Add(BitCodeAbbrevOp(bitc::MODULE_CODE_GLOBALVAR));
352     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
353                               Log2_32_Ceil(MaxGlobalType+1)));
354     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));      // Constant.
355     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));        // Initializer.
356     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4));      // Linkage.
357     if (MaxAlignment == 0)                                      // Alignment.
358       Abbv->Add(BitCodeAbbrevOp(0));
359     else {
360       unsigned MaxEncAlignment = Log2_32(MaxAlignment)+1;
361       Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
362                                Log2_32_Ceil(MaxEncAlignment+1)));
363     }
364     if (SectionMap.empty())                                    // Section.
365       Abbv->Add(BitCodeAbbrevOp(0));
366     else
367       Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
368                                Log2_32_Ceil(SectionMap.size()+1)));
369     // Don't bother emitting vis + thread local.
370     SimpleGVarAbbrev = Stream.EmitAbbrev(Abbv);
371   }
372   
373   // Emit the global variable information.
374   SmallVector<unsigned, 64> Vals;
375   for (Module::const_global_iterator GV = M->global_begin(),E = M->global_end();
376        GV != E; ++GV) {
377     unsigned AbbrevToUse = 0;
378
379     // GLOBALVAR: [type, isconst, initid, 
380     //             linkage, alignment, section, visibility, threadlocal]
381     Vals.push_back(VE.getTypeID(GV->getType()));
382     Vals.push_back(GV->isConstant());
383     Vals.push_back(GV->isDeclaration() ? 0 :
384                    (VE.getValueID(GV->getInitializer()) + 1));
385     Vals.push_back(getEncodedLinkage(GV));
386     Vals.push_back(Log2_32(GV->getAlignment())+1);
387     Vals.push_back(GV->hasSection() ? SectionMap[GV->getSection()] : 0);
388     if (GV->isThreadLocal() || 
389         GV->getVisibility() != GlobalValue::DefaultVisibility) {
390       Vals.push_back(getEncodedVisibility(GV));
391       Vals.push_back(GV->isThreadLocal());
392     } else {
393       AbbrevToUse = SimpleGVarAbbrev;
394     }
395     
396     Stream.EmitRecord(bitc::MODULE_CODE_GLOBALVAR, Vals, AbbrevToUse);
397     Vals.clear();
398   }
399
400   // Emit the function proto information.
401   for (Module::const_iterator F = M->begin(), E = M->end(); F != E; ++F) {
402     // FUNCTION:  [type, callingconv, isproto, paramattr,
403     //             linkage, alignment, section, visibility, collector]
404     Vals.push_back(VE.getTypeID(F->getType()));
405     Vals.push_back(F->getCallingConv());
406     Vals.push_back(F->isDeclaration());
407     Vals.push_back(getEncodedLinkage(F));
408     Vals.push_back(VE.getParamAttrID(F->getParamAttrs()));
409     Vals.push_back(Log2_32(F->getAlignment())+1);
410     Vals.push_back(F->hasSection() ? SectionMap[F->getSection()] : 0);
411     Vals.push_back(getEncodedVisibility(F));
412     Vals.push_back(F->hasCollector() ? CollectorMap[F->getCollector()] : 0);
413     
414     unsigned AbbrevToUse = 0;
415     Stream.EmitRecord(bitc::MODULE_CODE_FUNCTION, Vals, AbbrevToUse);
416     Vals.clear();
417   }
418   
419   
420   // Emit the alias information.
421   for (Module::const_alias_iterator AI = M->alias_begin(), E = M->alias_end();
422        AI != E; ++AI) {
423     Vals.push_back(VE.getTypeID(AI->getType()));
424     Vals.push_back(VE.getValueID(AI->getAliasee()));
425     Vals.push_back(getEncodedLinkage(AI));
426     Vals.push_back(getEncodedVisibility(AI));
427     unsigned AbbrevToUse = 0;
428     Stream.EmitRecord(bitc::MODULE_CODE_ALIAS, Vals, AbbrevToUse);
429     Vals.clear();
430   }
431 }
432
433
434 static void WriteConstants(unsigned FirstVal, unsigned LastVal,
435                            const ValueEnumerator &VE,
436                            BitstreamWriter &Stream, bool isGlobal) {
437   if (FirstVal == LastVal) return;
438   
439   Stream.EnterSubblock(bitc::CONSTANTS_BLOCK_ID, 4);
440
441   unsigned AggregateAbbrev = 0;
442   unsigned String8Abbrev = 0;
443   unsigned CString7Abbrev = 0;
444   unsigned CString6Abbrev = 0;
445   // If this is a constant pool for the module, emit module-specific abbrevs.
446   if (isGlobal) {
447     // Abbrev for CST_CODE_AGGREGATE.
448     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
449     Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_AGGREGATE));
450     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
451     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, Log2_32_Ceil(LastVal+1)));
452     AggregateAbbrev = Stream.EmitAbbrev(Abbv);
453
454     // Abbrev for CST_CODE_STRING.
455     Abbv = new BitCodeAbbrev();
456     Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_STRING));
457     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
458     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
459     String8Abbrev = Stream.EmitAbbrev(Abbv);
460     // Abbrev for CST_CODE_CSTRING.
461     Abbv = new BitCodeAbbrev();
462     Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_CSTRING));
463     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
464     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7));
465     CString7Abbrev = Stream.EmitAbbrev(Abbv);
466     // Abbrev for CST_CODE_CSTRING.
467     Abbv = new BitCodeAbbrev();
468     Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_CSTRING));
469     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
470     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
471     CString6Abbrev = Stream.EmitAbbrev(Abbv);
472   }  
473   
474   SmallVector<uint64_t, 64> Record;
475
476   const ValueEnumerator::ValueList &Vals = VE.getValues();
477   const Type *LastTy = 0;
478   for (unsigned i = FirstVal; i != LastVal; ++i) {
479     const Value *V = Vals[i].first;
480     // If we need to switch types, do so now.
481     if (V->getType() != LastTy) {
482       LastTy = V->getType();
483       Record.push_back(VE.getTypeID(LastTy));
484       Stream.EmitRecord(bitc::CST_CODE_SETTYPE, Record,
485                         CONSTANTS_SETTYPE_ABBREV);
486       Record.clear();
487     }
488     
489     if (const InlineAsm *IA = dyn_cast<InlineAsm>(V)) {
490       Record.push_back(unsigned(IA->hasSideEffects()));
491       
492       // Add the asm string.
493       const std::string &AsmStr = IA->getAsmString();
494       Record.push_back(AsmStr.size());
495       for (unsigned i = 0, e = AsmStr.size(); i != e; ++i)
496         Record.push_back(AsmStr[i]);
497       
498       // Add the constraint string.
499       const std::string &ConstraintStr = IA->getConstraintString();
500       Record.push_back(ConstraintStr.size());
501       for (unsigned i = 0, e = ConstraintStr.size(); i != e; ++i)
502         Record.push_back(ConstraintStr[i]);
503       Stream.EmitRecord(bitc::CST_CODE_INLINEASM, Record);
504       Record.clear();
505       continue;
506     }
507     const Constant *C = cast<Constant>(V);
508     unsigned Code = -1U;
509     unsigned AbbrevToUse = 0;
510     if (C->isNullValue()) {
511       Code = bitc::CST_CODE_NULL;
512     } else if (isa<UndefValue>(C)) {
513       Code = bitc::CST_CODE_UNDEF;
514     } else if (const ConstantInt *IV = dyn_cast<ConstantInt>(C)) {
515       if (IV->getBitWidth() <= 64) {
516         int64_t V = IV->getSExtValue();
517         if (V >= 0)
518           Record.push_back(V << 1);
519         else
520           Record.push_back((-V << 1) | 1);
521         Code = bitc::CST_CODE_INTEGER;
522         AbbrevToUse = CONSTANTS_INTEGER_ABBREV;
523       } else {                             // Wide integers, > 64 bits in size.
524         // We have an arbitrary precision integer value to write whose 
525         // bit width is > 64. However, in canonical unsigned integer 
526         // format it is likely that the high bits are going to be zero.
527         // So, we only write the number of active words.
528         unsigned NWords = IV->getValue().getActiveWords(); 
529         const uint64_t *RawWords = IV->getValue().getRawData();
530         for (unsigned i = 0; i != NWords; ++i) {
531           int64_t V = RawWords[i];
532           if (V >= 0)
533             Record.push_back(V << 1);
534           else
535             Record.push_back((-V << 1) | 1);
536         }
537         Code = bitc::CST_CODE_WIDE_INTEGER;
538       }
539     } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
540       Code = bitc::CST_CODE_FLOAT;
541       const Type *Ty = CFP->getType();
542       if (Ty == Type::FloatTy || Ty == Type::DoubleTy) {
543         Record.push_back(CFP->getValueAPF().convertToAPInt().getZExtValue());
544       } else if (Ty == Type::X86_FP80Ty) {
545         // api needed to prevent premature destruction
546         APInt api = CFP->getValueAPF().convertToAPInt();
547         const uint64_t *p = api.getRawData();
548         Record.push_back(p[0]);
549         Record.push_back((uint16_t)p[1]);
550       } else if (Ty == Type::FP128Ty || Ty == Type::PPC_FP128Ty) {
551         APInt api = CFP->getValueAPF().convertToAPInt();
552         const uint64_t *p = api.getRawData();
553         Record.push_back(p[0]);
554         Record.push_back(p[1]);
555       } else {
556         assert (0 && "Unknown FP type!");
557       }
558     } else if (isa<ConstantArray>(C) && cast<ConstantArray>(C)->isString()) {
559       // Emit constant strings specially.
560       unsigned NumOps = C->getNumOperands();
561       // If this is a null-terminated string, use the denser CSTRING encoding.
562       if (C->getOperand(NumOps-1)->isNullValue()) {
563         Code = bitc::CST_CODE_CSTRING;
564         --NumOps;  // Don't encode the null, which isn't allowed by char6.
565       } else {
566         Code = bitc::CST_CODE_STRING;
567         AbbrevToUse = String8Abbrev;
568       }
569       bool isCStr7 = Code == bitc::CST_CODE_CSTRING;
570       bool isCStrChar6 = Code == bitc::CST_CODE_CSTRING;
571       for (unsigned i = 0; i != NumOps; ++i) {
572         unsigned char V = cast<ConstantInt>(C->getOperand(i))->getZExtValue();
573         Record.push_back(V);
574         isCStr7 &= (V & 128) == 0;
575         if (isCStrChar6) 
576           isCStrChar6 = BitCodeAbbrevOp::isChar6(V);
577       }
578       
579       if (isCStrChar6)
580         AbbrevToUse = CString6Abbrev;
581       else if (isCStr7)
582         AbbrevToUse = CString7Abbrev;
583     } else if (isa<ConstantArray>(C) || isa<ConstantStruct>(V) ||
584                isa<ConstantVector>(V)) {
585       Code = bitc::CST_CODE_AGGREGATE;
586       for (unsigned i = 0, e = C->getNumOperands(); i != e; ++i)
587         Record.push_back(VE.getValueID(C->getOperand(i)));
588       AbbrevToUse = AggregateAbbrev;
589     } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
590       switch (CE->getOpcode()) {
591       default:
592         if (Instruction::isCast(CE->getOpcode())) {
593           Code = bitc::CST_CODE_CE_CAST;
594           Record.push_back(GetEncodedCastOpcode(CE->getOpcode()));
595           Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
596           Record.push_back(VE.getValueID(C->getOperand(0)));
597           AbbrevToUse = CONSTANTS_CE_CAST_Abbrev;
598         } else {
599           assert(CE->getNumOperands() == 2 && "Unknown constant expr!");
600           Code = bitc::CST_CODE_CE_BINOP;
601           Record.push_back(GetEncodedBinaryOpcode(CE->getOpcode()));
602           Record.push_back(VE.getValueID(C->getOperand(0)));
603           Record.push_back(VE.getValueID(C->getOperand(1)));
604         }
605         break;
606       case Instruction::GetElementPtr:
607         Code = bitc::CST_CODE_CE_GEP;
608         for (unsigned i = 0, e = CE->getNumOperands(); i != e; ++i) {
609           Record.push_back(VE.getTypeID(C->getOperand(i)->getType()));
610           Record.push_back(VE.getValueID(C->getOperand(i)));
611         }
612         break;
613       case Instruction::ExtractValue: {
614         Code = bitc::CST_CODE_CE_EXTRACTVAL;
615         Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
616         Record.push_back(VE.getValueID(C->getOperand(0)));
617         const SmallVector<unsigned, 4> &Indices = CE->getIndices();
618         for (unsigned i = 0, e = Indices.size(); i != e; ++i)
619           Record.push_back(Indices[i]);
620         break;
621       }
622       case Instruction::InsertValue: {
623         Code = bitc::CST_CODE_CE_INSERTVAL;
624         Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
625         Record.push_back(VE.getValueID(C->getOperand(0)));
626         Record.push_back(VE.getTypeID(C->getOperand(1)->getType()));
627         Record.push_back(VE.getValueID(C->getOperand(1)));
628         const SmallVector<unsigned, 4> &Indices = CE->getIndices();
629         for (unsigned i = 0, e = Indices.size(); i != e; ++i)
630           Record.push_back(Indices[i]);
631         break;
632       }
633       case Instruction::Select:
634         Code = bitc::CST_CODE_CE_SELECT;
635         Record.push_back(VE.getValueID(C->getOperand(0)));
636         Record.push_back(VE.getValueID(C->getOperand(1)));
637         Record.push_back(VE.getValueID(C->getOperand(2)));
638         break;
639       case Instruction::ExtractElement:
640         Code = bitc::CST_CODE_CE_EXTRACTELT;
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         break;
645       case Instruction::InsertElement:
646         Code = bitc::CST_CODE_CE_INSERTELT;
647         Record.push_back(VE.getValueID(C->getOperand(0)));
648         Record.push_back(VE.getValueID(C->getOperand(1)));
649         Record.push_back(VE.getValueID(C->getOperand(2)));
650         break;
651       case Instruction::ShuffleVector:
652         Code = bitc::CST_CODE_CE_SHUFFLEVEC;
653         Record.push_back(VE.getValueID(C->getOperand(0)));
654         Record.push_back(VE.getValueID(C->getOperand(1)));
655         Record.push_back(VE.getValueID(C->getOperand(2)));
656         break;
657       case Instruction::ICmp:
658       case Instruction::FCmp:
659       case Instruction::VICmp:
660       case Instruction::VFCmp:
661         Code = bitc::CST_CODE_CE_CMP;
662         Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
663         Record.push_back(VE.getValueID(C->getOperand(0)));
664         Record.push_back(VE.getValueID(C->getOperand(1)));
665         Record.push_back(CE->getPredicate());
666         break;
667       }
668     } else {
669       assert(0 && "Unknown constant!");
670     }
671     Stream.EmitRecord(Code, Record, AbbrevToUse);
672     Record.clear();
673   }
674
675   Stream.ExitBlock();
676 }
677
678 static void WriteModuleConstants(const ValueEnumerator &VE,
679                                  BitstreamWriter &Stream) {
680   const ValueEnumerator::ValueList &Vals = VE.getValues();
681   
682   // Find the first constant to emit, which is the first non-globalvalue value.
683   // We know globalvalues have been emitted by WriteModuleInfo.
684   for (unsigned i = 0, e = Vals.size(); i != e; ++i) {
685     if (!isa<GlobalValue>(Vals[i].first)) {
686       WriteConstants(i, Vals.size(), VE, Stream, true);
687       return;
688     }
689   }
690 }
691
692 /// PushValueAndType - The file has to encode both the value and type id for
693 /// many values, because we need to know what type to create for forward
694 /// references.  However, most operands are not forward references, so this type
695 /// field is not needed.
696 ///
697 /// This function adds V's value ID to Vals.  If the value ID is higher than the
698 /// instruction ID, then it is a forward reference, and it also includes the
699 /// type ID.
700 static bool PushValueAndType(Value *V, unsigned InstID,
701                              SmallVector<unsigned, 64> &Vals, 
702                              ValueEnumerator &VE) {
703   unsigned ValID = VE.getValueID(V);
704   Vals.push_back(ValID);
705   if (ValID >= InstID) {
706     Vals.push_back(VE.getTypeID(V->getType()));
707     return true;
708   }
709   return false;
710 }
711
712 /// WriteInstruction - Emit an instruction to the specified stream.
713 static void WriteInstruction(const Instruction &I, unsigned InstID,
714                              ValueEnumerator &VE, BitstreamWriter &Stream,
715                              SmallVector<unsigned, 64> &Vals) {
716   unsigned Code = 0;
717   unsigned AbbrevToUse = 0;
718   switch (I.getOpcode()) {
719   default:
720     if (Instruction::isCast(I.getOpcode())) {
721       Code = bitc::FUNC_CODE_INST_CAST;
722       if (!PushValueAndType(I.getOperand(0), InstID, Vals, VE))
723         AbbrevToUse = FUNCTION_INST_CAST_ABBREV;
724       Vals.push_back(VE.getTypeID(I.getType()));
725       Vals.push_back(GetEncodedCastOpcode(I.getOpcode()));
726     } else {
727       assert(isa<BinaryOperator>(I) && "Unknown instruction!");
728       Code = bitc::FUNC_CODE_INST_BINOP;
729       if (!PushValueAndType(I.getOperand(0), InstID, Vals, VE))
730         AbbrevToUse = FUNCTION_INST_BINOP_ABBREV;
731       Vals.push_back(VE.getValueID(I.getOperand(1)));
732       Vals.push_back(GetEncodedBinaryOpcode(I.getOpcode()));
733     }
734     break;
735
736   case Instruction::GetElementPtr:
737     Code = bitc::FUNC_CODE_INST_GEP;
738     for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
739       PushValueAndType(I.getOperand(i), InstID, Vals, VE);
740     break;
741   case Instruction::ExtractValue: {
742     Code = bitc::FUNC_CODE_INST_EXTRACTVAL;
743     PushValueAndType(I.getOperand(0), InstID, Vals, VE);
744     const ExtractValueInst *EVI = cast<ExtractValueInst>(&I);
745     for (const unsigned *i = EVI->idx_begin(), *e = EVI->idx_end(); i != e; ++i)
746       Vals.push_back(*i);
747     break;
748   }
749   case Instruction::InsertValue: {
750     Code = bitc::FUNC_CODE_INST_INSERTVAL;
751     PushValueAndType(I.getOperand(0), InstID, Vals, VE);
752     PushValueAndType(I.getOperand(1), InstID, Vals, VE);
753     const InsertValueInst *IVI = cast<InsertValueInst>(&I);
754     for (const unsigned *i = IVI->idx_begin(), *e = IVI->idx_end(); i != e; ++i)
755       Vals.push_back(*i);
756     break;
757   }
758   case Instruction::Select:
759     Code = bitc::FUNC_CODE_INST_SELECT;
760     PushValueAndType(I.getOperand(1), InstID, Vals, VE);
761     Vals.push_back(VE.getValueID(I.getOperand(2)));
762     Vals.push_back(VE.getValueID(I.getOperand(0)));
763     break;
764   case Instruction::ExtractElement:
765     Code = bitc::FUNC_CODE_INST_EXTRACTELT;
766     PushValueAndType(I.getOperand(0), InstID, Vals, VE);
767     Vals.push_back(VE.getValueID(I.getOperand(1)));
768     break;
769   case Instruction::InsertElement:
770     Code = bitc::FUNC_CODE_INST_INSERTELT;
771     PushValueAndType(I.getOperand(0), InstID, Vals, VE);
772     Vals.push_back(VE.getValueID(I.getOperand(1)));
773     Vals.push_back(VE.getValueID(I.getOperand(2)));
774     break;
775   case Instruction::ShuffleVector:
776     Code = bitc::FUNC_CODE_INST_SHUFFLEVEC;
777     PushValueAndType(I.getOperand(0), InstID, Vals, VE);
778     Vals.push_back(VE.getValueID(I.getOperand(1)));
779     Vals.push_back(VE.getValueID(I.getOperand(2)));
780     break;
781   case Instruction::ICmp:
782   case Instruction::FCmp:
783   case Instruction::VICmp:
784   case Instruction::VFCmp:
785     Code = bitc::FUNC_CODE_INST_CMP;
786     PushValueAndType(I.getOperand(0), InstID, Vals, VE);
787     Vals.push_back(VE.getValueID(I.getOperand(1)));
788     Vals.push_back(cast<CmpInst>(I).getPredicate());
789     break;
790   case Instruction::GetResult:
791     Code = bitc::FUNC_CODE_INST_GETRESULT;
792     PushValueAndType(I.getOperand(0), InstID, Vals, VE);
793     Vals.push_back(cast<GetResultInst>(I).getIndex());
794     break;
795
796   case Instruction::Ret: 
797     {
798       Code = bitc::FUNC_CODE_INST_RET;
799       unsigned NumOperands = I.getNumOperands();
800       if (NumOperands == 0)
801         AbbrevToUse = FUNCTION_INST_RET_VOID_ABBREV;
802       else if (NumOperands == 1) {
803         if (!PushValueAndType(I.getOperand(0), InstID, Vals, VE))
804           AbbrevToUse = FUNCTION_INST_RET_VAL_ABBREV;
805       } else {
806         for (unsigned i = 0, e = NumOperands; i != e; ++i)
807           PushValueAndType(I.getOperand(i), InstID, Vals, VE);
808       }
809     }
810     break;
811   case Instruction::Br:
812     Code = bitc::FUNC_CODE_INST_BR;
813     Vals.push_back(VE.getValueID(I.getOperand(0)));
814     if (cast<BranchInst>(I).isConditional()) {
815       Vals.push_back(VE.getValueID(I.getOperand(1)));
816       Vals.push_back(VE.getValueID(I.getOperand(2)));
817     }
818     break;
819   case Instruction::Switch:
820     Code = bitc::FUNC_CODE_INST_SWITCH;
821     Vals.push_back(VE.getTypeID(I.getOperand(0)->getType()));
822     for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
823       Vals.push_back(VE.getValueID(I.getOperand(i)));
824     break;
825   case Instruction::Invoke: {
826     const PointerType *PTy = cast<PointerType>(I.getOperand(0)->getType());
827     const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
828     Code = bitc::FUNC_CODE_INST_INVOKE;
829     
830     const InvokeInst *II = cast<InvokeInst>(&I);
831     Vals.push_back(VE.getParamAttrID(II->getParamAttrs()));
832     Vals.push_back(II->getCallingConv());
833     Vals.push_back(VE.getValueID(I.getOperand(1)));      // normal dest
834     Vals.push_back(VE.getValueID(I.getOperand(2)));      // unwind dest
835     PushValueAndType(I.getOperand(0), InstID, Vals, VE); // callee
836     
837     // Emit value #'s for the fixed parameters.
838     for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
839       Vals.push_back(VE.getValueID(I.getOperand(i+3)));  // fixed param.
840
841     // Emit type/value pairs for varargs params.
842     if (FTy->isVarArg()) {
843       for (unsigned i = 3+FTy->getNumParams(), e = I.getNumOperands();
844            i != e; ++i)
845         PushValueAndType(I.getOperand(i), InstID, Vals, VE); // vararg
846     }
847     break;
848   }
849   case Instruction::Unwind:
850     Code = bitc::FUNC_CODE_INST_UNWIND;
851     break;
852   case Instruction::Unreachable:
853     Code = bitc::FUNC_CODE_INST_UNREACHABLE;
854     AbbrevToUse = FUNCTION_INST_UNREACHABLE_ABBREV;
855     break;
856   
857   case Instruction::PHI:
858     Code = bitc::FUNC_CODE_INST_PHI;
859     Vals.push_back(VE.getTypeID(I.getType()));
860     for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
861       Vals.push_back(VE.getValueID(I.getOperand(i)));
862     break;
863     
864   case Instruction::Malloc:
865     Code = bitc::FUNC_CODE_INST_MALLOC;
866     Vals.push_back(VE.getTypeID(I.getType()));
867     Vals.push_back(VE.getValueID(I.getOperand(0))); // size.
868     Vals.push_back(Log2_32(cast<MallocInst>(I).getAlignment())+1);
869     break;
870     
871   case Instruction::Free:
872     Code = bitc::FUNC_CODE_INST_FREE;
873     PushValueAndType(I.getOperand(0), InstID, Vals, VE);
874     break;
875     
876   case Instruction::Alloca:
877     Code = bitc::FUNC_CODE_INST_ALLOCA;
878     Vals.push_back(VE.getTypeID(I.getType()));
879     Vals.push_back(VE.getValueID(I.getOperand(0))); // size.
880     Vals.push_back(Log2_32(cast<AllocaInst>(I).getAlignment())+1);
881     break;
882     
883   case Instruction::Load:
884     Code = bitc::FUNC_CODE_INST_LOAD;
885     if (!PushValueAndType(I.getOperand(0), InstID, Vals, VE))  // ptr
886       AbbrevToUse = FUNCTION_INST_LOAD_ABBREV;
887       
888     Vals.push_back(Log2_32(cast<LoadInst>(I).getAlignment())+1);
889     Vals.push_back(cast<LoadInst>(I).isVolatile());
890     break;
891   case Instruction::Store:
892     Code = bitc::FUNC_CODE_INST_STORE2;
893     PushValueAndType(I.getOperand(1), InstID, Vals, VE);  // ptrty + ptr
894     Vals.push_back(VE.getValueID(I.getOperand(0)));       // val.
895     Vals.push_back(Log2_32(cast<StoreInst>(I).getAlignment())+1);
896     Vals.push_back(cast<StoreInst>(I).isVolatile());
897     break;
898   case Instruction::Call: {
899     const PointerType *PTy = cast<PointerType>(I.getOperand(0)->getType());
900     const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
901
902     Code = bitc::FUNC_CODE_INST_CALL;
903     
904     const CallInst *CI = cast<CallInst>(&I);
905     Vals.push_back(VE.getParamAttrID(CI->getParamAttrs()));
906     Vals.push_back((CI->getCallingConv() << 1) | unsigned(CI->isTailCall()));
907     PushValueAndType(CI->getOperand(0), InstID, Vals, VE);  // Callee
908     
909     // Emit value #'s for the fixed parameters.
910     for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
911       Vals.push_back(VE.getValueID(I.getOperand(i+1)));  // fixed param.
912       
913     // Emit type/value pairs for varargs params.
914     if (FTy->isVarArg()) {
915       unsigned NumVarargs = I.getNumOperands()-1-FTy->getNumParams();
916       for (unsigned i = I.getNumOperands()-NumVarargs, e = I.getNumOperands();
917            i != e; ++i)
918         PushValueAndType(I.getOperand(i), InstID, Vals, VE);  // varargs
919     }
920     break;
921   }
922   case Instruction::VAArg:
923     Code = bitc::FUNC_CODE_INST_VAARG;
924     Vals.push_back(VE.getTypeID(I.getOperand(0)->getType()));   // valistty
925     Vals.push_back(VE.getValueID(I.getOperand(0))); // valist.
926     Vals.push_back(VE.getTypeID(I.getType())); // restype.
927     break;
928   }
929   
930   Stream.EmitRecord(Code, Vals, AbbrevToUse);
931   Vals.clear();
932 }
933
934 // Emit names for globals/functions etc.
935 static void WriteValueSymbolTable(const ValueSymbolTable &VST,
936                                   const ValueEnumerator &VE,
937                                   BitstreamWriter &Stream) {
938   if (VST.empty()) return;
939   Stream.EnterSubblock(bitc::VALUE_SYMTAB_BLOCK_ID, 4);
940
941   // FIXME: Set up the abbrev, we know how many values there are!
942   // FIXME: We know if the type names can use 7-bit ascii.
943   SmallVector<unsigned, 64> NameVals;
944   
945   for (ValueSymbolTable::const_iterator SI = VST.begin(), SE = VST.end();
946        SI != SE; ++SI) {
947     
948     const ValueName &Name = *SI;
949     
950     // Figure out the encoding to use for the name.
951     bool is7Bit = true;
952     bool isChar6 = true;
953     for (const char *C = Name.getKeyData(), *E = C+Name.getKeyLength();
954          C != E; ++C) {
955       if (isChar6) 
956         isChar6 = BitCodeAbbrevOp::isChar6(*C);
957       if ((unsigned char)*C & 128) {
958         is7Bit = false;
959         break;  // don't bother scanning the rest.
960       }
961     }
962     
963     unsigned AbbrevToUse = VST_ENTRY_8_ABBREV;
964     
965     // VST_ENTRY:   [valueid, namechar x N]
966     // VST_BBENTRY: [bbid, namechar x N]
967     unsigned Code;
968     if (isa<BasicBlock>(SI->getValue())) {
969       Code = bitc::VST_CODE_BBENTRY;
970       if (isChar6)
971         AbbrevToUse = VST_BBENTRY_6_ABBREV;
972     } else {
973       Code = bitc::VST_CODE_ENTRY;
974       if (isChar6)
975         AbbrevToUse = VST_ENTRY_6_ABBREV;
976       else if (is7Bit)
977         AbbrevToUse = VST_ENTRY_7_ABBREV;
978     }
979     
980     NameVals.push_back(VE.getValueID(SI->getValue()));
981     for (const char *P = Name.getKeyData(),
982          *E = Name.getKeyData()+Name.getKeyLength(); P != E; ++P)
983       NameVals.push_back((unsigned char)*P);
984     
985     // Emit the finished record.
986     Stream.EmitRecord(Code, NameVals, AbbrevToUse);
987     NameVals.clear();
988   }
989   Stream.ExitBlock();
990 }
991
992 /// WriteFunction - Emit a function body to the module stream.
993 static void WriteFunction(const Function &F, ValueEnumerator &VE, 
994                           BitstreamWriter &Stream) {
995   Stream.EnterSubblock(bitc::FUNCTION_BLOCK_ID, 4);
996   VE.incorporateFunction(F);
997
998   SmallVector<unsigned, 64> Vals;
999   
1000   // Emit the number of basic blocks, so the reader can create them ahead of
1001   // time.
1002   Vals.push_back(VE.getBasicBlocks().size());
1003   Stream.EmitRecord(bitc::FUNC_CODE_DECLAREBLOCKS, Vals);
1004   Vals.clear();
1005   
1006   // If there are function-local constants, emit them now.
1007   unsigned CstStart, CstEnd;
1008   VE.getFunctionConstantRange(CstStart, CstEnd);
1009   WriteConstants(CstStart, CstEnd, VE, Stream, false);
1010   
1011   // Keep a running idea of what the instruction ID is. 
1012   unsigned InstID = CstEnd;
1013   
1014   // Finally, emit all the instructions, in order.
1015   for (Function::const_iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
1016     for (BasicBlock::const_iterator I = BB->begin(), E = BB->end();
1017          I != E; ++I) {
1018       WriteInstruction(*I, InstID, VE, Stream, Vals);
1019       if (I->getType() != Type::VoidTy)
1020         ++InstID;
1021     }
1022   
1023   // Emit names for all the instructions etc.
1024   WriteValueSymbolTable(F.getValueSymbolTable(), VE, Stream);
1025     
1026   VE.purgeFunction();
1027   Stream.ExitBlock();
1028 }
1029
1030 /// WriteTypeSymbolTable - Emit a block for the specified type symtab.
1031 static void WriteTypeSymbolTable(const TypeSymbolTable &TST,
1032                                  const ValueEnumerator &VE,
1033                                  BitstreamWriter &Stream) {
1034   if (TST.empty()) return;
1035   
1036   Stream.EnterSubblock(bitc::TYPE_SYMTAB_BLOCK_ID, 3);
1037   
1038   // 7-bit fixed width VST_CODE_ENTRY strings.
1039   BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1040   Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_ENTRY));
1041   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
1042                             Log2_32_Ceil(VE.getTypes().size()+1)));
1043   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1044   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7));
1045   unsigned V7Abbrev = Stream.EmitAbbrev(Abbv);
1046   
1047   SmallVector<unsigned, 64> NameVals;
1048   
1049   for (TypeSymbolTable::const_iterator TI = TST.begin(), TE = TST.end(); 
1050        TI != TE; ++TI) {
1051     // TST_ENTRY: [typeid, namechar x N]
1052     NameVals.push_back(VE.getTypeID(TI->second));
1053     
1054     const std::string &Str = TI->first;
1055     bool is7Bit = true;
1056     for (unsigned i = 0, e = Str.size(); i != e; ++i) {
1057       NameVals.push_back((unsigned char)Str[i]);
1058       if (Str[i] & 128)
1059         is7Bit = false;
1060     }
1061     
1062     // Emit the finished record.
1063     Stream.EmitRecord(bitc::VST_CODE_ENTRY, NameVals, is7Bit ? V7Abbrev : 0);
1064     NameVals.clear();
1065   }
1066   
1067   Stream.ExitBlock();
1068 }
1069
1070 // Emit blockinfo, which defines the standard abbreviations etc.
1071 static void WriteBlockInfo(const ValueEnumerator &VE, BitstreamWriter &Stream) {
1072   // We only want to emit block info records for blocks that have multiple
1073   // instances: CONSTANTS_BLOCK, FUNCTION_BLOCK and VALUE_SYMTAB_BLOCK.  Other
1074   // blocks can defined their abbrevs inline.
1075   Stream.EnterBlockInfoBlock(2);
1076   
1077   { // 8-bit fixed-width VST_ENTRY/VST_BBENTRY strings.
1078     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1079     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 3));
1080     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
1081     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1082     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
1083     if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID, 
1084                                    Abbv) != VST_ENTRY_8_ABBREV)
1085       assert(0 && "Unexpected abbrev ordering!");
1086   }
1087   
1088   { // 7-bit fixed width VST_ENTRY strings.
1089     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1090     Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_ENTRY));
1091     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
1092     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1093     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7));
1094     if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID,
1095                                    Abbv) != VST_ENTRY_7_ABBREV)
1096       assert(0 && "Unexpected abbrev ordering!");
1097   }
1098   { // 6-bit char6 VST_ENTRY strings.
1099     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1100     Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_ENTRY));
1101     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
1102     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1103     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
1104     if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID,
1105                                    Abbv) != VST_ENTRY_6_ABBREV)
1106       assert(0 && "Unexpected abbrev ordering!");
1107   }
1108   { // 6-bit char6 VST_BBENTRY strings.
1109     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1110     Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_BBENTRY));
1111     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
1112     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1113     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
1114     if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID,
1115                                    Abbv) != VST_BBENTRY_6_ABBREV)
1116       assert(0 && "Unexpected abbrev ordering!");
1117   }
1118   
1119   
1120   
1121   { // SETTYPE abbrev for CONSTANTS_BLOCK.
1122     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1123     Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_SETTYPE));
1124     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
1125                               Log2_32_Ceil(VE.getTypes().size()+1)));
1126     if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID,
1127                                    Abbv) != CONSTANTS_SETTYPE_ABBREV)
1128       assert(0 && "Unexpected abbrev ordering!");
1129   }
1130   
1131   { // INTEGER abbrev for CONSTANTS_BLOCK.
1132     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1133     Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_INTEGER));
1134     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
1135     if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID,
1136                                    Abbv) != CONSTANTS_INTEGER_ABBREV)
1137       assert(0 && "Unexpected abbrev ordering!");
1138   }
1139   
1140   { // CE_CAST abbrev for CONSTANTS_BLOCK.
1141     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1142     Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_CE_CAST));
1143     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4));  // cast opc
1144     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,       // typeid
1145                               Log2_32_Ceil(VE.getTypes().size()+1)));
1146     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));    // value id
1147
1148     if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID,
1149                                    Abbv) != CONSTANTS_CE_CAST_Abbrev)
1150       assert(0 && "Unexpected abbrev ordering!");
1151   }
1152   { // NULL abbrev for CONSTANTS_BLOCK.
1153     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1154     Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_NULL));
1155     if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID,
1156                                    Abbv) != CONSTANTS_NULL_Abbrev)
1157       assert(0 && "Unexpected abbrev ordering!");
1158   }
1159   
1160   // FIXME: This should only use space for first class types!
1161  
1162   { // INST_LOAD abbrev for FUNCTION_BLOCK.
1163     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1164     Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_LOAD));
1165     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Ptr
1166     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // Align
1167     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // volatile
1168     if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
1169                                    Abbv) != FUNCTION_INST_LOAD_ABBREV)
1170       assert(0 && "Unexpected abbrev ordering!");
1171   }
1172   { // INST_BINOP abbrev for FUNCTION_BLOCK.
1173     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1174     Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_BINOP));
1175     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // LHS
1176     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // RHS
1177     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
1178     if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
1179                                    Abbv) != FUNCTION_INST_BINOP_ABBREV)
1180       assert(0 && "Unexpected abbrev ordering!");
1181   }
1182   { // INST_CAST abbrev for FUNCTION_BLOCK.
1183     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1184     Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_CAST));
1185     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));    // OpVal
1186     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,       // dest ty
1187                               Log2_32_Ceil(VE.getTypes().size()+1)));
1188     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4));  // opc
1189     if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
1190                                    Abbv) != FUNCTION_INST_CAST_ABBREV)
1191       assert(0 && "Unexpected abbrev ordering!");
1192   }
1193   
1194   { // INST_RET abbrev for FUNCTION_BLOCK.
1195     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1196     Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_RET));
1197     if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
1198                                    Abbv) != FUNCTION_INST_RET_VOID_ABBREV)
1199       assert(0 && "Unexpected abbrev ordering!");
1200   }
1201   { // INST_RET abbrev for FUNCTION_BLOCK.
1202     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1203     Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_RET));
1204     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // ValID
1205     if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
1206                                    Abbv) != FUNCTION_INST_RET_VAL_ABBREV)
1207       assert(0 && "Unexpected abbrev ordering!");
1208   }
1209   { // INST_UNREACHABLE abbrev for FUNCTION_BLOCK.
1210     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1211     Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_UNREACHABLE));
1212     if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
1213                                    Abbv) != FUNCTION_INST_UNREACHABLE_ABBREV)
1214       assert(0 && "Unexpected abbrev ordering!");
1215   }
1216   
1217   Stream.ExitBlock();
1218 }
1219
1220
1221 /// WriteModule - Emit the specified module to the bitstream.
1222 static void WriteModule(const Module *M, BitstreamWriter &Stream) {
1223   Stream.EnterSubblock(bitc::MODULE_BLOCK_ID, 3);
1224   
1225   // Emit the version number if it is non-zero.
1226   if (CurVersion) {
1227     SmallVector<unsigned, 1> Vals;
1228     Vals.push_back(CurVersion);
1229     Stream.EmitRecord(bitc::MODULE_CODE_VERSION, Vals);
1230   }
1231   
1232   // Analyze the module, enumerating globals, functions, etc.
1233   ValueEnumerator VE(M);
1234
1235   // Emit blockinfo, which defines the standard abbreviations etc.
1236   WriteBlockInfo(VE, Stream);
1237   
1238   // Emit information about parameter attributes.
1239   WriteParamAttrTable(VE, Stream);
1240   
1241   // Emit information describing all of the types in the module.
1242   WriteTypeTable(VE, Stream);
1243   
1244   // Emit top-level description of module, including target triple, inline asm,
1245   // descriptors for global variables, and function prototype info.
1246   WriteModuleInfo(M, VE, Stream);
1247   
1248   // Emit constants.
1249   WriteModuleConstants(VE, Stream);
1250   
1251   // If we have any aggregate values in the value table, purge them - these can
1252   // only be used to initialize global variables.  Doing so makes the value
1253   // namespace smaller for code in functions.
1254   int NumNonAggregates = VE.PurgeAggregateValues();
1255   if (NumNonAggregates != -1) {
1256     SmallVector<unsigned, 1> Vals;
1257     Vals.push_back(NumNonAggregates);
1258     Stream.EmitRecord(bitc::MODULE_CODE_PURGEVALS, Vals);
1259   }
1260   
1261   // Emit function bodies.
1262   for (Module::const_iterator I = M->begin(), E = M->end(); I != E; ++I)
1263     if (!I->isDeclaration())
1264       WriteFunction(*I, VE, Stream);
1265   
1266   // Emit the type symbol table information.
1267   WriteTypeSymbolTable(M->getTypeSymbolTable(), VE, Stream);
1268   
1269   // Emit names for globals/functions etc.
1270   WriteValueSymbolTable(M->getValueSymbolTable(), VE, Stream);
1271   
1272   Stream.ExitBlock();
1273 }
1274
1275
1276 /// WriteBitcodeToFile - Write the specified module to the specified output
1277 /// stream.
1278 void llvm::WriteBitcodeToFile(const Module *M, std::ostream &Out) {
1279   std::vector<unsigned char> Buffer;
1280   BitstreamWriter Stream(Buffer);
1281   
1282   Buffer.reserve(256*1024);
1283   
1284   // Emit the file header.
1285   Stream.Emit((unsigned)'B', 8);
1286   Stream.Emit((unsigned)'C', 8);
1287   Stream.Emit(0x0, 4);
1288   Stream.Emit(0xC, 4);
1289   Stream.Emit(0xE, 4);
1290   Stream.Emit(0xD, 4);
1291
1292   // Emit the module.
1293   WriteModule(M, Stream);
1294   
1295   // Write the generated bitstream to "Out".
1296   Out.write((char*)&Buffer.front(), Buffer.size());
1297   
1298   // Make sure it hits disk now.
1299   Out.flush();
1300 }