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