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