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