Add a little wrapper header that is put around bc files when emitting
[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 collectors, computing how many there
307   // are.  Also compute the maximum alignment value.
308   std::map<std::string, unsigned> SectionMap;
309   std::map<std::string, unsigned> CollectorMap;
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->hasCollector()) {
337       // Same for collector names.
338       unsigned &Entry = CollectorMap[F->getCollector()];
339       if (!Entry) {
340         WriteStringRecord(bitc::MODULE_CODE_COLLECTORNAME, F->getCollector(),
341                           0/*TODO*/, Stream);
342         Entry = CollectorMap.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, collector]
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->hasCollector() ? CollectorMap[F->getCollector()] : 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::ExtractValue: {
615         Code = bitc::CST_CODE_CE_EXTRACTVAL;
616         Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
617         Record.push_back(VE.getValueID(C->getOperand(0)));
618         const SmallVector<unsigned, 4> &Indices = CE->getIndices();
619         for (unsigned i = 0, e = Indices.size(); i != e; ++i)
620           Record.push_back(Indices[i]);
621         break;
622       }
623       case Instruction::InsertValue: {
624         Code = bitc::CST_CODE_CE_INSERTVAL;
625         Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
626         Record.push_back(VE.getValueID(C->getOperand(0)));
627         Record.push_back(VE.getTypeID(C->getOperand(1)->getType()));
628         Record.push_back(VE.getValueID(C->getOperand(1)));
629         const SmallVector<unsigned, 4> &Indices = CE->getIndices();
630         for (unsigned i = 0, e = Indices.size(); i != e; ++i)
631           Record.push_back(Indices[i]);
632         break;
633       }
634       case Instruction::Select:
635         Code = bitc::CST_CODE_CE_SELECT;
636         Record.push_back(VE.getValueID(C->getOperand(0)));
637         Record.push_back(VE.getValueID(C->getOperand(1)));
638         Record.push_back(VE.getValueID(C->getOperand(2)));
639         break;
640       case Instruction::ExtractElement:
641         Code = bitc::CST_CODE_CE_EXTRACTELT;
642         Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
643         Record.push_back(VE.getValueID(C->getOperand(0)));
644         Record.push_back(VE.getValueID(C->getOperand(1)));
645         break;
646       case Instruction::InsertElement:
647         Code = bitc::CST_CODE_CE_INSERTELT;
648         Record.push_back(VE.getValueID(C->getOperand(0)));
649         Record.push_back(VE.getValueID(C->getOperand(1)));
650         Record.push_back(VE.getValueID(C->getOperand(2)));
651         break;
652       case Instruction::ShuffleVector:
653         Code = bitc::CST_CODE_CE_SHUFFLEVEC;
654         Record.push_back(VE.getValueID(C->getOperand(0)));
655         Record.push_back(VE.getValueID(C->getOperand(1)));
656         Record.push_back(VE.getValueID(C->getOperand(2)));
657         break;
658       case Instruction::ICmp:
659       case Instruction::FCmp:
660       case Instruction::VICmp:
661       case Instruction::VFCmp:
662         Code = bitc::CST_CODE_CE_CMP;
663         Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
664         Record.push_back(VE.getValueID(C->getOperand(0)));
665         Record.push_back(VE.getValueID(C->getOperand(1)));
666         Record.push_back(CE->getPredicate());
667         break;
668       }
669     } else {
670       assert(0 && "Unknown constant!");
671     }
672     Stream.EmitRecord(Code, Record, AbbrevToUse);
673     Record.clear();
674   }
675
676   Stream.ExitBlock();
677 }
678
679 static void WriteModuleConstants(const ValueEnumerator &VE,
680                                  BitstreamWriter &Stream) {
681   const ValueEnumerator::ValueList &Vals = VE.getValues();
682   
683   // Find the first constant to emit, which is the first non-globalvalue value.
684   // We know globalvalues have been emitted by WriteModuleInfo.
685   for (unsigned i = 0, e = Vals.size(); i != e; ++i) {
686     if (!isa<GlobalValue>(Vals[i].first)) {
687       WriteConstants(i, Vals.size(), VE, Stream, true);
688       return;
689     }
690   }
691 }
692
693 /// PushValueAndType - The file has to encode both the value and type id for
694 /// many values, because we need to know what type to create for forward
695 /// references.  However, most operands are not forward references, so this type
696 /// field is not needed.
697 ///
698 /// This function adds V's value ID to Vals.  If the value ID is higher than the
699 /// instruction ID, then it is a forward reference, and it also includes the
700 /// type ID.
701 static bool PushValueAndType(Value *V, unsigned InstID,
702                              SmallVector<unsigned, 64> &Vals, 
703                              ValueEnumerator &VE) {
704   unsigned ValID = VE.getValueID(V);
705   Vals.push_back(ValID);
706   if (ValID >= InstID) {
707     Vals.push_back(VE.getTypeID(V->getType()));
708     return true;
709   }
710   return false;
711 }
712
713 /// WriteInstruction - Emit an instruction to the specified stream.
714 static void WriteInstruction(const Instruction &I, unsigned InstID,
715                              ValueEnumerator &VE, BitstreamWriter &Stream,
716                              SmallVector<unsigned, 64> &Vals) {
717   unsigned Code = 0;
718   unsigned AbbrevToUse = 0;
719   switch (I.getOpcode()) {
720   default:
721     if (Instruction::isCast(I.getOpcode())) {
722       Code = bitc::FUNC_CODE_INST_CAST;
723       if (!PushValueAndType(I.getOperand(0), InstID, Vals, VE))
724         AbbrevToUse = FUNCTION_INST_CAST_ABBREV;
725       Vals.push_back(VE.getTypeID(I.getType()));
726       Vals.push_back(GetEncodedCastOpcode(I.getOpcode()));
727     } else {
728       assert(isa<BinaryOperator>(I) && "Unknown instruction!");
729       Code = bitc::FUNC_CODE_INST_BINOP;
730       if (!PushValueAndType(I.getOperand(0), InstID, Vals, VE))
731         AbbrevToUse = FUNCTION_INST_BINOP_ABBREV;
732       Vals.push_back(VE.getValueID(I.getOperand(1)));
733       Vals.push_back(GetEncodedBinaryOpcode(I.getOpcode()));
734     }
735     break;
736
737   case Instruction::GetElementPtr:
738     Code = bitc::FUNC_CODE_INST_GEP;
739     for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
740       PushValueAndType(I.getOperand(i), InstID, Vals, VE);
741     break;
742   case Instruction::ExtractValue: {
743     Code = bitc::FUNC_CODE_INST_EXTRACTVAL;
744     PushValueAndType(I.getOperand(0), InstID, Vals, VE);
745     const ExtractValueInst *EVI = cast<ExtractValueInst>(&I);
746     for (const unsigned *i = EVI->idx_begin(), *e = EVI->idx_end(); i != e; ++i)
747       Vals.push_back(*i);
748     break;
749   }
750   case Instruction::InsertValue: {
751     Code = bitc::FUNC_CODE_INST_INSERTVAL;
752     PushValueAndType(I.getOperand(0), InstID, Vals, VE);
753     PushValueAndType(I.getOperand(1), InstID, Vals, VE);
754     const InsertValueInst *IVI = cast<InsertValueInst>(&I);
755     for (const unsigned *i = IVI->idx_begin(), *e = IVI->idx_end(); i != e; ++i)
756       Vals.push_back(*i);
757     break;
758   }
759   case Instruction::Select:
760     Code = bitc::FUNC_CODE_INST_SELECT;
761     PushValueAndType(I.getOperand(1), InstID, Vals, VE);
762     Vals.push_back(VE.getValueID(I.getOperand(2)));
763     Vals.push_back(VE.getValueID(I.getOperand(0)));
764     break;
765   case Instruction::ExtractElement:
766     Code = bitc::FUNC_CODE_INST_EXTRACTELT;
767     PushValueAndType(I.getOperand(0), InstID, Vals, VE);
768     Vals.push_back(VE.getValueID(I.getOperand(1)));
769     break;
770   case Instruction::InsertElement:
771     Code = bitc::FUNC_CODE_INST_INSERTELT;
772     PushValueAndType(I.getOperand(0), InstID, Vals, VE);
773     Vals.push_back(VE.getValueID(I.getOperand(1)));
774     Vals.push_back(VE.getValueID(I.getOperand(2)));
775     break;
776   case Instruction::ShuffleVector:
777     Code = bitc::FUNC_CODE_INST_SHUFFLEVEC;
778     PushValueAndType(I.getOperand(0), InstID, Vals, VE);
779     Vals.push_back(VE.getValueID(I.getOperand(1)));
780     Vals.push_back(VE.getValueID(I.getOperand(2)));
781     break;
782   case Instruction::ICmp:
783   case Instruction::FCmp:
784   case Instruction::VICmp:
785   case Instruction::VFCmp:
786     Code = bitc::FUNC_CODE_INST_CMP;
787     PushValueAndType(I.getOperand(0), InstID, Vals, VE);
788     Vals.push_back(VE.getValueID(I.getOperand(1)));
789     Vals.push_back(cast<CmpInst>(I).getPredicate());
790     break;
791   case Instruction::GetResult:
792     Code = bitc::FUNC_CODE_INST_GETRESULT;
793     PushValueAndType(I.getOperand(0), InstID, Vals, VE);
794     Vals.push_back(cast<GetResultInst>(I).getIndex());
795     break;
796
797   case Instruction::Ret: 
798     {
799       Code = bitc::FUNC_CODE_INST_RET;
800       unsigned NumOperands = I.getNumOperands();
801       if (NumOperands == 0)
802         AbbrevToUse = FUNCTION_INST_RET_VOID_ABBREV;
803       else if (NumOperands == 1) {
804         if (!PushValueAndType(I.getOperand(0), InstID, Vals, VE))
805           AbbrevToUse = FUNCTION_INST_RET_VAL_ABBREV;
806       } else {
807         for (unsigned i = 0, e = NumOperands; i != e; ++i)
808           PushValueAndType(I.getOperand(i), InstID, Vals, VE);
809       }
810     }
811     break;
812   case Instruction::Br:
813     Code = bitc::FUNC_CODE_INST_BR;
814     Vals.push_back(VE.getValueID(I.getOperand(0)));
815     if (cast<BranchInst>(I).isConditional()) {
816       Vals.push_back(VE.getValueID(I.getOperand(1)));
817       Vals.push_back(VE.getValueID(I.getOperand(2)));
818     }
819     break;
820   case Instruction::Switch:
821     Code = bitc::FUNC_CODE_INST_SWITCH;
822     Vals.push_back(VE.getTypeID(I.getOperand(0)->getType()));
823     for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
824       Vals.push_back(VE.getValueID(I.getOperand(i)));
825     break;
826   case Instruction::Invoke: {
827     const PointerType *PTy = cast<PointerType>(I.getOperand(0)->getType());
828     const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
829     Code = bitc::FUNC_CODE_INST_INVOKE;
830     
831     const InvokeInst *II = cast<InvokeInst>(&I);
832     Vals.push_back(VE.getParamAttrID(II->getParamAttrs()));
833     Vals.push_back(II->getCallingConv());
834     Vals.push_back(VE.getValueID(I.getOperand(1)));      // normal dest
835     Vals.push_back(VE.getValueID(I.getOperand(2)));      // unwind dest
836     PushValueAndType(I.getOperand(0), InstID, Vals, VE); // callee
837     
838     // Emit value #'s for the fixed parameters.
839     for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
840       Vals.push_back(VE.getValueID(I.getOperand(i+3)));  // fixed param.
841
842     // Emit type/value pairs for varargs params.
843     if (FTy->isVarArg()) {
844       for (unsigned i = 3+FTy->getNumParams(), e = I.getNumOperands();
845            i != e; ++i)
846         PushValueAndType(I.getOperand(i), InstID, Vals, VE); // vararg
847     }
848     break;
849   }
850   case Instruction::Unwind:
851     Code = bitc::FUNC_CODE_INST_UNWIND;
852     break;
853   case Instruction::Unreachable:
854     Code = bitc::FUNC_CODE_INST_UNREACHABLE;
855     AbbrevToUse = FUNCTION_INST_UNREACHABLE_ABBREV;
856     break;
857   
858   case Instruction::PHI:
859     Code = bitc::FUNC_CODE_INST_PHI;
860     Vals.push_back(VE.getTypeID(I.getType()));
861     for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
862       Vals.push_back(VE.getValueID(I.getOperand(i)));
863     break;
864     
865   case Instruction::Malloc:
866     Code = bitc::FUNC_CODE_INST_MALLOC;
867     Vals.push_back(VE.getTypeID(I.getType()));
868     Vals.push_back(VE.getValueID(I.getOperand(0))); // size.
869     Vals.push_back(Log2_32(cast<MallocInst>(I).getAlignment())+1);
870     break;
871     
872   case Instruction::Free:
873     Code = bitc::FUNC_CODE_INST_FREE;
874     PushValueAndType(I.getOperand(0), InstID, Vals, VE);
875     break;
876     
877   case Instruction::Alloca:
878     Code = bitc::FUNC_CODE_INST_ALLOCA;
879     Vals.push_back(VE.getTypeID(I.getType()));
880     Vals.push_back(VE.getValueID(I.getOperand(0))); // size.
881     Vals.push_back(Log2_32(cast<AllocaInst>(I).getAlignment())+1);
882     break;
883     
884   case Instruction::Load:
885     Code = bitc::FUNC_CODE_INST_LOAD;
886     if (!PushValueAndType(I.getOperand(0), InstID, Vals, VE))  // ptr
887       AbbrevToUse = FUNCTION_INST_LOAD_ABBREV;
888       
889     Vals.push_back(Log2_32(cast<LoadInst>(I).getAlignment())+1);
890     Vals.push_back(cast<LoadInst>(I).isVolatile());
891     break;
892   case Instruction::Store:
893     Code = bitc::FUNC_CODE_INST_STORE2;
894     PushValueAndType(I.getOperand(1), InstID, Vals, VE);  // ptrty + ptr
895     Vals.push_back(VE.getValueID(I.getOperand(0)));       // val.
896     Vals.push_back(Log2_32(cast<StoreInst>(I).getAlignment())+1);
897     Vals.push_back(cast<StoreInst>(I).isVolatile());
898     break;
899   case Instruction::Call: {
900     const PointerType *PTy = cast<PointerType>(I.getOperand(0)->getType());
901     const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
902
903     Code = bitc::FUNC_CODE_INST_CALL;
904     
905     const CallInst *CI = cast<CallInst>(&I);
906     Vals.push_back(VE.getParamAttrID(CI->getParamAttrs()));
907     Vals.push_back((CI->getCallingConv() << 1) | unsigned(CI->isTailCall()));
908     PushValueAndType(CI->getOperand(0), InstID, Vals, VE);  // Callee
909     
910     // Emit value #'s for the fixed parameters.
911     for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
912       Vals.push_back(VE.getValueID(I.getOperand(i+1)));  // fixed param.
913       
914     // Emit type/value pairs for varargs params.
915     if (FTy->isVarArg()) {
916       unsigned NumVarargs = I.getNumOperands()-1-FTy->getNumParams();
917       for (unsigned i = I.getNumOperands()-NumVarargs, e = I.getNumOperands();
918            i != e; ++i)
919         PushValueAndType(I.getOperand(i), InstID, Vals, VE);  // varargs
920     }
921     break;
922   }
923   case Instruction::VAArg:
924     Code = bitc::FUNC_CODE_INST_VAARG;
925     Vals.push_back(VE.getTypeID(I.getOperand(0)->getType()));   // valistty
926     Vals.push_back(VE.getValueID(I.getOperand(0))); // valist.
927     Vals.push_back(VE.getTypeID(I.getType())); // restype.
928     break;
929   }
930   
931   Stream.EmitRecord(Code, Vals, AbbrevToUse);
932   Vals.clear();
933 }
934
935 // Emit names for globals/functions etc.
936 static void WriteValueSymbolTable(const ValueSymbolTable &VST,
937                                   const ValueEnumerator &VE,
938                                   BitstreamWriter &Stream) {
939   if (VST.empty()) return;
940   Stream.EnterSubblock(bitc::VALUE_SYMTAB_BLOCK_ID, 4);
941
942   // FIXME: Set up the abbrev, we know how many values there are!
943   // FIXME: We know if the type names can use 7-bit ascii.
944   SmallVector<unsigned, 64> NameVals;
945   
946   for (ValueSymbolTable::const_iterator SI = VST.begin(), SE = VST.end();
947        SI != SE; ++SI) {
948     
949     const ValueName &Name = *SI;
950     
951     // Figure out the encoding to use for the name.
952     bool is7Bit = true;
953     bool isChar6 = true;
954     for (const char *C = Name.getKeyData(), *E = C+Name.getKeyLength();
955          C != E; ++C) {
956       if (isChar6) 
957         isChar6 = BitCodeAbbrevOp::isChar6(*C);
958       if ((unsigned char)*C & 128) {
959         is7Bit = false;
960         break;  // don't bother scanning the rest.
961       }
962     }
963     
964     unsigned AbbrevToUse = VST_ENTRY_8_ABBREV;
965     
966     // VST_ENTRY:   [valueid, namechar x N]
967     // VST_BBENTRY: [bbid, namechar x N]
968     unsigned Code;
969     if (isa<BasicBlock>(SI->getValue())) {
970       Code = bitc::VST_CODE_BBENTRY;
971       if (isChar6)
972         AbbrevToUse = VST_BBENTRY_6_ABBREV;
973     } else {
974       Code = bitc::VST_CODE_ENTRY;
975       if (isChar6)
976         AbbrevToUse = VST_ENTRY_6_ABBREV;
977       else if (is7Bit)
978         AbbrevToUse = VST_ENTRY_7_ABBREV;
979     }
980     
981     NameVals.push_back(VE.getValueID(SI->getValue()));
982     for (const char *P = Name.getKeyData(),
983          *E = Name.getKeyData()+Name.getKeyLength(); P != E; ++P)
984       NameVals.push_back((unsigned char)*P);
985     
986     // Emit the finished record.
987     Stream.EmitRecord(Code, NameVals, AbbrevToUse);
988     NameVals.clear();
989   }
990   Stream.ExitBlock();
991 }
992
993 /// WriteFunction - Emit a function body to the module stream.
994 static void WriteFunction(const Function &F, ValueEnumerator &VE, 
995                           BitstreamWriter &Stream) {
996   Stream.EnterSubblock(bitc::FUNCTION_BLOCK_ID, 4);
997   VE.incorporateFunction(F);
998
999   SmallVector<unsigned, 64> Vals;
1000   
1001   // Emit the number of basic blocks, so the reader can create them ahead of
1002   // time.
1003   Vals.push_back(VE.getBasicBlocks().size());
1004   Stream.EmitRecord(bitc::FUNC_CODE_DECLAREBLOCKS, Vals);
1005   Vals.clear();
1006   
1007   // If there are function-local constants, emit them now.
1008   unsigned CstStart, CstEnd;
1009   VE.getFunctionConstantRange(CstStart, CstEnd);
1010   WriteConstants(CstStart, CstEnd, VE, Stream, false);
1011   
1012   // Keep a running idea of what the instruction ID is. 
1013   unsigned InstID = CstEnd;
1014   
1015   // Finally, emit all the instructions, in order.
1016   for (Function::const_iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
1017     for (BasicBlock::const_iterator I = BB->begin(), E = BB->end();
1018          I != E; ++I) {
1019       WriteInstruction(*I, InstID, VE, Stream, Vals);
1020       if (I->getType() != Type::VoidTy)
1021         ++InstID;
1022     }
1023   
1024   // Emit names for all the instructions etc.
1025   WriteValueSymbolTable(F.getValueSymbolTable(), VE, Stream);
1026     
1027   VE.purgeFunction();
1028   Stream.ExitBlock();
1029 }
1030
1031 /// WriteTypeSymbolTable - Emit a block for the specified type symtab.
1032 static void WriteTypeSymbolTable(const TypeSymbolTable &TST,
1033                                  const ValueEnumerator &VE,
1034                                  BitstreamWriter &Stream) {
1035   if (TST.empty()) return;
1036   
1037   Stream.EnterSubblock(bitc::TYPE_SYMTAB_BLOCK_ID, 3);
1038   
1039   // 7-bit fixed width VST_CODE_ENTRY strings.
1040   BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1041   Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_ENTRY));
1042   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
1043                             Log2_32_Ceil(VE.getTypes().size()+1)));
1044   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1045   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7));
1046   unsigned V7Abbrev = Stream.EmitAbbrev(Abbv);
1047   
1048   SmallVector<unsigned, 64> NameVals;
1049   
1050   for (TypeSymbolTable::const_iterator TI = TST.begin(), TE = TST.end(); 
1051        TI != TE; ++TI) {
1052     // TST_ENTRY: [typeid, namechar x N]
1053     NameVals.push_back(VE.getTypeID(TI->second));
1054     
1055     const std::string &Str = TI->first;
1056     bool is7Bit = true;
1057     for (unsigned i = 0, e = Str.size(); i != e; ++i) {
1058       NameVals.push_back((unsigned char)Str[i]);
1059       if (Str[i] & 128)
1060         is7Bit = false;
1061     }
1062     
1063     // Emit the finished record.
1064     Stream.EmitRecord(bitc::VST_CODE_ENTRY, NameVals, is7Bit ? V7Abbrev : 0);
1065     NameVals.clear();
1066   }
1067   
1068   Stream.ExitBlock();
1069 }
1070
1071 // Emit blockinfo, which defines the standard abbreviations etc.
1072 static void WriteBlockInfo(const ValueEnumerator &VE, BitstreamWriter &Stream) {
1073   // We only want to emit block info records for blocks that have multiple
1074   // instances: CONSTANTS_BLOCK, FUNCTION_BLOCK and VALUE_SYMTAB_BLOCK.  Other
1075   // blocks can defined their abbrevs inline.
1076   Stream.EnterBlockInfoBlock(2);
1077   
1078   { // 8-bit fixed-width VST_ENTRY/VST_BBENTRY strings.
1079     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1080     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 3));
1081     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
1082     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1083     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
1084     if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID, 
1085                                    Abbv) != VST_ENTRY_8_ABBREV)
1086       assert(0 && "Unexpected abbrev ordering!");
1087   }
1088   
1089   { // 7-bit fixed width VST_ENTRY strings.
1090     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1091     Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_ENTRY));
1092     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
1093     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1094     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7));
1095     if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID,
1096                                    Abbv) != VST_ENTRY_7_ABBREV)
1097       assert(0 && "Unexpected abbrev ordering!");
1098   }
1099   { // 6-bit char6 VST_ENTRY strings.
1100     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1101     Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_ENTRY));
1102     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
1103     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1104     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
1105     if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID,
1106                                    Abbv) != VST_ENTRY_6_ABBREV)
1107       assert(0 && "Unexpected abbrev ordering!");
1108   }
1109   { // 6-bit char6 VST_BBENTRY strings.
1110     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1111     Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_BBENTRY));
1112     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
1113     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1114     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
1115     if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID,
1116                                    Abbv) != VST_BBENTRY_6_ABBREV)
1117       assert(0 && "Unexpected abbrev ordering!");
1118   }
1119   
1120   
1121   
1122   { // SETTYPE abbrev for CONSTANTS_BLOCK.
1123     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1124     Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_SETTYPE));
1125     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
1126                               Log2_32_Ceil(VE.getTypes().size()+1)));
1127     if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID,
1128                                    Abbv) != CONSTANTS_SETTYPE_ABBREV)
1129       assert(0 && "Unexpected abbrev ordering!");
1130   }
1131   
1132   { // INTEGER abbrev for CONSTANTS_BLOCK.
1133     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1134     Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_INTEGER));
1135     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
1136     if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID,
1137                                    Abbv) != CONSTANTS_INTEGER_ABBREV)
1138       assert(0 && "Unexpected abbrev ordering!");
1139   }
1140   
1141   { // CE_CAST abbrev for CONSTANTS_BLOCK.
1142     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1143     Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_CE_CAST));
1144     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4));  // cast opc
1145     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,       // typeid
1146                               Log2_32_Ceil(VE.getTypes().size()+1)));
1147     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));    // value id
1148
1149     if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID,
1150                                    Abbv) != CONSTANTS_CE_CAST_Abbrev)
1151       assert(0 && "Unexpected abbrev ordering!");
1152   }
1153   { // NULL abbrev for CONSTANTS_BLOCK.
1154     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1155     Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_NULL));
1156     if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID,
1157                                    Abbv) != CONSTANTS_NULL_Abbrev)
1158       assert(0 && "Unexpected abbrev ordering!");
1159   }
1160   
1161   // FIXME: This should only use space for first class types!
1162  
1163   { // INST_LOAD abbrev for FUNCTION_BLOCK.
1164     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1165     Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_LOAD));
1166     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Ptr
1167     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // Align
1168     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // volatile
1169     if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
1170                                    Abbv) != FUNCTION_INST_LOAD_ABBREV)
1171       assert(0 && "Unexpected abbrev ordering!");
1172   }
1173   { // INST_BINOP abbrev for FUNCTION_BLOCK.
1174     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1175     Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_BINOP));
1176     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // LHS
1177     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // RHS
1178     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
1179     if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
1180                                    Abbv) != FUNCTION_INST_BINOP_ABBREV)
1181       assert(0 && "Unexpected abbrev ordering!");
1182   }
1183   { // INST_CAST abbrev for FUNCTION_BLOCK.
1184     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1185     Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_CAST));
1186     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));    // OpVal
1187     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,       // dest ty
1188                               Log2_32_Ceil(VE.getTypes().size()+1)));
1189     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4));  // opc
1190     if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
1191                                    Abbv) != FUNCTION_INST_CAST_ABBREV)
1192       assert(0 && "Unexpected abbrev ordering!");
1193   }
1194   
1195   { // INST_RET abbrev for FUNCTION_BLOCK.
1196     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1197     Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_RET));
1198     if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
1199                                    Abbv) != FUNCTION_INST_RET_VOID_ABBREV)
1200       assert(0 && "Unexpected abbrev ordering!");
1201   }
1202   { // INST_RET abbrev for FUNCTION_BLOCK.
1203     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1204     Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_RET));
1205     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // ValID
1206     if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
1207                                    Abbv) != FUNCTION_INST_RET_VAL_ABBREV)
1208       assert(0 && "Unexpected abbrev ordering!");
1209   }
1210   { // INST_UNREACHABLE abbrev for FUNCTION_BLOCK.
1211     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1212     Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_UNREACHABLE));
1213     if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
1214                                    Abbv) != FUNCTION_INST_UNREACHABLE_ABBREV)
1215       assert(0 && "Unexpected abbrev ordering!");
1216   }
1217   
1218   Stream.ExitBlock();
1219 }
1220
1221
1222 /// WriteModule - Emit the specified module to the bitstream.
1223 static void WriteModule(const Module *M, BitstreamWriter &Stream) {
1224   Stream.EnterSubblock(bitc::MODULE_BLOCK_ID, 3);
1225   
1226   // Emit the version number if it is non-zero.
1227   if (CurVersion) {
1228     SmallVector<unsigned, 1> Vals;
1229     Vals.push_back(CurVersion);
1230     Stream.EmitRecord(bitc::MODULE_CODE_VERSION, Vals);
1231   }
1232   
1233   // Analyze the module, enumerating globals, functions, etc.
1234   ValueEnumerator VE(M);
1235
1236   // Emit blockinfo, which defines the standard abbreviations etc.
1237   WriteBlockInfo(VE, Stream);
1238   
1239   // Emit information about parameter attributes.
1240   WriteParamAttrTable(VE, Stream);
1241   
1242   // Emit information describing all of the types in the module.
1243   WriteTypeTable(VE, Stream);
1244   
1245   // Emit top-level description of module, including target triple, inline asm,
1246   // descriptors for global variables, and function prototype info.
1247   WriteModuleInfo(M, VE, Stream);
1248   
1249   // Emit constants.
1250   WriteModuleConstants(VE, Stream);
1251   
1252   // If we have any aggregate values in the value table, purge them - these can
1253   // only be used to initialize global variables.  Doing so makes the value
1254   // namespace smaller for code in functions.
1255   int NumNonAggregates = VE.PurgeAggregateValues();
1256   if (NumNonAggregates != -1) {
1257     SmallVector<unsigned, 1> Vals;
1258     Vals.push_back(NumNonAggregates);
1259     Stream.EmitRecord(bitc::MODULE_CODE_PURGEVALS, Vals);
1260   }
1261   
1262   // Emit function bodies.
1263   for (Module::const_iterator I = M->begin(), E = M->end(); I != E; ++I)
1264     if (!I->isDeclaration())
1265       WriteFunction(*I, VE, Stream);
1266   
1267   // Emit the type symbol table information.
1268   WriteTypeSymbolTable(M->getTypeSymbolTable(), VE, Stream);
1269   
1270   // Emit names for globals/functions etc.
1271   WriteValueSymbolTable(M->getValueSymbolTable(), VE, Stream);
1272   
1273   Stream.ExitBlock();
1274 }
1275
1276 /// EmitDarwinBCHeader - If generating a bc file on darwin, we have to emit a
1277 /// header and trailer to make it compatible with the system archiver.  To do
1278 /// this we emit the following header, and then emit a trailer that pads the
1279 /// file out to be a multiple of 16 bytes.
1280 /// 
1281 /// struct bc_header {
1282 ///   uint32_t Magic;         // 0x0B17C0DE
1283 ///   uint32_t Version;       // Version, currently always 0.
1284 ///   uint32_t BitcodeOffset; // Offset to traditional bitcode file.
1285 ///   uint32_t BitcodeSize;   // Size of traditional bitcode file.
1286 ///   uint32_t CPUType;       // CPU specifier.
1287 ///   ... potentially more later ...
1288 /// };
1289 enum {
1290   DarwinBCSizeFieldOffset = 3*4, // Offset to bitcode_size.
1291   DarwinBCHeaderSize = 5*4
1292 };
1293
1294 static void EmitDarwinBCHeader(BitstreamWriter &Stream,
1295                                const std::string &TT) {
1296   unsigned CPUType = ~0U;
1297   
1298   // Match x86_64-*, i[3-9]86-*, powerpc-*, powerpc64-*.  The CPUType is a
1299   // magic number from /usr/include/mach/machine.h.  It is ok to reproduce the
1300   // specific constants here because they are implicitly part of the Darwin ABI.
1301   enum {
1302     DARWIN_CPU_ARCH_ABI64      = 0x01000000,
1303     DARWIN_CPU_TYPE_X86        = 7,
1304     DARWIN_CPU_TYPE_POWERPC    = 18
1305   };
1306   
1307   if (TT.find("x86_64-") == 0)
1308     CPUType = DARWIN_CPU_TYPE_X86 | DARWIN_CPU_ARCH_ABI64;
1309   else if (TT.size() >= 5 && TT[0] == 'i' && TT[2] == '8' && TT[3] == '6' &&
1310            TT[4] == '-' && TT[1] - '3' < 6)
1311     CPUType = DARWIN_CPU_TYPE_X86;
1312   else if (TT.find("powerpc-") == 0)
1313     CPUType = DARWIN_CPU_TYPE_POWERPC;
1314   else if (TT.find("powerpc64-") == 0)
1315     CPUType = DARWIN_CPU_TYPE_POWERPC | DARWIN_CPU_ARCH_ABI64;
1316   
1317   // Traditional Bitcode starts after header.
1318   unsigned BCOffset = DarwinBCHeaderSize;
1319   
1320   Stream.Emit(0x0B17C0DE, 32);
1321   Stream.Emit(0         , 32);  // Version.
1322   Stream.Emit(BCOffset  , 32);
1323   Stream.Emit(0         , 32);  // Filled in later.
1324   Stream.Emit(CPUType   , 32);
1325 }
1326
1327 /// EmitDarwinBCTrailer - Emit the darwin epilog after the bitcode file and
1328 /// finalize the header.
1329 static void EmitDarwinBCTrailer(BitstreamWriter &Stream, unsigned BufferSize) {
1330   // Update the size field in the header.
1331   Stream.BackpatchWord(DarwinBCSizeFieldOffset, BufferSize-DarwinBCHeaderSize);
1332   
1333   // If the file is not a multiple of 16 bytes, insert dummy padding.
1334   while (BufferSize & 15) {
1335     Stream.Emit(0, 8);
1336     ++BufferSize;
1337   }
1338 }
1339
1340
1341 /// WriteBitcodeToFile - Write the specified module to the specified output
1342 /// stream.
1343 void llvm::WriteBitcodeToFile(const Module *M, std::ostream &Out) {
1344   std::vector<unsigned char> Buffer;
1345   BitstreamWriter Stream(Buffer);
1346   
1347   Buffer.reserve(256*1024);
1348   
1349   // If this is darwin, emit a file header and trailer if needed.
1350   bool isDarwin = M->getTargetTriple().find("-darwin") != std::string::npos;
1351   if (isDarwin)
1352     EmitDarwinBCHeader(Stream, M->getTargetTriple());
1353   
1354   // Emit the file header.
1355   Stream.Emit((unsigned)'B', 8);
1356   Stream.Emit((unsigned)'C', 8);
1357   Stream.Emit(0x0, 4);
1358   Stream.Emit(0xC, 4);
1359   Stream.Emit(0xE, 4);
1360   Stream.Emit(0xD, 4);
1361
1362   // Emit the module.
1363   WriteModule(M, Stream);
1364
1365   if (isDarwin)
1366     EmitDarwinBCTrailer(Stream, Buffer.size());
1367
1368   
1369   // If writing to stdout, set binary mode.
1370   if (llvm::cout == Out)
1371     sys::Program::ChangeStdoutToBinary();
1372
1373   // Write the generated bitstream to "Out".
1374   Out.write((char*)&Buffer.front(), Buffer.size());
1375   
1376   // Make sure it hits disk now.
1377   Out.flush();
1378 }