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