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