Remove unnecessary default cases in switches that cover all enum values.
[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/Operator.h"
24 #include "llvm/ValueSymbolTable.h"
25 #include "llvm/ADT/Triple.h"
26 #include "llvm/Support/CommandLine.h"
27 #include "llvm/Support/ErrorHandling.h"
28 #include "llvm/Support/MathExtras.h"
29 #include "llvm/Support/raw_ostream.h"
30 #include "llvm/Support/Program.h"
31 #include <cctype>
32 #include <map>
33 using namespace llvm;
34
35 static cl::opt<bool>
36 EnablePreserveUseListOrdering("enable-bc-uselist-preserve",
37                               cl::desc("Turn on experimental support for "
38                                        "use-list order preservation."),
39                               cl::init(false), cl::Hidden);
40
41 /// These are manifest constants used by the bitcode writer. They do not need to
42 /// be kept in sync with the reader, but need to be consistent within this file.
43 enum {
44   CurVersion = 0,
45
46   // VALUE_SYMTAB_BLOCK abbrev id's.
47   VST_ENTRY_8_ABBREV = bitc::FIRST_APPLICATION_ABBREV,
48   VST_ENTRY_7_ABBREV,
49   VST_ENTRY_6_ABBREV,
50   VST_BBENTRY_6_ABBREV,
51
52   // CONSTANTS_BLOCK abbrev id's.
53   CONSTANTS_SETTYPE_ABBREV = bitc::FIRST_APPLICATION_ABBREV,
54   CONSTANTS_INTEGER_ABBREV,
55   CONSTANTS_CE_CAST_Abbrev,
56   CONSTANTS_NULL_Abbrev,
57
58   // FUNCTION_BLOCK abbrev id's.
59   FUNCTION_INST_LOAD_ABBREV = bitc::FIRST_APPLICATION_ABBREV,
60   FUNCTION_INST_BINOP_ABBREV,
61   FUNCTION_INST_BINOP_FLAGS_ABBREV,
62   FUNCTION_INST_CAST_ABBREV,
63   FUNCTION_INST_RET_VOID_ABBREV,
64   FUNCTION_INST_RET_VAL_ABBREV,
65   FUNCTION_INST_UNREACHABLE_ABBREV
66 };
67
68 static unsigned GetEncodedCastOpcode(unsigned Opcode) {
69   switch (Opcode) {
70   default: llvm_unreachable("Unknown cast instruction!");
71   case Instruction::Trunc   : return bitc::CAST_TRUNC;
72   case Instruction::ZExt    : return bitc::CAST_ZEXT;
73   case Instruction::SExt    : return bitc::CAST_SEXT;
74   case Instruction::FPToUI  : return bitc::CAST_FPTOUI;
75   case Instruction::FPToSI  : return bitc::CAST_FPTOSI;
76   case Instruction::UIToFP  : return bitc::CAST_UITOFP;
77   case Instruction::SIToFP  : return bitc::CAST_SITOFP;
78   case Instruction::FPTrunc : return bitc::CAST_FPTRUNC;
79   case Instruction::FPExt   : return bitc::CAST_FPEXT;
80   case Instruction::PtrToInt: return bitc::CAST_PTRTOINT;
81   case Instruction::IntToPtr: return bitc::CAST_INTTOPTR;
82   case Instruction::BitCast : return bitc::CAST_BITCAST;
83   }
84 }
85
86 static unsigned GetEncodedBinaryOpcode(unsigned Opcode) {
87   switch (Opcode) {
88   default: llvm_unreachable("Unknown binary instruction!");
89   case Instruction::Add:
90   case Instruction::FAdd: return bitc::BINOP_ADD;
91   case Instruction::Sub:
92   case Instruction::FSub: return bitc::BINOP_SUB;
93   case Instruction::Mul:
94   case Instruction::FMul: return bitc::BINOP_MUL;
95   case Instruction::UDiv: return bitc::BINOP_UDIV;
96   case Instruction::FDiv:
97   case Instruction::SDiv: return bitc::BINOP_SDIV;
98   case Instruction::URem: return bitc::BINOP_UREM;
99   case Instruction::FRem:
100   case Instruction::SRem: return bitc::BINOP_SREM;
101   case Instruction::Shl:  return bitc::BINOP_SHL;
102   case Instruction::LShr: return bitc::BINOP_LSHR;
103   case Instruction::AShr: return bitc::BINOP_ASHR;
104   case Instruction::And:  return bitc::BINOP_AND;
105   case Instruction::Or:   return bitc::BINOP_OR;
106   case Instruction::Xor:  return bitc::BINOP_XOR;
107   }
108 }
109
110 static unsigned GetEncodedRMWOperation(AtomicRMWInst::BinOp Op) {
111   switch (Op) {
112   default: llvm_unreachable("Unknown RMW operation!");
113   case AtomicRMWInst::Xchg: return bitc::RMW_XCHG;
114   case AtomicRMWInst::Add: return bitc::RMW_ADD;
115   case AtomicRMWInst::Sub: return bitc::RMW_SUB;
116   case AtomicRMWInst::And: return bitc::RMW_AND;
117   case AtomicRMWInst::Nand: return bitc::RMW_NAND;
118   case AtomicRMWInst::Or: return bitc::RMW_OR;
119   case AtomicRMWInst::Xor: return bitc::RMW_XOR;
120   case AtomicRMWInst::Max: return bitc::RMW_MAX;
121   case AtomicRMWInst::Min: return bitc::RMW_MIN;
122   case AtomicRMWInst::UMax: return bitc::RMW_UMAX;
123   case AtomicRMWInst::UMin: return bitc::RMW_UMIN;
124   }
125 }
126
127 static unsigned GetEncodedOrdering(AtomicOrdering Ordering) {
128   switch (Ordering) {
129   case NotAtomic: return bitc::ORDERING_NOTATOMIC;
130   case Unordered: return bitc::ORDERING_UNORDERED;
131   case Monotonic: return bitc::ORDERING_MONOTONIC;
132   case Acquire: return bitc::ORDERING_ACQUIRE;
133   case Release: return bitc::ORDERING_RELEASE;
134   case AcquireRelease: return bitc::ORDERING_ACQREL;
135   case SequentiallyConsistent: return bitc::ORDERING_SEQCST;
136   }
137 }
138
139 static unsigned GetEncodedSynchScope(SynchronizationScope SynchScope) {
140   switch (SynchScope) {
141   case SingleThread: return bitc::SYNCHSCOPE_SINGLETHREAD;
142   case CrossThread: return bitc::SYNCHSCOPE_CROSSTHREAD;
143   }
144 }
145
146 static void WriteStringRecord(unsigned Code, StringRef Str,
147                               unsigned AbbrevToUse, BitstreamWriter &Stream) {
148   SmallVector<unsigned, 64> Vals;
149
150   // Code: [strchar x N]
151   for (unsigned i = 0, e = Str.size(); i != e; ++i) {
152     if (AbbrevToUse && !BitCodeAbbrevOp::isChar6(Str[i]))
153       AbbrevToUse = 0;
154     Vals.push_back(Str[i]);
155   }
156
157   // Emit the finished record.
158   Stream.EmitRecord(Code, Vals, AbbrevToUse);
159 }
160
161 // Emit information about parameter attributes.
162 static void WriteAttributeTable(const ValueEnumerator &VE,
163                                 BitstreamWriter &Stream) {
164   const std::vector<AttrListPtr> &Attrs = VE.getAttributes();
165   if (Attrs.empty()) return;
166
167   Stream.EnterSubblock(bitc::PARAMATTR_BLOCK_ID, 3);
168
169   SmallVector<uint64_t, 64> Record;
170   for (unsigned i = 0, e = Attrs.size(); i != e; ++i) {
171     const AttrListPtr &A = Attrs[i];
172     for (unsigned i = 0, e = A.getNumSlots(); i != e; ++i) {
173       const AttributeWithIndex &PAWI = A.getSlot(i);
174       Record.push_back(PAWI.Index);
175
176       // FIXME: remove in LLVM 3.0
177       // Store the alignment in the bitcode as a 16-bit raw value instead of a
178       // 5-bit log2 encoded value. Shift the bits above the alignment up by
179       // 11 bits.
180       uint64_t FauxAttr = PAWI.Attrs & 0xffff;
181       if (PAWI.Attrs & Attribute::Alignment)
182         FauxAttr |= (1ull<<16)<<(((PAWI.Attrs & Attribute::Alignment)-1) >> 16);
183       FauxAttr |= (PAWI.Attrs & (0x3FFull << 21)) << 11;
184
185       Record.push_back(FauxAttr);
186     }
187
188     Stream.EmitRecord(bitc::PARAMATTR_CODE_ENTRY, Record);
189     Record.clear();
190   }
191
192   Stream.ExitBlock();
193 }
194
195 /// WriteTypeTable - Write out the type table for a module.
196 static void WriteTypeTable(const ValueEnumerator &VE, BitstreamWriter &Stream) {
197   const ValueEnumerator::TypeList &TypeList = VE.getTypes();
198
199   Stream.EnterSubblock(bitc::TYPE_BLOCK_ID_NEW, 4 /*count from # abbrevs */);
200   SmallVector<uint64_t, 64> TypeVals;
201
202   uint64_t NumBits = Log2_32_Ceil(VE.getTypes().size()+1);
203
204   // Abbrev for TYPE_CODE_POINTER.
205   BitCodeAbbrev *Abbv = new BitCodeAbbrev();
206   Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_POINTER));
207   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
208   Abbv->Add(BitCodeAbbrevOp(0));  // Addrspace = 0
209   unsigned PtrAbbrev = Stream.EmitAbbrev(Abbv);
210
211   // Abbrev for TYPE_CODE_FUNCTION.
212   Abbv = new BitCodeAbbrev();
213   Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_FUNCTION));
214   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));  // isvararg
215   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
216   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
217
218   unsigned FunctionAbbrev = Stream.EmitAbbrev(Abbv);
219
220   // Abbrev for TYPE_CODE_STRUCT_ANON.
221   Abbv = new BitCodeAbbrev();
222   Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_STRUCT_ANON));
223   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));  // ispacked
224   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
225   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
226
227   unsigned StructAnonAbbrev = Stream.EmitAbbrev(Abbv);
228
229   // Abbrev for TYPE_CODE_STRUCT_NAME.
230   Abbv = new BitCodeAbbrev();
231   Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_STRUCT_NAME));
232   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
233   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
234   unsigned StructNameAbbrev = Stream.EmitAbbrev(Abbv);
235
236   // Abbrev for TYPE_CODE_STRUCT_NAMED.
237   Abbv = new BitCodeAbbrev();
238   Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_STRUCT_NAMED));
239   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));  // ispacked
240   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
241   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
242
243   unsigned StructNamedAbbrev = Stream.EmitAbbrev(Abbv);
244   
245   // Abbrev for TYPE_CODE_ARRAY.
246   Abbv = new BitCodeAbbrev();
247   Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_ARRAY));
248   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));   // size
249   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
250
251   unsigned ArrayAbbrev = Stream.EmitAbbrev(Abbv);
252
253   // Emit an entry count so the reader can reserve space.
254   TypeVals.push_back(TypeList.size());
255   Stream.EmitRecord(bitc::TYPE_CODE_NUMENTRY, TypeVals);
256   TypeVals.clear();
257
258   // Loop over all of the types, emitting each in turn.
259   for (unsigned i = 0, e = TypeList.size(); i != e; ++i) {
260     Type *T = TypeList[i];
261     int AbbrevToUse = 0;
262     unsigned Code = 0;
263
264     switch (T->getTypeID()) {
265     default: llvm_unreachable("Unknown type!");
266     case Type::VoidTyID:      Code = bitc::TYPE_CODE_VOID;   break;
267     case Type::HalfTyID:      Code = bitc::TYPE_CODE_HALF;   break;
268     case Type::FloatTyID:     Code = bitc::TYPE_CODE_FLOAT;  break;
269     case Type::DoubleTyID:    Code = bitc::TYPE_CODE_DOUBLE; break;
270     case Type::X86_FP80TyID:  Code = bitc::TYPE_CODE_X86_FP80; break;
271     case Type::FP128TyID:     Code = bitc::TYPE_CODE_FP128; break;
272     case Type::PPC_FP128TyID: Code = bitc::TYPE_CODE_PPC_FP128; break;
273     case Type::LabelTyID:     Code = bitc::TYPE_CODE_LABEL;  break;
274     case Type::MetadataTyID:  Code = bitc::TYPE_CODE_METADATA; break;
275     case Type::X86_MMXTyID:   Code = bitc::TYPE_CODE_X86_MMX; break;
276     case Type::IntegerTyID:
277       // INTEGER: [width]
278       Code = bitc::TYPE_CODE_INTEGER;
279       TypeVals.push_back(cast<IntegerType>(T)->getBitWidth());
280       break;
281     case Type::PointerTyID: {
282       PointerType *PTy = cast<PointerType>(T);
283       // POINTER: [pointee type, address space]
284       Code = bitc::TYPE_CODE_POINTER;
285       TypeVals.push_back(VE.getTypeID(PTy->getElementType()));
286       unsigned AddressSpace = PTy->getAddressSpace();
287       TypeVals.push_back(AddressSpace);
288       if (AddressSpace == 0) AbbrevToUse = PtrAbbrev;
289       break;
290     }
291     case Type::FunctionTyID: {
292       FunctionType *FT = cast<FunctionType>(T);
293       // FUNCTION: [isvararg, retty, paramty x N]
294       Code = bitc::TYPE_CODE_FUNCTION;
295       TypeVals.push_back(FT->isVarArg());
296       TypeVals.push_back(VE.getTypeID(FT->getReturnType()));
297       for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i)
298         TypeVals.push_back(VE.getTypeID(FT->getParamType(i)));
299       AbbrevToUse = FunctionAbbrev;
300       break;
301     }
302     case Type::StructTyID: {
303       StructType *ST = cast<StructType>(T);
304       // STRUCT: [ispacked, eltty x N]
305       TypeVals.push_back(ST->isPacked());
306       // Output all of the element types.
307       for (StructType::element_iterator I = ST->element_begin(),
308            E = ST->element_end(); I != E; ++I)
309         TypeVals.push_back(VE.getTypeID(*I));
310       
311       if (ST->isLiteral()) {
312         Code = bitc::TYPE_CODE_STRUCT_ANON;
313         AbbrevToUse = StructAnonAbbrev;
314       } else {
315         if (ST->isOpaque()) {
316           Code = bitc::TYPE_CODE_OPAQUE;
317         } else {
318           Code = bitc::TYPE_CODE_STRUCT_NAMED;
319           AbbrevToUse = StructNamedAbbrev;
320         }
321
322         // Emit the name if it is present.
323         if (!ST->getName().empty())
324           WriteStringRecord(bitc::TYPE_CODE_STRUCT_NAME, ST->getName(),
325                             StructNameAbbrev, Stream);
326       }
327       break;
328     }
329     case Type::ArrayTyID: {
330       ArrayType *AT = cast<ArrayType>(T);
331       // ARRAY: [numelts, eltty]
332       Code = bitc::TYPE_CODE_ARRAY;
333       TypeVals.push_back(AT->getNumElements());
334       TypeVals.push_back(VE.getTypeID(AT->getElementType()));
335       AbbrevToUse = ArrayAbbrev;
336       break;
337     }
338     case Type::VectorTyID: {
339       VectorType *VT = cast<VectorType>(T);
340       // VECTOR [numelts, eltty]
341       Code = bitc::TYPE_CODE_VECTOR;
342       TypeVals.push_back(VT->getNumElements());
343       TypeVals.push_back(VE.getTypeID(VT->getElementType()));
344       break;
345     }
346     }
347
348     // Emit the finished record.
349     Stream.EmitRecord(Code, TypeVals, AbbrevToUse);
350     TypeVals.clear();
351   }
352
353   Stream.ExitBlock();
354 }
355
356 static unsigned getEncodedLinkage(const GlobalValue *GV) {
357   switch (GV->getLinkage()) {
358   case GlobalValue::ExternalLinkage:                 return 0;
359   case GlobalValue::WeakAnyLinkage:                  return 1;
360   case GlobalValue::AppendingLinkage:                return 2;
361   case GlobalValue::InternalLinkage:                 return 3;
362   case GlobalValue::LinkOnceAnyLinkage:              return 4;
363   case GlobalValue::DLLImportLinkage:                return 5;
364   case GlobalValue::DLLExportLinkage:                return 6;
365   case GlobalValue::ExternalWeakLinkage:             return 7;
366   case GlobalValue::CommonLinkage:                   return 8;
367   case GlobalValue::PrivateLinkage:                  return 9;
368   case GlobalValue::WeakODRLinkage:                  return 10;
369   case GlobalValue::LinkOnceODRLinkage:              return 11;
370   case GlobalValue::AvailableExternallyLinkage:      return 12;
371   case GlobalValue::LinkerPrivateLinkage:            return 13;
372   case GlobalValue::LinkerPrivateWeakLinkage:        return 14;
373   case GlobalValue::LinkerPrivateWeakDefAutoLinkage: return 15;
374   }
375 }
376
377 static unsigned getEncodedVisibility(const GlobalValue *GV) {
378   switch (GV->getVisibility()) {
379   case GlobalValue::DefaultVisibility:   return 0;
380   case GlobalValue::HiddenVisibility:    return 1;
381   case GlobalValue::ProtectedVisibility: return 2;
382   }
383 }
384
385 // Emit top-level description of module, including target triple, inline asm,
386 // descriptors for global variables, and function prototype info.
387 static void WriteModuleInfo(const Module *M, const ValueEnumerator &VE,
388                             BitstreamWriter &Stream) {
389   // Emit the list of dependent libraries for the Module.
390   for (Module::lib_iterator I = M->lib_begin(), E = M->lib_end(); I != E; ++I)
391     WriteStringRecord(bitc::MODULE_CODE_DEPLIB, *I, 0/*TODO*/, Stream);
392
393   // Emit various pieces of data attached to a module.
394   if (!M->getTargetTriple().empty())
395     WriteStringRecord(bitc::MODULE_CODE_TRIPLE, M->getTargetTriple(),
396                       0/*TODO*/, Stream);
397   if (!M->getDataLayout().empty())
398     WriteStringRecord(bitc::MODULE_CODE_DATALAYOUT, M->getDataLayout(),
399                       0/*TODO*/, Stream);
400   if (!M->getModuleInlineAsm().empty())
401     WriteStringRecord(bitc::MODULE_CODE_ASM, M->getModuleInlineAsm(),
402                       0/*TODO*/, Stream);
403
404   // Emit information about sections and GC, computing how many there are. Also
405   // compute the maximum alignment value.
406   std::map<std::string, unsigned> SectionMap;
407   std::map<std::string, unsigned> GCMap;
408   unsigned MaxAlignment = 0;
409   unsigned MaxGlobalType = 0;
410   for (Module::const_global_iterator GV = M->global_begin(),E = M->global_end();
411        GV != E; ++GV) {
412     MaxAlignment = std::max(MaxAlignment, GV->getAlignment());
413     MaxGlobalType = std::max(MaxGlobalType, VE.getTypeID(GV->getType()));
414     if (GV->hasSection()) {
415       // Give section names unique ID's.
416       unsigned &Entry = SectionMap[GV->getSection()];
417       if (!Entry) {
418         WriteStringRecord(bitc::MODULE_CODE_SECTIONNAME, GV->getSection(),
419                           0/*TODO*/, Stream);
420         Entry = SectionMap.size();
421       }
422     }
423   }
424   for (Module::const_iterator F = M->begin(), E = M->end(); F != E; ++F) {
425     MaxAlignment = std::max(MaxAlignment, F->getAlignment());
426     if (F->hasSection()) {
427       // Give section names unique ID's.
428       unsigned &Entry = SectionMap[F->getSection()];
429       if (!Entry) {
430         WriteStringRecord(bitc::MODULE_CODE_SECTIONNAME, F->getSection(),
431                           0/*TODO*/, Stream);
432         Entry = SectionMap.size();
433       }
434     }
435     if (F->hasGC()) {
436       // Same for GC names.
437       unsigned &Entry = GCMap[F->getGC()];
438       if (!Entry) {
439         WriteStringRecord(bitc::MODULE_CODE_GCNAME, F->getGC(),
440                           0/*TODO*/, Stream);
441         Entry = GCMap.size();
442       }
443     }
444   }
445
446   // Emit abbrev for globals, now that we know # sections and max alignment.
447   unsigned SimpleGVarAbbrev = 0;
448   if (!M->global_empty()) {
449     // Add an abbrev for common globals with no visibility or thread localness.
450     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
451     Abbv->Add(BitCodeAbbrevOp(bitc::MODULE_CODE_GLOBALVAR));
452     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
453                               Log2_32_Ceil(MaxGlobalType+1)));
454     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));      // Constant.
455     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));        // Initializer.
456     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4));      // Linkage.
457     if (MaxAlignment == 0)                                      // Alignment.
458       Abbv->Add(BitCodeAbbrevOp(0));
459     else {
460       unsigned MaxEncAlignment = Log2_32(MaxAlignment)+1;
461       Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
462                                Log2_32_Ceil(MaxEncAlignment+1)));
463     }
464     if (SectionMap.empty())                                    // Section.
465       Abbv->Add(BitCodeAbbrevOp(0));
466     else
467       Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
468                                Log2_32_Ceil(SectionMap.size()+1)));
469     // Don't bother emitting vis + thread local.
470     SimpleGVarAbbrev = Stream.EmitAbbrev(Abbv);
471   }
472
473   // Emit the global variable information.
474   SmallVector<unsigned, 64> Vals;
475   for (Module::const_global_iterator GV = M->global_begin(),E = M->global_end();
476        GV != E; ++GV) {
477     unsigned AbbrevToUse = 0;
478
479     // GLOBALVAR: [type, isconst, initid,
480     //             linkage, alignment, section, visibility, threadlocal,
481     //             unnamed_addr]
482     Vals.push_back(VE.getTypeID(GV->getType()));
483     Vals.push_back(GV->isConstant());
484     Vals.push_back(GV->isDeclaration() ? 0 :
485                    (VE.getValueID(GV->getInitializer()) + 1));
486     Vals.push_back(getEncodedLinkage(GV));
487     Vals.push_back(Log2_32(GV->getAlignment())+1);
488     Vals.push_back(GV->hasSection() ? SectionMap[GV->getSection()] : 0);
489     if (GV->isThreadLocal() ||
490         GV->getVisibility() != GlobalValue::DefaultVisibility ||
491         GV->hasUnnamedAddr()) {
492       Vals.push_back(getEncodedVisibility(GV));
493       Vals.push_back(GV->isThreadLocal());
494       Vals.push_back(GV->hasUnnamedAddr());
495     } else {
496       AbbrevToUse = SimpleGVarAbbrev;
497     }
498
499     Stream.EmitRecord(bitc::MODULE_CODE_GLOBALVAR, Vals, AbbrevToUse);
500     Vals.clear();
501   }
502
503   // Emit the function proto information.
504   for (Module::const_iterator F = M->begin(), E = M->end(); F != E; ++F) {
505     // FUNCTION:  [type, callingconv, isproto, linkage, paramattrs, alignment,
506     //             section, visibility, gc, unnamed_addr]
507     Vals.push_back(VE.getTypeID(F->getType()));
508     Vals.push_back(F->getCallingConv());
509     Vals.push_back(F->isDeclaration());
510     Vals.push_back(getEncodedLinkage(F));
511     Vals.push_back(VE.getAttributeID(F->getAttributes()));
512     Vals.push_back(Log2_32(F->getAlignment())+1);
513     Vals.push_back(F->hasSection() ? SectionMap[F->getSection()] : 0);
514     Vals.push_back(getEncodedVisibility(F));
515     Vals.push_back(F->hasGC() ? GCMap[F->getGC()] : 0);
516     Vals.push_back(F->hasUnnamedAddr());
517
518     unsigned AbbrevToUse = 0;
519     Stream.EmitRecord(bitc::MODULE_CODE_FUNCTION, Vals, AbbrevToUse);
520     Vals.clear();
521   }
522
523   // Emit the alias information.
524   for (Module::const_alias_iterator AI = M->alias_begin(), E = M->alias_end();
525        AI != E; ++AI) {
526     // ALIAS: [alias type, aliasee val#, linkage, visibility]
527     Vals.push_back(VE.getTypeID(AI->getType()));
528     Vals.push_back(VE.getValueID(AI->getAliasee()));
529     Vals.push_back(getEncodedLinkage(AI));
530     Vals.push_back(getEncodedVisibility(AI));
531     unsigned AbbrevToUse = 0;
532     Stream.EmitRecord(bitc::MODULE_CODE_ALIAS, Vals, AbbrevToUse);
533     Vals.clear();
534   }
535 }
536
537 static uint64_t GetOptimizationFlags(const Value *V) {
538   uint64_t Flags = 0;
539
540   if (const OverflowingBinaryOperator *OBO =
541         dyn_cast<OverflowingBinaryOperator>(V)) {
542     if (OBO->hasNoSignedWrap())
543       Flags |= 1 << bitc::OBO_NO_SIGNED_WRAP;
544     if (OBO->hasNoUnsignedWrap())
545       Flags |= 1 << bitc::OBO_NO_UNSIGNED_WRAP;
546   } else if (const PossiblyExactOperator *PEO =
547                dyn_cast<PossiblyExactOperator>(V)) {
548     if (PEO->isExact())
549       Flags |= 1 << bitc::PEO_EXACT;
550   }
551
552   return Flags;
553 }
554
555 static void WriteMDNode(const MDNode *N,
556                         const ValueEnumerator &VE,
557                         BitstreamWriter &Stream,
558                         SmallVector<uint64_t, 64> &Record) {
559   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
560     if (N->getOperand(i)) {
561       Record.push_back(VE.getTypeID(N->getOperand(i)->getType()));
562       Record.push_back(VE.getValueID(N->getOperand(i)));
563     } else {
564       Record.push_back(VE.getTypeID(Type::getVoidTy(N->getContext())));
565       Record.push_back(0);
566     }
567   }
568   unsigned MDCode = N->isFunctionLocal() ? bitc::METADATA_FN_NODE :
569                                            bitc::METADATA_NODE;
570   Stream.EmitRecord(MDCode, Record, 0);
571   Record.clear();
572 }
573
574 static void WriteModuleMetadata(const Module *M,
575                                 const ValueEnumerator &VE,
576                                 BitstreamWriter &Stream) {
577   const ValueEnumerator::ValueList &Vals = VE.getMDValues();
578   bool StartedMetadataBlock = false;
579   unsigned MDSAbbrev = 0;
580   SmallVector<uint64_t, 64> Record;
581   for (unsigned i = 0, e = Vals.size(); i != e; ++i) {
582
583     if (const MDNode *N = dyn_cast<MDNode>(Vals[i].first)) {
584       if (!N->isFunctionLocal() || !N->getFunction()) {
585         if (!StartedMetadataBlock) {
586           Stream.EnterSubblock(bitc::METADATA_BLOCK_ID, 3);
587           StartedMetadataBlock = true;
588         }
589         WriteMDNode(N, VE, Stream, Record);
590       }
591     } else if (const MDString *MDS = dyn_cast<MDString>(Vals[i].first)) {
592       if (!StartedMetadataBlock)  {
593         Stream.EnterSubblock(bitc::METADATA_BLOCK_ID, 3);
594
595         // Abbrev for METADATA_STRING.
596         BitCodeAbbrev *Abbv = new BitCodeAbbrev();
597         Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_STRING));
598         Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
599         Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
600         MDSAbbrev = Stream.EmitAbbrev(Abbv);
601         StartedMetadataBlock = true;
602       }
603
604       // Code: [strchar x N]
605       Record.append(MDS->begin(), MDS->end());
606
607       // Emit the finished record.
608       Stream.EmitRecord(bitc::METADATA_STRING, Record, MDSAbbrev);
609       Record.clear();
610     }
611   }
612
613   // Write named metadata.
614   for (Module::const_named_metadata_iterator I = M->named_metadata_begin(),
615        E = M->named_metadata_end(); I != E; ++I) {
616     const NamedMDNode *NMD = I;
617     if (!StartedMetadataBlock)  {
618       Stream.EnterSubblock(bitc::METADATA_BLOCK_ID, 3);
619       StartedMetadataBlock = true;
620     }
621
622     // Write name.
623     StringRef Str = NMD->getName();
624     for (unsigned i = 0, e = Str.size(); i != e; ++i)
625       Record.push_back(Str[i]);
626     Stream.EmitRecord(bitc::METADATA_NAME, Record, 0/*TODO*/);
627     Record.clear();
628
629     // Write named metadata operands.
630     for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i)
631       Record.push_back(VE.getValueID(NMD->getOperand(i)));
632     Stream.EmitRecord(bitc::METADATA_NAMED_NODE, Record, 0);
633     Record.clear();
634   }
635
636   if (StartedMetadataBlock)
637     Stream.ExitBlock();
638 }
639
640 static void WriteFunctionLocalMetadata(const Function &F,
641                                        const ValueEnumerator &VE,
642                                        BitstreamWriter &Stream) {
643   bool StartedMetadataBlock = false;
644   SmallVector<uint64_t, 64> Record;
645   const SmallVector<const MDNode *, 8> &Vals = VE.getFunctionLocalMDValues();
646   for (unsigned i = 0, e = Vals.size(); i != e; ++i)
647     if (const MDNode *N = Vals[i])
648       if (N->isFunctionLocal() && N->getFunction() == &F) {
649         if (!StartedMetadataBlock) {
650           Stream.EnterSubblock(bitc::METADATA_BLOCK_ID, 3);
651           StartedMetadataBlock = true;
652         }
653         WriteMDNode(N, VE, Stream, Record);
654       }
655       
656   if (StartedMetadataBlock)
657     Stream.ExitBlock();
658 }
659
660 static void WriteMetadataAttachment(const Function &F,
661                                     const ValueEnumerator &VE,
662                                     BitstreamWriter &Stream) {
663   Stream.EnterSubblock(bitc::METADATA_ATTACHMENT_ID, 3);
664
665   SmallVector<uint64_t, 64> Record;
666
667   // Write metadata attachments
668   // METADATA_ATTACHMENT - [m x [value, [n x [id, mdnode]]]
669   SmallVector<std::pair<unsigned, MDNode*>, 4> MDs;
670   
671   for (Function::const_iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
672     for (BasicBlock::const_iterator I = BB->begin(), E = BB->end();
673          I != E; ++I) {
674       MDs.clear();
675       I->getAllMetadataOtherThanDebugLoc(MDs);
676       
677       // If no metadata, ignore instruction.
678       if (MDs.empty()) continue;
679
680       Record.push_back(VE.getInstructionID(I));
681       
682       for (unsigned i = 0, e = MDs.size(); i != e; ++i) {
683         Record.push_back(MDs[i].first);
684         Record.push_back(VE.getValueID(MDs[i].second));
685       }
686       Stream.EmitRecord(bitc::METADATA_ATTACHMENT, Record, 0);
687       Record.clear();
688     }
689
690   Stream.ExitBlock();
691 }
692
693 static void WriteModuleMetadataStore(const Module *M, BitstreamWriter &Stream) {
694   SmallVector<uint64_t, 64> Record;
695
696   // Write metadata kinds
697   // METADATA_KIND - [n x [id, name]]
698   SmallVector<StringRef, 4> Names;
699   M->getMDKindNames(Names);
700   
701   if (Names.empty()) return;
702
703   Stream.EnterSubblock(bitc::METADATA_BLOCK_ID, 3);
704   
705   for (unsigned MDKindID = 0, e = Names.size(); MDKindID != e; ++MDKindID) {
706     Record.push_back(MDKindID);
707     StringRef KName = Names[MDKindID];
708     Record.append(KName.begin(), KName.end());
709     
710     Stream.EmitRecord(bitc::METADATA_KIND, Record, 0);
711     Record.clear();
712   }
713
714   Stream.ExitBlock();
715 }
716
717 static void WriteConstants(unsigned FirstVal, unsigned LastVal,
718                            const ValueEnumerator &VE,
719                            BitstreamWriter &Stream, bool isGlobal) {
720   if (FirstVal == LastVal) return;
721
722   Stream.EnterSubblock(bitc::CONSTANTS_BLOCK_ID, 4);
723
724   unsigned AggregateAbbrev = 0;
725   unsigned String8Abbrev = 0;
726   unsigned CString7Abbrev = 0;
727   unsigned CString6Abbrev = 0;
728   // If this is a constant pool for the module, emit module-specific abbrevs.
729   if (isGlobal) {
730     // Abbrev for CST_CODE_AGGREGATE.
731     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
732     Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_AGGREGATE));
733     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
734     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, Log2_32_Ceil(LastVal+1)));
735     AggregateAbbrev = Stream.EmitAbbrev(Abbv);
736
737     // Abbrev for CST_CODE_STRING.
738     Abbv = new BitCodeAbbrev();
739     Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_STRING));
740     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
741     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
742     String8Abbrev = Stream.EmitAbbrev(Abbv);
743     // Abbrev for CST_CODE_CSTRING.
744     Abbv = new BitCodeAbbrev();
745     Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_CSTRING));
746     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
747     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7));
748     CString7Abbrev = Stream.EmitAbbrev(Abbv);
749     // Abbrev for CST_CODE_CSTRING.
750     Abbv = new BitCodeAbbrev();
751     Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_CSTRING));
752     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
753     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
754     CString6Abbrev = Stream.EmitAbbrev(Abbv);
755   }
756
757   SmallVector<uint64_t, 64> Record;
758
759   const ValueEnumerator::ValueList &Vals = VE.getValues();
760   Type *LastTy = 0;
761   for (unsigned i = FirstVal; i != LastVal; ++i) {
762     const Value *V = Vals[i].first;
763     // If we need to switch types, do so now.
764     if (V->getType() != LastTy) {
765       LastTy = V->getType();
766       Record.push_back(VE.getTypeID(LastTy));
767       Stream.EmitRecord(bitc::CST_CODE_SETTYPE, Record,
768                         CONSTANTS_SETTYPE_ABBREV);
769       Record.clear();
770     }
771
772     if (const InlineAsm *IA = dyn_cast<InlineAsm>(V)) {
773       Record.push_back(unsigned(IA->hasSideEffects()) |
774                        unsigned(IA->isAlignStack()) << 1);
775
776       // Add the asm string.
777       const std::string &AsmStr = IA->getAsmString();
778       Record.push_back(AsmStr.size());
779       for (unsigned i = 0, e = AsmStr.size(); i != e; ++i)
780         Record.push_back(AsmStr[i]);
781
782       // Add the constraint string.
783       const std::string &ConstraintStr = IA->getConstraintString();
784       Record.push_back(ConstraintStr.size());
785       for (unsigned i = 0, e = ConstraintStr.size(); i != e; ++i)
786         Record.push_back(ConstraintStr[i]);
787       Stream.EmitRecord(bitc::CST_CODE_INLINEASM, Record);
788       Record.clear();
789       continue;
790     }
791     const Constant *C = cast<Constant>(V);
792     unsigned Code = -1U;
793     unsigned AbbrevToUse = 0;
794     if (C->isNullValue()) {
795       Code = bitc::CST_CODE_NULL;
796     } else if (isa<UndefValue>(C)) {
797       Code = bitc::CST_CODE_UNDEF;
798     } else if (const ConstantInt *IV = dyn_cast<ConstantInt>(C)) {
799       if (IV->getBitWidth() <= 64) {
800         uint64_t V = IV->getSExtValue();
801         if ((int64_t)V >= 0)
802           Record.push_back(V << 1);
803         else
804           Record.push_back((-V << 1) | 1);
805         Code = bitc::CST_CODE_INTEGER;
806         AbbrevToUse = CONSTANTS_INTEGER_ABBREV;
807       } else {                             // Wide integers, > 64 bits in size.
808         // We have an arbitrary precision integer value to write whose
809         // bit width is > 64. However, in canonical unsigned integer
810         // format it is likely that the high bits are going to be zero.
811         // So, we only write the number of active words.
812         unsigned NWords = IV->getValue().getActiveWords();
813         const uint64_t *RawWords = IV->getValue().getRawData();
814         for (unsigned i = 0; i != NWords; ++i) {
815           int64_t V = RawWords[i];
816           if (V >= 0)
817             Record.push_back(V << 1);
818           else
819             Record.push_back((-V << 1) | 1);
820         }
821         Code = bitc::CST_CODE_WIDE_INTEGER;
822       }
823     } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
824       Code = bitc::CST_CODE_FLOAT;
825       Type *Ty = CFP->getType();
826       if (Ty->isHalfTy() || Ty->isFloatTy() || Ty->isDoubleTy()) {
827         Record.push_back(CFP->getValueAPF().bitcastToAPInt().getZExtValue());
828       } else if (Ty->isX86_FP80Ty()) {
829         // api needed to prevent premature destruction
830         // bits are not in the same order as a normal i80 APInt, compensate.
831         APInt api = CFP->getValueAPF().bitcastToAPInt();
832         const uint64_t *p = api.getRawData();
833         Record.push_back((p[1] << 48) | (p[0] >> 16));
834         Record.push_back(p[0] & 0xffffLL);
835       } else if (Ty->isFP128Ty() || Ty->isPPC_FP128Ty()) {
836         APInt api = CFP->getValueAPF().bitcastToAPInt();
837         const uint64_t *p = api.getRawData();
838         Record.push_back(p[0]);
839         Record.push_back(p[1]);
840       } else {
841         assert (0 && "Unknown FP type!");
842       }
843     } else if (isa<ConstantArray>(C) && cast<ConstantArray>(C)->isString()) {
844       const ConstantArray *CA = cast<ConstantArray>(C);
845       // Emit constant strings specially.
846       unsigned NumOps = CA->getNumOperands();
847       // If this is a null-terminated string, use the denser CSTRING encoding.
848       if (CA->getOperand(NumOps-1)->isNullValue()) {
849         Code = bitc::CST_CODE_CSTRING;
850         --NumOps;  // Don't encode the null, which isn't allowed by char6.
851       } else {
852         Code = bitc::CST_CODE_STRING;
853         AbbrevToUse = String8Abbrev;
854       }
855       bool isCStr7 = Code == bitc::CST_CODE_CSTRING;
856       bool isCStrChar6 = Code == bitc::CST_CODE_CSTRING;
857       for (unsigned i = 0; i != NumOps; ++i) {
858         unsigned char V = cast<ConstantInt>(CA->getOperand(i))->getZExtValue();
859         Record.push_back(V);
860         isCStr7 &= (V & 128) == 0;
861         if (isCStrChar6)
862           isCStrChar6 = BitCodeAbbrevOp::isChar6(V);
863       }
864
865       if (isCStrChar6)
866         AbbrevToUse = CString6Abbrev;
867       else if (isCStr7)
868         AbbrevToUse = CString7Abbrev;
869     } else if (isa<ConstantArray>(C) || isa<ConstantStruct>(V) ||
870                isa<ConstantVector>(V)) {
871       Code = bitc::CST_CODE_AGGREGATE;
872       for (unsigned i = 0, e = C->getNumOperands(); i != e; ++i)
873         Record.push_back(VE.getValueID(C->getOperand(i)));
874       AbbrevToUse = AggregateAbbrev;
875     } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
876       switch (CE->getOpcode()) {
877       default:
878         if (Instruction::isCast(CE->getOpcode())) {
879           Code = bitc::CST_CODE_CE_CAST;
880           Record.push_back(GetEncodedCastOpcode(CE->getOpcode()));
881           Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
882           Record.push_back(VE.getValueID(C->getOperand(0)));
883           AbbrevToUse = CONSTANTS_CE_CAST_Abbrev;
884         } else {
885           assert(CE->getNumOperands() == 2 && "Unknown constant expr!");
886           Code = bitc::CST_CODE_CE_BINOP;
887           Record.push_back(GetEncodedBinaryOpcode(CE->getOpcode()));
888           Record.push_back(VE.getValueID(C->getOperand(0)));
889           Record.push_back(VE.getValueID(C->getOperand(1)));
890           uint64_t Flags = GetOptimizationFlags(CE);
891           if (Flags != 0)
892             Record.push_back(Flags);
893         }
894         break;
895       case Instruction::GetElementPtr:
896         Code = bitc::CST_CODE_CE_GEP;
897         if (cast<GEPOperator>(C)->isInBounds())
898           Code = bitc::CST_CODE_CE_INBOUNDS_GEP;
899         for (unsigned i = 0, e = CE->getNumOperands(); i != e; ++i) {
900           Record.push_back(VE.getTypeID(C->getOperand(i)->getType()));
901           Record.push_back(VE.getValueID(C->getOperand(i)));
902         }
903         break;
904       case Instruction::Select:
905         Code = bitc::CST_CODE_CE_SELECT;
906         Record.push_back(VE.getValueID(C->getOperand(0)));
907         Record.push_back(VE.getValueID(C->getOperand(1)));
908         Record.push_back(VE.getValueID(C->getOperand(2)));
909         break;
910       case Instruction::ExtractElement:
911         Code = bitc::CST_CODE_CE_EXTRACTELT;
912         Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
913         Record.push_back(VE.getValueID(C->getOperand(0)));
914         Record.push_back(VE.getValueID(C->getOperand(1)));
915         break;
916       case Instruction::InsertElement:
917         Code = bitc::CST_CODE_CE_INSERTELT;
918         Record.push_back(VE.getValueID(C->getOperand(0)));
919         Record.push_back(VE.getValueID(C->getOperand(1)));
920         Record.push_back(VE.getValueID(C->getOperand(2)));
921         break;
922       case Instruction::ShuffleVector:
923         // If the return type and argument types are the same, this is a
924         // standard shufflevector instruction.  If the types are different,
925         // then the shuffle is widening or truncating the input vectors, and
926         // the argument type must also be encoded.
927         if (C->getType() == C->getOperand(0)->getType()) {
928           Code = bitc::CST_CODE_CE_SHUFFLEVEC;
929         } else {
930           Code = bitc::CST_CODE_CE_SHUFVEC_EX;
931           Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
932         }
933         Record.push_back(VE.getValueID(C->getOperand(0)));
934         Record.push_back(VE.getValueID(C->getOperand(1)));
935         Record.push_back(VE.getValueID(C->getOperand(2)));
936         break;
937       case Instruction::ICmp:
938       case Instruction::FCmp:
939         Code = bitc::CST_CODE_CE_CMP;
940         Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
941         Record.push_back(VE.getValueID(C->getOperand(0)));
942         Record.push_back(VE.getValueID(C->getOperand(1)));
943         Record.push_back(CE->getPredicate());
944         break;
945       }
946     } else if (const BlockAddress *BA = dyn_cast<BlockAddress>(C)) {
947       Code = bitc::CST_CODE_BLOCKADDRESS;
948       Record.push_back(VE.getTypeID(BA->getFunction()->getType()));
949       Record.push_back(VE.getValueID(BA->getFunction()));
950       Record.push_back(VE.getGlobalBasicBlockID(BA->getBasicBlock()));
951     } else {
952 #ifndef NDEBUG
953       C->dump();
954 #endif
955       llvm_unreachable("Unknown constant!");
956     }
957     Stream.EmitRecord(Code, Record, AbbrevToUse);
958     Record.clear();
959   }
960
961   Stream.ExitBlock();
962 }
963
964 static void WriteModuleConstants(const ValueEnumerator &VE,
965                                  BitstreamWriter &Stream) {
966   const ValueEnumerator::ValueList &Vals = VE.getValues();
967
968   // Find the first constant to emit, which is the first non-globalvalue value.
969   // We know globalvalues have been emitted by WriteModuleInfo.
970   for (unsigned i = 0, e = Vals.size(); i != e; ++i) {
971     if (!isa<GlobalValue>(Vals[i].first)) {
972       WriteConstants(i, Vals.size(), VE, Stream, true);
973       return;
974     }
975   }
976 }
977
978 /// PushValueAndType - The file has to encode both the value and type id for
979 /// many values, because we need to know what type to create for forward
980 /// references.  However, most operands are not forward references, so this type
981 /// field is not needed.
982 ///
983 /// This function adds V's value ID to Vals.  If the value ID is higher than the
984 /// instruction ID, then it is a forward reference, and it also includes the
985 /// type ID.
986 static bool PushValueAndType(const Value *V, unsigned InstID,
987                              SmallVector<unsigned, 64> &Vals,
988                              ValueEnumerator &VE) {
989   unsigned ValID = VE.getValueID(V);
990   Vals.push_back(ValID);
991   if (ValID >= InstID) {
992     Vals.push_back(VE.getTypeID(V->getType()));
993     return true;
994   }
995   return false;
996 }
997
998 /// WriteInstruction - Emit an instruction to the specified stream.
999 static void WriteInstruction(const Instruction &I, unsigned InstID,
1000                              ValueEnumerator &VE, BitstreamWriter &Stream,
1001                              SmallVector<unsigned, 64> &Vals) {
1002   unsigned Code = 0;
1003   unsigned AbbrevToUse = 0;
1004   VE.setInstructionID(&I);
1005   switch (I.getOpcode()) {
1006   default:
1007     if (Instruction::isCast(I.getOpcode())) {
1008       Code = bitc::FUNC_CODE_INST_CAST;
1009       if (!PushValueAndType(I.getOperand(0), InstID, Vals, VE))
1010         AbbrevToUse = FUNCTION_INST_CAST_ABBREV;
1011       Vals.push_back(VE.getTypeID(I.getType()));
1012       Vals.push_back(GetEncodedCastOpcode(I.getOpcode()));
1013     } else {
1014       assert(isa<BinaryOperator>(I) && "Unknown instruction!");
1015       Code = bitc::FUNC_CODE_INST_BINOP;
1016       if (!PushValueAndType(I.getOperand(0), InstID, Vals, VE))
1017         AbbrevToUse = FUNCTION_INST_BINOP_ABBREV;
1018       Vals.push_back(VE.getValueID(I.getOperand(1)));
1019       Vals.push_back(GetEncodedBinaryOpcode(I.getOpcode()));
1020       uint64_t Flags = GetOptimizationFlags(&I);
1021       if (Flags != 0) {
1022         if (AbbrevToUse == FUNCTION_INST_BINOP_ABBREV)
1023           AbbrevToUse = FUNCTION_INST_BINOP_FLAGS_ABBREV;
1024         Vals.push_back(Flags);
1025       }
1026     }
1027     break;
1028
1029   case Instruction::GetElementPtr:
1030     Code = bitc::FUNC_CODE_INST_GEP;
1031     if (cast<GEPOperator>(&I)->isInBounds())
1032       Code = bitc::FUNC_CODE_INST_INBOUNDS_GEP;
1033     for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
1034       PushValueAndType(I.getOperand(i), InstID, Vals, VE);
1035     break;
1036   case Instruction::ExtractValue: {
1037     Code = bitc::FUNC_CODE_INST_EXTRACTVAL;
1038     PushValueAndType(I.getOperand(0), InstID, Vals, VE);
1039     const ExtractValueInst *EVI = cast<ExtractValueInst>(&I);
1040     for (const unsigned *i = EVI->idx_begin(), *e = EVI->idx_end(); i != e; ++i)
1041       Vals.push_back(*i);
1042     break;
1043   }
1044   case Instruction::InsertValue: {
1045     Code = bitc::FUNC_CODE_INST_INSERTVAL;
1046     PushValueAndType(I.getOperand(0), InstID, Vals, VE);
1047     PushValueAndType(I.getOperand(1), InstID, Vals, VE);
1048     const InsertValueInst *IVI = cast<InsertValueInst>(&I);
1049     for (const unsigned *i = IVI->idx_begin(), *e = IVI->idx_end(); i != e; ++i)
1050       Vals.push_back(*i);
1051     break;
1052   }
1053   case Instruction::Select:
1054     Code = bitc::FUNC_CODE_INST_VSELECT;
1055     PushValueAndType(I.getOperand(1), InstID, Vals, VE);
1056     Vals.push_back(VE.getValueID(I.getOperand(2)));
1057     PushValueAndType(I.getOperand(0), InstID, Vals, VE);
1058     break;
1059   case Instruction::ExtractElement:
1060     Code = bitc::FUNC_CODE_INST_EXTRACTELT;
1061     PushValueAndType(I.getOperand(0), InstID, Vals, VE);
1062     Vals.push_back(VE.getValueID(I.getOperand(1)));
1063     break;
1064   case Instruction::InsertElement:
1065     Code = bitc::FUNC_CODE_INST_INSERTELT;
1066     PushValueAndType(I.getOperand(0), InstID, Vals, VE);
1067     Vals.push_back(VE.getValueID(I.getOperand(1)));
1068     Vals.push_back(VE.getValueID(I.getOperand(2)));
1069     break;
1070   case Instruction::ShuffleVector:
1071     Code = bitc::FUNC_CODE_INST_SHUFFLEVEC;
1072     PushValueAndType(I.getOperand(0), InstID, Vals, VE);
1073     Vals.push_back(VE.getValueID(I.getOperand(1)));
1074     Vals.push_back(VE.getValueID(I.getOperand(2)));
1075     break;
1076   case Instruction::ICmp:
1077   case Instruction::FCmp:
1078     // compare returning Int1Ty or vector of Int1Ty
1079     Code = bitc::FUNC_CODE_INST_CMP2;
1080     PushValueAndType(I.getOperand(0), InstID, Vals, VE);
1081     Vals.push_back(VE.getValueID(I.getOperand(1)));
1082     Vals.push_back(cast<CmpInst>(I).getPredicate());
1083     break;
1084
1085   case Instruction::Ret:
1086     {
1087       Code = bitc::FUNC_CODE_INST_RET;
1088       unsigned NumOperands = I.getNumOperands();
1089       if (NumOperands == 0)
1090         AbbrevToUse = FUNCTION_INST_RET_VOID_ABBREV;
1091       else if (NumOperands == 1) {
1092         if (!PushValueAndType(I.getOperand(0), InstID, Vals, VE))
1093           AbbrevToUse = FUNCTION_INST_RET_VAL_ABBREV;
1094       } else {
1095         for (unsigned i = 0, e = NumOperands; i != e; ++i)
1096           PushValueAndType(I.getOperand(i), InstID, Vals, VE);
1097       }
1098     }
1099     break;
1100   case Instruction::Br:
1101     {
1102       Code = bitc::FUNC_CODE_INST_BR;
1103       BranchInst &II = cast<BranchInst>(I);
1104       Vals.push_back(VE.getValueID(II.getSuccessor(0)));
1105       if (II.isConditional()) {
1106         Vals.push_back(VE.getValueID(II.getSuccessor(1)));
1107         Vals.push_back(VE.getValueID(II.getCondition()));
1108       }
1109     }
1110     break;
1111   case Instruction::Switch:
1112     Code = bitc::FUNC_CODE_INST_SWITCH;
1113     Vals.push_back(VE.getTypeID(I.getOperand(0)->getType()));
1114     for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
1115       Vals.push_back(VE.getValueID(I.getOperand(i)));
1116     break;
1117   case Instruction::IndirectBr:
1118     Code = bitc::FUNC_CODE_INST_INDIRECTBR;
1119     Vals.push_back(VE.getTypeID(I.getOperand(0)->getType()));
1120     for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
1121       Vals.push_back(VE.getValueID(I.getOperand(i)));
1122     break;
1123       
1124   case Instruction::Invoke: {
1125     const InvokeInst *II = cast<InvokeInst>(&I);
1126     const Value *Callee(II->getCalledValue());
1127     PointerType *PTy = cast<PointerType>(Callee->getType());
1128     FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
1129     Code = bitc::FUNC_CODE_INST_INVOKE;
1130
1131     Vals.push_back(VE.getAttributeID(II->getAttributes()));
1132     Vals.push_back(II->getCallingConv());
1133     Vals.push_back(VE.getValueID(II->getNormalDest()));
1134     Vals.push_back(VE.getValueID(II->getUnwindDest()));
1135     PushValueAndType(Callee, InstID, Vals, VE);
1136
1137     // Emit value #'s for the fixed parameters.
1138     for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
1139       Vals.push_back(VE.getValueID(I.getOperand(i)));  // fixed param.
1140
1141     // Emit type/value pairs for varargs params.
1142     if (FTy->isVarArg()) {
1143       for (unsigned i = FTy->getNumParams(), e = I.getNumOperands()-3;
1144            i != e; ++i)
1145         PushValueAndType(I.getOperand(i), InstID, Vals, VE); // vararg
1146     }
1147     break;
1148   }
1149   case Instruction::Resume:
1150     Code = bitc::FUNC_CODE_INST_RESUME;
1151     PushValueAndType(I.getOperand(0), InstID, Vals, VE);
1152     break;
1153   case Instruction::Unwind:
1154     Code = bitc::FUNC_CODE_INST_UNWIND;
1155     break;
1156   case Instruction::Unreachable:
1157     Code = bitc::FUNC_CODE_INST_UNREACHABLE;
1158     AbbrevToUse = FUNCTION_INST_UNREACHABLE_ABBREV;
1159     break;
1160
1161   case Instruction::PHI: {
1162     const PHINode &PN = cast<PHINode>(I);
1163     Code = bitc::FUNC_CODE_INST_PHI;
1164     Vals.push_back(VE.getTypeID(PN.getType()));
1165     for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
1166       Vals.push_back(VE.getValueID(PN.getIncomingValue(i)));
1167       Vals.push_back(VE.getValueID(PN.getIncomingBlock(i)));
1168     }
1169     break;
1170   }
1171
1172   case Instruction::LandingPad: {
1173     const LandingPadInst &LP = cast<LandingPadInst>(I);
1174     Code = bitc::FUNC_CODE_INST_LANDINGPAD;
1175     Vals.push_back(VE.getTypeID(LP.getType()));
1176     PushValueAndType(LP.getPersonalityFn(), InstID, Vals, VE);
1177     Vals.push_back(LP.isCleanup());
1178     Vals.push_back(LP.getNumClauses());
1179     for (unsigned I = 0, E = LP.getNumClauses(); I != E; ++I) {
1180       if (LP.isCatch(I))
1181         Vals.push_back(LandingPadInst::Catch);
1182       else
1183         Vals.push_back(LandingPadInst::Filter);
1184       PushValueAndType(LP.getClause(I), InstID, Vals, VE);
1185     }
1186     break;
1187   }
1188
1189   case Instruction::Alloca:
1190     Code = bitc::FUNC_CODE_INST_ALLOCA;
1191     Vals.push_back(VE.getTypeID(I.getType()));
1192     Vals.push_back(VE.getTypeID(I.getOperand(0)->getType()));
1193     Vals.push_back(VE.getValueID(I.getOperand(0))); // size.
1194     Vals.push_back(Log2_32(cast<AllocaInst>(I).getAlignment())+1);
1195     break;
1196
1197   case Instruction::Load:
1198     if (cast<LoadInst>(I).isAtomic()) {
1199       Code = bitc::FUNC_CODE_INST_LOADATOMIC;
1200       PushValueAndType(I.getOperand(0), InstID, Vals, VE);
1201     } else {
1202       Code = bitc::FUNC_CODE_INST_LOAD;
1203       if (!PushValueAndType(I.getOperand(0), InstID, Vals, VE))  // ptr
1204         AbbrevToUse = FUNCTION_INST_LOAD_ABBREV;
1205     }
1206     Vals.push_back(Log2_32(cast<LoadInst>(I).getAlignment())+1);
1207     Vals.push_back(cast<LoadInst>(I).isVolatile());
1208     if (cast<LoadInst>(I).isAtomic()) {
1209       Vals.push_back(GetEncodedOrdering(cast<LoadInst>(I).getOrdering()));
1210       Vals.push_back(GetEncodedSynchScope(cast<LoadInst>(I).getSynchScope()));
1211     }
1212     break;
1213   case Instruction::Store:
1214     if (cast<StoreInst>(I).isAtomic())
1215       Code = bitc::FUNC_CODE_INST_STOREATOMIC;
1216     else
1217       Code = bitc::FUNC_CODE_INST_STORE;
1218     PushValueAndType(I.getOperand(1), InstID, Vals, VE);  // ptrty + ptr
1219     Vals.push_back(VE.getValueID(I.getOperand(0)));       // val.
1220     Vals.push_back(Log2_32(cast<StoreInst>(I).getAlignment())+1);
1221     Vals.push_back(cast<StoreInst>(I).isVolatile());
1222     if (cast<StoreInst>(I).isAtomic()) {
1223       Vals.push_back(GetEncodedOrdering(cast<StoreInst>(I).getOrdering()));
1224       Vals.push_back(GetEncodedSynchScope(cast<StoreInst>(I).getSynchScope()));
1225     }
1226     break;
1227   case Instruction::AtomicCmpXchg:
1228     Code = bitc::FUNC_CODE_INST_CMPXCHG;
1229     PushValueAndType(I.getOperand(0), InstID, Vals, VE);  // ptrty + ptr
1230     Vals.push_back(VE.getValueID(I.getOperand(1)));       // cmp.
1231     Vals.push_back(VE.getValueID(I.getOperand(2)));       // newval.
1232     Vals.push_back(cast<AtomicCmpXchgInst>(I).isVolatile());
1233     Vals.push_back(GetEncodedOrdering(
1234                      cast<AtomicCmpXchgInst>(I).getOrdering()));
1235     Vals.push_back(GetEncodedSynchScope(
1236                      cast<AtomicCmpXchgInst>(I).getSynchScope()));
1237     break;
1238   case Instruction::AtomicRMW:
1239     Code = bitc::FUNC_CODE_INST_ATOMICRMW;
1240     PushValueAndType(I.getOperand(0), InstID, Vals, VE);  // ptrty + ptr
1241     Vals.push_back(VE.getValueID(I.getOperand(1)));       // val.
1242     Vals.push_back(GetEncodedRMWOperation(
1243                      cast<AtomicRMWInst>(I).getOperation()));
1244     Vals.push_back(cast<AtomicRMWInst>(I).isVolatile());
1245     Vals.push_back(GetEncodedOrdering(cast<AtomicRMWInst>(I).getOrdering()));
1246     Vals.push_back(GetEncodedSynchScope(
1247                      cast<AtomicRMWInst>(I).getSynchScope()));
1248     break;
1249   case Instruction::Fence:
1250     Code = bitc::FUNC_CODE_INST_FENCE;
1251     Vals.push_back(GetEncodedOrdering(cast<FenceInst>(I).getOrdering()));
1252     Vals.push_back(GetEncodedSynchScope(cast<FenceInst>(I).getSynchScope()));
1253     break;
1254   case Instruction::Call: {
1255     const CallInst &CI = cast<CallInst>(I);
1256     PointerType *PTy = cast<PointerType>(CI.getCalledValue()->getType());
1257     FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
1258
1259     Code = bitc::FUNC_CODE_INST_CALL;
1260
1261     Vals.push_back(VE.getAttributeID(CI.getAttributes()));
1262     Vals.push_back((CI.getCallingConv() << 1) | unsigned(CI.isTailCall()));
1263     PushValueAndType(CI.getCalledValue(), InstID, Vals, VE);  // Callee
1264
1265     // Emit value #'s for the fixed parameters.
1266     for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
1267       Vals.push_back(VE.getValueID(CI.getArgOperand(i)));  // fixed param.
1268
1269     // Emit type/value pairs for varargs params.
1270     if (FTy->isVarArg()) {
1271       for (unsigned i = FTy->getNumParams(), e = CI.getNumArgOperands();
1272            i != e; ++i)
1273         PushValueAndType(CI.getArgOperand(i), InstID, Vals, VE);  // varargs
1274     }
1275     break;
1276   }
1277   case Instruction::VAArg:
1278     Code = bitc::FUNC_CODE_INST_VAARG;
1279     Vals.push_back(VE.getTypeID(I.getOperand(0)->getType()));   // valistty
1280     Vals.push_back(VE.getValueID(I.getOperand(0))); // valist.
1281     Vals.push_back(VE.getTypeID(I.getType())); // restype.
1282     break;
1283   }
1284
1285   Stream.EmitRecord(Code, Vals, AbbrevToUse);
1286   Vals.clear();
1287 }
1288
1289 // Emit names for globals/functions etc.
1290 static void WriteValueSymbolTable(const ValueSymbolTable &VST,
1291                                   const ValueEnumerator &VE,
1292                                   BitstreamWriter &Stream) {
1293   if (VST.empty()) return;
1294   Stream.EnterSubblock(bitc::VALUE_SYMTAB_BLOCK_ID, 4);
1295
1296   // FIXME: Set up the abbrev, we know how many values there are!
1297   // FIXME: We know if the type names can use 7-bit ascii.
1298   SmallVector<unsigned, 64> NameVals;
1299
1300   for (ValueSymbolTable::const_iterator SI = VST.begin(), SE = VST.end();
1301        SI != SE; ++SI) {
1302
1303     const ValueName &Name = *SI;
1304
1305     // Figure out the encoding to use for the name.
1306     bool is7Bit = true;
1307     bool isChar6 = true;
1308     for (const char *C = Name.getKeyData(), *E = C+Name.getKeyLength();
1309          C != E; ++C) {
1310       if (isChar6)
1311         isChar6 = BitCodeAbbrevOp::isChar6(*C);
1312       if ((unsigned char)*C & 128) {
1313         is7Bit = false;
1314         break;  // don't bother scanning the rest.
1315       }
1316     }
1317
1318     unsigned AbbrevToUse = VST_ENTRY_8_ABBREV;
1319
1320     // VST_ENTRY:   [valueid, namechar x N]
1321     // VST_BBENTRY: [bbid, namechar x N]
1322     unsigned Code;
1323     if (isa<BasicBlock>(SI->getValue())) {
1324       Code = bitc::VST_CODE_BBENTRY;
1325       if (isChar6)
1326         AbbrevToUse = VST_BBENTRY_6_ABBREV;
1327     } else {
1328       Code = bitc::VST_CODE_ENTRY;
1329       if (isChar6)
1330         AbbrevToUse = VST_ENTRY_6_ABBREV;
1331       else if (is7Bit)
1332         AbbrevToUse = VST_ENTRY_7_ABBREV;
1333     }
1334
1335     NameVals.push_back(VE.getValueID(SI->getValue()));
1336     for (const char *P = Name.getKeyData(),
1337          *E = Name.getKeyData()+Name.getKeyLength(); P != E; ++P)
1338       NameVals.push_back((unsigned char)*P);
1339
1340     // Emit the finished record.
1341     Stream.EmitRecord(Code, NameVals, AbbrevToUse);
1342     NameVals.clear();
1343   }
1344   Stream.ExitBlock();
1345 }
1346
1347 /// WriteFunction - Emit a function body to the module stream.
1348 static void WriteFunction(const Function &F, ValueEnumerator &VE,
1349                           BitstreamWriter &Stream) {
1350   Stream.EnterSubblock(bitc::FUNCTION_BLOCK_ID, 4);
1351   VE.incorporateFunction(F);
1352
1353   SmallVector<unsigned, 64> Vals;
1354
1355   // Emit the number of basic blocks, so the reader can create them ahead of
1356   // time.
1357   Vals.push_back(VE.getBasicBlocks().size());
1358   Stream.EmitRecord(bitc::FUNC_CODE_DECLAREBLOCKS, Vals);
1359   Vals.clear();
1360
1361   // If there are function-local constants, emit them now.
1362   unsigned CstStart, CstEnd;
1363   VE.getFunctionConstantRange(CstStart, CstEnd);
1364   WriteConstants(CstStart, CstEnd, VE, Stream, false);
1365
1366   // If there is function-local metadata, emit it now.
1367   WriteFunctionLocalMetadata(F, VE, Stream);
1368
1369   // Keep a running idea of what the instruction ID is.
1370   unsigned InstID = CstEnd;
1371
1372   bool NeedsMetadataAttachment = false;
1373   
1374   DebugLoc LastDL;
1375   
1376   // Finally, emit all the instructions, in order.
1377   for (Function::const_iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
1378     for (BasicBlock::const_iterator I = BB->begin(), E = BB->end();
1379          I != E; ++I) {
1380       WriteInstruction(*I, InstID, VE, Stream, Vals);
1381       
1382       if (!I->getType()->isVoidTy())
1383         ++InstID;
1384       
1385       // If the instruction has metadata, write a metadata attachment later.
1386       NeedsMetadataAttachment |= I->hasMetadataOtherThanDebugLoc();
1387       
1388       // If the instruction has a debug location, emit it.
1389       DebugLoc DL = I->getDebugLoc();
1390       if (DL.isUnknown()) {
1391         // nothing todo.
1392       } else if (DL == LastDL) {
1393         // Just repeat the same debug loc as last time.
1394         Stream.EmitRecord(bitc::FUNC_CODE_DEBUG_LOC_AGAIN, Vals);
1395       } else {
1396         MDNode *Scope, *IA;
1397         DL.getScopeAndInlinedAt(Scope, IA, I->getContext());
1398         
1399         Vals.push_back(DL.getLine());
1400         Vals.push_back(DL.getCol());
1401         Vals.push_back(Scope ? VE.getValueID(Scope)+1 : 0);
1402         Vals.push_back(IA ? VE.getValueID(IA)+1 : 0);
1403         Stream.EmitRecord(bitc::FUNC_CODE_DEBUG_LOC, Vals);
1404         Vals.clear();
1405         
1406         LastDL = DL;
1407       }
1408     }
1409
1410   // Emit names for all the instructions etc.
1411   WriteValueSymbolTable(F.getValueSymbolTable(), VE, Stream);
1412
1413   if (NeedsMetadataAttachment)
1414     WriteMetadataAttachment(F, VE, Stream);
1415   VE.purgeFunction();
1416   Stream.ExitBlock();
1417 }
1418
1419 // Emit blockinfo, which defines the standard abbreviations etc.
1420 static void WriteBlockInfo(const ValueEnumerator &VE, BitstreamWriter &Stream) {
1421   // We only want to emit block info records for blocks that have multiple
1422   // instances: CONSTANTS_BLOCK, FUNCTION_BLOCK and VALUE_SYMTAB_BLOCK.  Other
1423   // blocks can defined their abbrevs inline.
1424   Stream.EnterBlockInfoBlock(2);
1425
1426   { // 8-bit fixed-width VST_ENTRY/VST_BBENTRY strings.
1427     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1428     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 3));
1429     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
1430     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1431     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
1432     if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID,
1433                                    Abbv) != VST_ENTRY_8_ABBREV)
1434       llvm_unreachable("Unexpected abbrev ordering!");
1435   }
1436
1437   { // 7-bit fixed width VST_ENTRY strings.
1438     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1439     Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_ENTRY));
1440     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
1441     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1442     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7));
1443     if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID,
1444                                    Abbv) != VST_ENTRY_7_ABBREV)
1445       llvm_unreachable("Unexpected abbrev ordering!");
1446   }
1447   { // 6-bit char6 VST_ENTRY strings.
1448     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1449     Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_ENTRY));
1450     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
1451     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1452     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
1453     if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID,
1454                                    Abbv) != VST_ENTRY_6_ABBREV)
1455       llvm_unreachable("Unexpected abbrev ordering!");
1456   }
1457   { // 6-bit char6 VST_BBENTRY strings.
1458     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1459     Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_BBENTRY));
1460     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
1461     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1462     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
1463     if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID,
1464                                    Abbv) != VST_BBENTRY_6_ABBREV)
1465       llvm_unreachable("Unexpected abbrev ordering!");
1466   }
1467
1468
1469
1470   { // SETTYPE abbrev for CONSTANTS_BLOCK.
1471     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1472     Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_SETTYPE));
1473     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
1474                               Log2_32_Ceil(VE.getTypes().size()+1)));
1475     if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID,
1476                                    Abbv) != CONSTANTS_SETTYPE_ABBREV)
1477       llvm_unreachable("Unexpected abbrev ordering!");
1478   }
1479
1480   { // INTEGER abbrev for CONSTANTS_BLOCK.
1481     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1482     Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_INTEGER));
1483     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
1484     if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID,
1485                                    Abbv) != CONSTANTS_INTEGER_ABBREV)
1486       llvm_unreachable("Unexpected abbrev ordering!");
1487   }
1488
1489   { // CE_CAST abbrev for CONSTANTS_BLOCK.
1490     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1491     Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_CE_CAST));
1492     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4));  // cast opc
1493     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,       // typeid
1494                               Log2_32_Ceil(VE.getTypes().size()+1)));
1495     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));    // value id
1496
1497     if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID,
1498                                    Abbv) != CONSTANTS_CE_CAST_Abbrev)
1499       llvm_unreachable("Unexpected abbrev ordering!");
1500   }
1501   { // NULL abbrev for CONSTANTS_BLOCK.
1502     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1503     Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_NULL));
1504     if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID,
1505                                    Abbv) != CONSTANTS_NULL_Abbrev)
1506       llvm_unreachable("Unexpected abbrev ordering!");
1507   }
1508
1509   // FIXME: This should only use space for first class types!
1510
1511   { // INST_LOAD abbrev for FUNCTION_BLOCK.
1512     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1513     Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_LOAD));
1514     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Ptr
1515     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // Align
1516     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // volatile
1517     if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
1518                                    Abbv) != FUNCTION_INST_LOAD_ABBREV)
1519       llvm_unreachable("Unexpected abbrev ordering!");
1520   }
1521   { // INST_BINOP abbrev for FUNCTION_BLOCK.
1522     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1523     Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_BINOP));
1524     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // LHS
1525     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // RHS
1526     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
1527     if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
1528                                    Abbv) != FUNCTION_INST_BINOP_ABBREV)
1529       llvm_unreachable("Unexpected abbrev ordering!");
1530   }
1531   { // INST_BINOP_FLAGS abbrev for FUNCTION_BLOCK.
1532     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1533     Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_BINOP));
1534     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // LHS
1535     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // RHS
1536     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
1537     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7)); // flags
1538     if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
1539                                    Abbv) != FUNCTION_INST_BINOP_FLAGS_ABBREV)
1540       llvm_unreachable("Unexpected abbrev ordering!");
1541   }
1542   { // INST_CAST abbrev for FUNCTION_BLOCK.
1543     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1544     Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_CAST));
1545     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));    // OpVal
1546     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,       // dest ty
1547                               Log2_32_Ceil(VE.getTypes().size()+1)));
1548     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4));  // opc
1549     if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
1550                                    Abbv) != FUNCTION_INST_CAST_ABBREV)
1551       llvm_unreachable("Unexpected abbrev ordering!");
1552   }
1553
1554   { // INST_RET abbrev for FUNCTION_BLOCK.
1555     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1556     Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_RET));
1557     if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
1558                                    Abbv) != FUNCTION_INST_RET_VOID_ABBREV)
1559       llvm_unreachable("Unexpected abbrev ordering!");
1560   }
1561   { // INST_RET abbrev for FUNCTION_BLOCK.
1562     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1563     Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_RET));
1564     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // ValID
1565     if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
1566                                    Abbv) != FUNCTION_INST_RET_VAL_ABBREV)
1567       llvm_unreachable("Unexpected abbrev ordering!");
1568   }
1569   { // INST_UNREACHABLE abbrev for FUNCTION_BLOCK.
1570     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1571     Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_UNREACHABLE));
1572     if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
1573                                    Abbv) != FUNCTION_INST_UNREACHABLE_ABBREV)
1574       llvm_unreachable("Unexpected abbrev ordering!");
1575   }
1576
1577   Stream.ExitBlock();
1578 }
1579
1580 // Sort the Users based on the order in which the reader parses the bitcode 
1581 // file.
1582 static bool bitcodereader_order(const User *lhs, const User *rhs) {
1583   // TODO: Implement.
1584   return true;
1585 }
1586
1587 static void WriteUseList(const Value *V, const ValueEnumerator &VE,
1588                          BitstreamWriter &Stream) {
1589
1590   // One or zero uses can't get out of order.
1591   if (V->use_empty() || V->hasNUses(1))
1592     return;
1593
1594   // Make a copy of the in-memory use-list for sorting.
1595   unsigned UseListSize = std::distance(V->use_begin(), V->use_end());
1596   SmallVector<const User*, 8> UseList;
1597   UseList.reserve(UseListSize);
1598   for (Value::const_use_iterator I = V->use_begin(), E = V->use_end();
1599        I != E; ++I) {
1600     const User *U = *I;
1601     UseList.push_back(U);
1602   }
1603
1604   // Sort the copy based on the order read by the BitcodeReader.
1605   std::sort(UseList.begin(), UseList.end(), bitcodereader_order);
1606
1607   // TODO: Generate a diff between the BitcodeWriter in-memory use-list and the
1608   // sorted list (i.e., the expected BitcodeReader in-memory use-list).
1609
1610   // TODO: Emit the USELIST_CODE_ENTRYs.
1611 }
1612
1613 static void WriteFunctionUseList(const Function *F, ValueEnumerator &VE,
1614                                  BitstreamWriter &Stream) {
1615   VE.incorporateFunction(*F);
1616
1617   for (Function::const_arg_iterator AI = F->arg_begin(), AE = F->arg_end();
1618        AI != AE; ++AI)
1619     WriteUseList(AI, VE, Stream);
1620   for (Function::const_iterator BB = F->begin(), FE = F->end(); BB != FE;
1621        ++BB) {
1622     WriteUseList(BB, VE, Stream);
1623     for (BasicBlock::const_iterator II = BB->begin(), IE = BB->end(); II != IE;
1624          ++II) {
1625       WriteUseList(II, VE, Stream);
1626       for (User::const_op_iterator OI = II->op_begin(), E = II->op_end();
1627            OI != E; ++OI) {
1628         if ((isa<Constant>(*OI) && !isa<GlobalValue>(*OI)) ||
1629             isa<InlineAsm>(*OI))
1630           WriteUseList(*OI, VE, Stream);
1631       }
1632     }
1633   }
1634   VE.purgeFunction();
1635 }
1636
1637 // Emit use-lists.
1638 static void WriteModuleUseLists(const Module *M, ValueEnumerator &VE,
1639                                 BitstreamWriter &Stream) {
1640   Stream.EnterSubblock(bitc::USELIST_BLOCK_ID, 3);
1641
1642   // XXX: this modifies the module, but in a way that should never change the
1643   // behavior of any pass or codegen in LLVM. The problem is that GVs may
1644   // contain entries in the use_list that do not exist in the Module and are
1645   // not stored in the .bc file.
1646   for (Module::const_global_iterator I = M->global_begin(), E = M->global_end();
1647        I != E; ++I)
1648     I->removeDeadConstantUsers();
1649   
1650   // Write the global variables.
1651   for (Module::const_global_iterator GI = M->global_begin(), 
1652          GE = M->global_end(); GI != GE; ++GI) {
1653     WriteUseList(GI, VE, Stream);
1654
1655     // Write the global variable initializers.
1656     if (GI->hasInitializer())
1657       WriteUseList(GI->getInitializer(), VE, Stream);
1658   }
1659
1660   // Write the functions.
1661   for (Module::const_iterator FI = M->begin(), FE = M->end(); FI != FE; ++FI) {
1662     WriteUseList(FI, VE, Stream);
1663     if (!FI->isDeclaration())
1664       WriteFunctionUseList(FI, VE, Stream);
1665   }
1666
1667   // Write the aliases.
1668   for (Module::const_alias_iterator AI = M->alias_begin(), AE = M->alias_end();
1669        AI != AE; ++AI) {
1670     WriteUseList(AI, VE, Stream);
1671     WriteUseList(AI->getAliasee(), VE, Stream);
1672   }
1673
1674   Stream.ExitBlock();
1675 }
1676
1677 /// WriteModule - Emit the specified module to the bitstream.
1678 static void WriteModule(const Module *M, BitstreamWriter &Stream) {
1679   Stream.EnterSubblock(bitc::MODULE_BLOCK_ID, 3);
1680
1681   // Emit the version number if it is non-zero.
1682   if (CurVersion) {
1683     SmallVector<unsigned, 1> Vals;
1684     Vals.push_back(CurVersion);
1685     Stream.EmitRecord(bitc::MODULE_CODE_VERSION, Vals);
1686   }
1687
1688   // Analyze the module, enumerating globals, functions, etc.
1689   ValueEnumerator VE(M);
1690
1691   // Emit blockinfo, which defines the standard abbreviations etc.
1692   WriteBlockInfo(VE, Stream);
1693
1694   // Emit information about parameter attributes.
1695   WriteAttributeTable(VE, Stream);
1696
1697   // Emit information describing all of the types in the module.
1698   WriteTypeTable(VE, Stream);
1699
1700   // Emit top-level description of module, including target triple, inline asm,
1701   // descriptors for global variables, and function prototype info.
1702   WriteModuleInfo(M, VE, Stream);
1703
1704   // Emit constants.
1705   WriteModuleConstants(VE, Stream);
1706
1707   // Emit metadata.
1708   WriteModuleMetadata(M, VE, Stream);
1709
1710   // Emit function bodies.
1711   for (Module::const_iterator F = M->begin(), E = M->end(); F != E; ++F)
1712     if (!F->isDeclaration())
1713       WriteFunction(*F, VE, Stream);
1714
1715   // Emit metadata.
1716   WriteModuleMetadataStore(M, Stream);
1717
1718   // Emit names for globals/functions etc.
1719   WriteValueSymbolTable(M->getValueSymbolTable(), VE, Stream);
1720
1721   // Emit use-lists.
1722   if (EnablePreserveUseListOrdering)
1723     WriteModuleUseLists(M, VE, Stream);
1724
1725   Stream.ExitBlock();
1726 }
1727
1728 /// EmitDarwinBCHeader - If generating a bc file on darwin, we have to emit a
1729 /// header and trailer to make it compatible with the system archiver.  To do
1730 /// this we emit the following header, and then emit a trailer that pads the
1731 /// file out to be a multiple of 16 bytes.
1732 ///
1733 /// struct bc_header {
1734 ///   uint32_t Magic;         // 0x0B17C0DE
1735 ///   uint32_t Version;       // Version, currently always 0.
1736 ///   uint32_t BitcodeOffset; // Offset to traditional bitcode file.
1737 ///   uint32_t BitcodeSize;   // Size of traditional bitcode file.
1738 ///   uint32_t CPUType;       // CPU specifier.
1739 ///   ... potentially more later ...
1740 /// };
1741 enum {
1742   DarwinBCSizeFieldOffset = 3*4, // Offset to bitcode_size.
1743   DarwinBCHeaderSize = 5*4
1744 };
1745
1746 static void EmitDarwinBCHeader(BitstreamWriter &Stream, const Triple &TT) {
1747   unsigned CPUType = ~0U;
1748
1749   // Match x86_64-*, i[3-9]86-*, powerpc-*, powerpc64-*, arm-*, thumb-*,
1750   // armv[0-9]-*, thumbv[0-9]-*, armv5te-*, or armv6t2-*. The CPUType is a magic
1751   // number from /usr/include/mach/machine.h.  It is ok to reproduce the
1752   // specific constants here because they are implicitly part of the Darwin ABI.
1753   enum {
1754     DARWIN_CPU_ARCH_ABI64      = 0x01000000,
1755     DARWIN_CPU_TYPE_X86        = 7,
1756     DARWIN_CPU_TYPE_ARM        = 12,
1757     DARWIN_CPU_TYPE_POWERPC    = 18
1758   };
1759
1760   Triple::ArchType Arch = TT.getArch();
1761   if (Arch == Triple::x86_64)
1762     CPUType = DARWIN_CPU_TYPE_X86 | DARWIN_CPU_ARCH_ABI64;
1763   else if (Arch == Triple::x86)
1764     CPUType = DARWIN_CPU_TYPE_X86;
1765   else if (Arch == Triple::ppc)
1766     CPUType = DARWIN_CPU_TYPE_POWERPC;
1767   else if (Arch == Triple::ppc64)
1768     CPUType = DARWIN_CPU_TYPE_POWERPC | DARWIN_CPU_ARCH_ABI64;
1769   else if (Arch == Triple::arm || Arch == Triple::thumb)
1770     CPUType = DARWIN_CPU_TYPE_ARM;
1771
1772   // Traditional Bitcode starts after header.
1773   unsigned BCOffset = DarwinBCHeaderSize;
1774
1775   Stream.Emit(0x0B17C0DE, 32);
1776   Stream.Emit(0         , 32);  // Version.
1777   Stream.Emit(BCOffset  , 32);
1778   Stream.Emit(0         , 32);  // Filled in later.
1779   Stream.Emit(CPUType   , 32);
1780 }
1781
1782 /// EmitDarwinBCTrailer - Emit the darwin epilog after the bitcode file and
1783 /// finalize the header.
1784 static void EmitDarwinBCTrailer(BitstreamWriter &Stream, unsigned BufferSize) {
1785   // Update the size field in the header.
1786   Stream.BackpatchWord(DarwinBCSizeFieldOffset, BufferSize-DarwinBCHeaderSize);
1787
1788   // If the file is not a multiple of 16 bytes, insert dummy padding.
1789   while (BufferSize & 15) {
1790     Stream.Emit(0, 8);
1791     ++BufferSize;
1792   }
1793 }
1794
1795
1796 /// WriteBitcodeToFile - Write the specified module to the specified output
1797 /// stream.
1798 void llvm::WriteBitcodeToFile(const Module *M, raw_ostream &Out) {
1799   std::vector<unsigned char> Buffer;
1800   BitstreamWriter Stream(Buffer);
1801
1802   Buffer.reserve(256*1024);
1803
1804   WriteBitcodeToStream( M, Stream );
1805
1806   // Write the generated bitstream to "Out".
1807   Out.write((char*)&Buffer.front(), Buffer.size());
1808 }
1809
1810 /// WriteBitcodeToStream - Write the specified module to the specified output
1811 /// stream.
1812 void llvm::WriteBitcodeToStream(const Module *M, BitstreamWriter &Stream) {
1813   // If this is darwin or another generic macho target, emit a file header and
1814   // trailer if needed.
1815   Triple TT(M->getTargetTriple());
1816   if (TT.isOSDarwin())
1817     EmitDarwinBCHeader(Stream, TT);
1818
1819   // Emit the file header.
1820   Stream.Emit((unsigned)'B', 8);
1821   Stream.Emit((unsigned)'C', 8);
1822   Stream.Emit(0x0, 4);
1823   Stream.Emit(0xC, 4);
1824   Stream.Emit(0xE, 4);
1825   Stream.Emit(0xD, 4);
1826
1827   // Emit the module.
1828   WriteModule(M, Stream);
1829
1830   if (TT.isOSDarwin())
1831     EmitDarwinBCTrailer(Stream, Stream.getBuffer().size());
1832 }