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