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