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