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