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 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 ValueEnumerator &VE,
170                                 BitstreamWriter &Stream) {
171  const 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 ValueEnumerator &VE, BitstreamWriter &Stream) {
243  const ValueEnumerator::TypeList &TypeList = VE.getTypes();
244
245  Stream.EnterSubblock(TYPE_BLOCK_ID_OLD_3_0, 4 /*count from # abbrevs */);
246  SmallVector<uint64_t, 64> TypeVals;
247
248  // Abbrev for TYPE_CODE_POINTER.
249  BitCodeAbbrev *Abbv = new BitCodeAbbrev();
250  Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_POINTER));
251  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
252                            Log2_32_Ceil(VE.getTypes().size()+1)));
253  Abbv->Add(BitCodeAbbrevOp(0));  // Addrspace = 0
254  unsigned PtrAbbrev = Stream.EmitAbbrev(Abbv);
255
256  // Abbrev for TYPE_CODE_FUNCTION.
257  Abbv = new BitCodeAbbrev();
258  Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_FUNCTION_OLD));
259  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));  // isvararg
260  Abbv->Add(BitCodeAbbrevOp(0));  // FIXME: DEAD value, remove in LLVM 3.0
261  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
262  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
263                            Log2_32_Ceil(VE.getTypes().size()+1)));
264  unsigned FunctionAbbrev = Stream.EmitAbbrev(Abbv);
265
266#if 0
267  // Abbrev for TYPE_CODE_STRUCT_ANON.
268  Abbv = new BitCodeAbbrev();
269  Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_STRUCT_ANON));
270  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));  // ispacked
271  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
272  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
273                            Log2_32_Ceil(VE.getTypes().size()+1)));
274  unsigned StructAnonAbbrev = Stream.EmitAbbrev(Abbv);
275
276  // Abbrev for TYPE_CODE_STRUCT_NAME.
277  Abbv = new BitCodeAbbrev();
278  Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_STRUCT_NAME));
279  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
280  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
281  unsigned StructNameAbbrev = Stream.EmitAbbrev(Abbv);
282
283  // Abbrev for TYPE_CODE_STRUCT_NAMED.
284  Abbv = new BitCodeAbbrev();
285  Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_STRUCT_NAMED));
286  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));  // ispacked
287  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
288  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
289                            Log2_32_Ceil(VE.getTypes().size()+1)));
290  unsigned StructNamedAbbrev = Stream.EmitAbbrev(Abbv);
291#endif
292
293  // Abbrev for TYPE_CODE_STRUCT.
294  Abbv = new BitCodeAbbrev();
295  Abbv->Add(BitCodeAbbrevOp(TYPE_CODE_STRUCT_OLD_3_0));
296  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));  // ispacked
297  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
298  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
299                            Log2_32_Ceil(VE.getTypes().size()+1)));
300  unsigned StructAbbrev = Stream.EmitAbbrev(Abbv);
301
302  // Abbrev for TYPE_CODE_ARRAY.
303  Abbv = new BitCodeAbbrev();
304  Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_ARRAY));
305  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));   // size
306  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
307                            Log2_32_Ceil(VE.getTypes().size()+1)));
308  unsigned ArrayAbbrev = Stream.EmitAbbrev(Abbv);
309
310  // Emit an entry count so the reader can reserve space.
311  TypeVals.push_back(TypeList.size());
312  Stream.EmitRecord(bitc::TYPE_CODE_NUMENTRY, TypeVals);
313  TypeVals.clear();
314
315  // Loop over all of the types, emitting each in turn.
316  for (unsigned i = 0, e = TypeList.size(); i != e; ++i) {
317    Type *T = TypeList[i];
318    int AbbrevToUse = 0;
319    unsigned Code = 0;
320
321    switch (T->getTypeID()) {
322    default: llvm_unreachable("Unknown type!");
323    case Type::VoidTyID:      Code = bitc::TYPE_CODE_VOID;   break;
324    case Type::FloatTyID:     Code = bitc::TYPE_CODE_FLOAT;  break;
325    case Type::DoubleTyID:    Code = bitc::TYPE_CODE_DOUBLE; break;
326    case Type::X86_FP80TyID:  Code = bitc::TYPE_CODE_X86_FP80; break;
327    case Type::FP128TyID:     Code = bitc::TYPE_CODE_FP128; break;
328    case Type::PPC_FP128TyID: Code = bitc::TYPE_CODE_PPC_FP128; break;
329    case Type::LabelTyID:     Code = bitc::TYPE_CODE_LABEL;  break;
330    case Type::MetadataTyID:  Code = bitc::TYPE_CODE_METADATA; break;
331    case Type::X86_MMXTyID:   Code = bitc::TYPE_CODE_X86_MMX; break;
332    case Type::IntegerTyID:
333      // INTEGER: [width]
334      Code = bitc::TYPE_CODE_INTEGER;
335      TypeVals.push_back(cast<IntegerType>(T)->getBitWidth());
336      break;
337    case Type::PointerTyID: {
338      PointerType *PTy = cast<PointerType>(T);
339      // POINTER: [pointee type, address space]
340      Code = bitc::TYPE_CODE_POINTER;
341      TypeVals.push_back(VE.getTypeID(PTy->getElementType()));
342      unsigned AddressSpace = PTy->getAddressSpace();
343      TypeVals.push_back(AddressSpace);
344      if (AddressSpace == 0) AbbrevToUse = PtrAbbrev;
345      break;
346    }
347    case Type::FunctionTyID: {
348      FunctionType *FT = cast<FunctionType>(T);
349      // FUNCTION: [isvararg, attrid, retty, paramty x N]
350      Code = bitc::TYPE_CODE_FUNCTION_OLD;
351      TypeVals.push_back(FT->isVarArg());
352      TypeVals.push_back(0);  // FIXME: DEAD: remove in llvm 3.0
353      TypeVals.push_back(VE.getTypeID(FT->getReturnType()));
354      for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i)
355        TypeVals.push_back(VE.getTypeID(FT->getParamType(i)));
356      AbbrevToUse = FunctionAbbrev;
357      break;
358    }
359    case Type::StructTyID: {
360      StructType *ST = cast<StructType>(T);
361      // STRUCT: [ispacked, eltty x N]
362      TypeVals.push_back(ST->isPacked());
363      // Output all of the element types.
364      for (StructType::element_iterator I = ST->element_begin(),
365           E = ST->element_end(); I != E; ++I)
366        TypeVals.push_back(VE.getTypeID(*I));
367      AbbrevToUse = StructAbbrev;
368      break;
369    }
370    case Type::ArrayTyID: {
371      ArrayType *AT = cast<ArrayType>(T);
372      // ARRAY: [numelts, eltty]
373      Code = bitc::TYPE_CODE_ARRAY;
374      TypeVals.push_back(AT->getNumElements());
375      TypeVals.push_back(VE.getTypeID(AT->getElementType()));
376      AbbrevToUse = ArrayAbbrev;
377      break;
378    }
379    case Type::VectorTyID: {
380      VectorType *VT = cast<VectorType>(T);
381      // VECTOR [numelts, eltty]
382      Code = bitc::TYPE_CODE_VECTOR;
383      TypeVals.push_back(VT->getNumElements());
384      TypeVals.push_back(VE.getTypeID(VT->getElementType()));
385      break;
386    }
387    }
388
389    // Emit the finished record.
390    Stream.EmitRecord(Code, TypeVals, AbbrevToUse);
391    TypeVals.clear();
392  }
393
394  Stream.ExitBlock();
395
396  WriteTypeSymbolTable(VE, Stream);
397}
398
399static unsigned getEncodedLinkage(const GlobalValue *GV) {
400  switch (GV->getLinkage()) {
401  default: llvm_unreachable("Invalid linkage!");
402  case GlobalValue::ExternalLinkage:                 return 0;
403  case GlobalValue::WeakAnyLinkage:                  return 1;
404  case GlobalValue::AppendingLinkage:                return 2;
405  case GlobalValue::InternalLinkage:                 return 3;
406  case GlobalValue::LinkOnceAnyLinkage:              return 4;
407  case GlobalValue::DLLImportLinkage:                return 5;
408  case GlobalValue::DLLExportLinkage:                return 6;
409  case GlobalValue::ExternalWeakLinkage:             return 7;
410  case GlobalValue::CommonLinkage:                   return 8;
411  case GlobalValue::PrivateLinkage:                  return 9;
412  case GlobalValue::WeakODRLinkage:                  return 10;
413  case GlobalValue::LinkOnceODRLinkage:              return 11;
414  case GlobalValue::AvailableExternallyLinkage:      return 12;
415  case GlobalValue::LinkerPrivateLinkage:            return 13;
416  case GlobalValue::LinkerPrivateWeakLinkage:        return 14;
417  case GlobalValue::LinkerPrivateWeakDefAutoLinkage: return 15;
418  }
419}
420
421static unsigned getEncodedVisibility(const GlobalValue *GV) {
422  switch (GV->getVisibility()) {
423  default: llvm_unreachable("Invalid visibility!");
424  case GlobalValue::DefaultVisibility:   return 0;
425  case GlobalValue::HiddenVisibility:    return 1;
426  case GlobalValue::ProtectedVisibility: return 2;
427  }
428}
429
430// Emit top-level description of module, including target triple, inline asm,
431// descriptors for global variables, and function prototype info.
432static void WriteModuleInfo(const Module *M, const ValueEnumerator &VE,
433                            BitstreamWriter &Stream) {
434  // Emit the list of dependent libraries for the Module.
435  for (Module::lib_iterator I = M->lib_begin(), E = M->lib_end(); I != E; ++I)
436    WriteStringRecord(bitc::MODULE_CODE_DEPLIB, *I, 0/*TODO*/, Stream);
437
438  // Emit various pieces of data attached to a module.
439  if (!M->getTargetTriple().empty())
440    WriteStringRecord(bitc::MODULE_CODE_TRIPLE, M->getTargetTriple(),
441                      0/*TODO*/, Stream);
442  if (!M->getDataLayout().empty())
443    WriteStringRecord(bitc::MODULE_CODE_DATALAYOUT, M->getDataLayout(),
444                      0/*TODO*/, Stream);
445  if (!M->getModuleInlineAsm().empty())
446    WriteStringRecord(bitc::MODULE_CODE_ASM, M->getModuleInlineAsm(),
447                      0/*TODO*/, Stream);
448
449  // Emit information about sections and GC, computing how many there are. Also
450  // compute the maximum alignment value.
451  std::map<std::string, unsigned> SectionMap;
452  std::map<std::string, unsigned> GCMap;
453  unsigned MaxAlignment = 0;
454  unsigned MaxGlobalType = 0;
455  for (Module::const_global_iterator GV = M->global_begin(),E = M->global_end();
456       GV != E; ++GV) {
457    MaxAlignment = std::max(MaxAlignment, GV->getAlignment());
458    MaxGlobalType = std::max(MaxGlobalType, VE.getTypeID(GV->getType()));
459
460    if (!GV->hasSection()) continue;
461    // Give section names unique ID's.
462    unsigned &Entry = SectionMap[GV->getSection()];
463    if (Entry != 0) continue;
464    WriteStringRecord(bitc::MODULE_CODE_SECTIONNAME, GV->getSection(),
465                      0/*TODO*/, Stream);
466    Entry = SectionMap.size();
467  }
468  for (Module::const_iterator F = M->begin(), E = M->end(); F != E; ++F) {
469    MaxAlignment = std::max(MaxAlignment, F->getAlignment());
470    if (F->hasSection()) {
471      // Give section names unique ID's.
472      unsigned &Entry = SectionMap[F->getSection()];
473      if (!Entry) {
474        WriteStringRecord(bitc::MODULE_CODE_SECTIONNAME, F->getSection(),
475                          0/*TODO*/, Stream);
476        Entry = SectionMap.size();
477      }
478    }
479    if (F->hasGC()) {
480      // Same for GC names.
481      unsigned &Entry = GCMap[F->getGC()];
482      if (!Entry) {
483        WriteStringRecord(bitc::MODULE_CODE_GCNAME, F->getGC(),
484                          0/*TODO*/, Stream);
485        Entry = GCMap.size();
486      }
487    }
488  }
489
490  // Emit abbrev for globals, now that we know # sections and max alignment.
491  unsigned SimpleGVarAbbrev = 0;
492  if (!M->global_empty()) {
493    // Add an abbrev for common globals with no visibility or thread localness.
494    BitCodeAbbrev *Abbv = new BitCodeAbbrev();
495    Abbv->Add(BitCodeAbbrevOp(bitc::MODULE_CODE_GLOBALVAR));
496    Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
497                              Log2_32_Ceil(MaxGlobalType+1)));
498    Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));      // Constant.
499    Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));        // Initializer.
500    Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4));      // Linkage.
501    if (MaxAlignment == 0)                                      // Alignment.
502      Abbv->Add(BitCodeAbbrevOp(0));
503    else {
504      unsigned MaxEncAlignment = Log2_32(MaxAlignment)+1;
505      Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
506                               Log2_32_Ceil(MaxEncAlignment+1)));
507    }
508    if (SectionMap.empty())                                    // Section.
509      Abbv->Add(BitCodeAbbrevOp(0));
510    else
511      Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
512                               Log2_32_Ceil(SectionMap.size()+1)));
513    // Don't bother emitting vis + thread local.
514    SimpleGVarAbbrev = Stream.EmitAbbrev(Abbv);
515  }
516
517  // Emit the global variable information.
518  SmallVector<unsigned, 64> Vals;
519  for (Module::const_global_iterator GV = M->global_begin(),E = M->global_end();
520       GV != E; ++GV) {
521    unsigned AbbrevToUse = 0;
522
523    // GLOBALVAR: [type, isconst, initid,
524    //             linkage, alignment, section, visibility, threadlocal,
525    //             unnamed_addr]
526    Vals.push_back(VE.getTypeID(GV->getType()));
527    Vals.push_back(GV->isConstant());
528    Vals.push_back(GV->isDeclaration() ? 0 :
529                   (VE.getValueID(GV->getInitializer()) + 1));
530    Vals.push_back(getEncodedLinkage(GV));
531    Vals.push_back(Log2_32(GV->getAlignment())+1);
532    Vals.push_back(GV->hasSection() ? SectionMap[GV->getSection()] : 0);
533    if (GV->isThreadLocal() ||
534        GV->getVisibility() != GlobalValue::DefaultVisibility ||
535        GV->hasUnnamedAddr()) {
536      Vals.push_back(getEncodedVisibility(GV));
537      Vals.push_back(GV->isThreadLocal());
538      Vals.push_back(GV->hasUnnamedAddr());
539    } else {
540      AbbrevToUse = SimpleGVarAbbrev;
541    }
542
543    Stream.EmitRecord(bitc::MODULE_CODE_GLOBALVAR, Vals, AbbrevToUse);
544    Vals.clear();
545  }
546
547  // Emit the function proto information.
548  for (Module::const_iterator F = M->begin(), E = M->end(); F != E; ++F) {
549    // FUNCTION:  [type, callingconv, isproto, paramattr,
550    //             linkage, alignment, section, visibility, gc, unnamed_addr]
551    Vals.push_back(VE.getTypeID(F->getType()));
552    Vals.push_back(F->getCallingConv());
553    Vals.push_back(F->isDeclaration());
554    Vals.push_back(getEncodedLinkage(F));
555    Vals.push_back(VE.getAttributeID(F->getAttributes()));
556    Vals.push_back(Log2_32(F->getAlignment())+1);
557    Vals.push_back(F->hasSection() ? SectionMap[F->getSection()] : 0);
558    Vals.push_back(getEncodedVisibility(F));
559    Vals.push_back(F->hasGC() ? GCMap[F->getGC()] : 0);
560    Vals.push_back(F->hasUnnamedAddr());
561
562    unsigned AbbrevToUse = 0;
563    Stream.EmitRecord(bitc::MODULE_CODE_FUNCTION, Vals, AbbrevToUse);
564    Vals.clear();
565  }
566
567  // Emit the alias information.
568  for (Module::const_alias_iterator AI = M->alias_begin(), E = M->alias_end();
569       AI != E; ++AI) {
570    Vals.push_back(VE.getTypeID(AI->getType()));
571    Vals.push_back(VE.getValueID(AI->getAliasee()));
572    Vals.push_back(getEncodedLinkage(AI));
573    Vals.push_back(getEncodedVisibility(AI));
574    unsigned AbbrevToUse = 0;
575    Stream.EmitRecord(bitc::MODULE_CODE_ALIAS, Vals, AbbrevToUse);
576    Vals.clear();
577  }
578}
579
580static uint64_t GetOptimizationFlags(const Value *V) {
581  uint64_t Flags = 0;
582
583  if (const OverflowingBinaryOperator *OBO =
584        dyn_cast<OverflowingBinaryOperator>(V)) {
585    if (OBO->hasNoSignedWrap())
586      Flags |= 1 << bitc::OBO_NO_SIGNED_WRAP;
587    if (OBO->hasNoUnsignedWrap())
588      Flags |= 1 << bitc::OBO_NO_UNSIGNED_WRAP;
589  } else if (const PossiblyExactOperator *PEO =
590               dyn_cast<PossiblyExactOperator>(V)) {
591    if (PEO->isExact())
592      Flags |= 1 << bitc::PEO_EXACT;
593  }
594
595  return Flags;
596}
597
598static void WriteMDNode(const MDNode *N,
599                        const ValueEnumerator &VE,
600                        BitstreamWriter &Stream,
601                        SmallVector<uint64_t, 64> &Record) {
602  for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
603    if (N->getOperand(i)) {
604      Record.push_back(VE.getTypeID(N->getOperand(i)->getType()));
605      Record.push_back(VE.getValueID(N->getOperand(i)));
606    } else {
607      Record.push_back(VE.getTypeID(Type::getVoidTy(N->getContext())));
608      Record.push_back(0);
609    }
610  }
611  unsigned MDCode = N->isFunctionLocal() ? METADATA_FN_NODE_2_7 :
612                                           METADATA_NODE_2_7;
613  Stream.EmitRecord(MDCode, Record, 0);
614  Record.clear();
615}
616
617static void WriteModuleMetadata(const Module *M,
618                                const ValueEnumerator &VE,
619                                BitstreamWriter &Stream) {
620  const ValueEnumerator::ValueList &Vals = VE.getMDValues();
621  bool StartedMetadataBlock = false;
622  unsigned MDSAbbrev = 0;
623  SmallVector<uint64_t, 64> Record;
624  for (unsigned i = 0, e = Vals.size(); i != e; ++i) {
625
626    if (const MDNode *N = dyn_cast<MDNode>(Vals[i].first)) {
627      if (!N->isFunctionLocal() || !N->getFunction()) {
628        if (!StartedMetadataBlock) {
629          Stream.EnterSubblock(bitc::METADATA_BLOCK_ID, 3);
630          StartedMetadataBlock = true;
631        }
632        WriteMDNode(N, VE, Stream, Record);
633      }
634    } else if (const MDString *MDS = dyn_cast<MDString>(Vals[i].first)) {
635      if (!StartedMetadataBlock)  {
636        Stream.EnterSubblock(bitc::METADATA_BLOCK_ID, 3);
637
638        // Abbrev for METADATA_STRING.
639        BitCodeAbbrev *Abbv = new BitCodeAbbrev();
640        Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_STRING));
641        Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
642        Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
643        MDSAbbrev = Stream.EmitAbbrev(Abbv);
644        StartedMetadataBlock = true;
645      }
646
647      // Code: [strchar x N]
648      Record.append(MDS->begin(), MDS->end());
649
650      // Emit the finished record.
651      Stream.EmitRecord(bitc::METADATA_STRING, Record, MDSAbbrev);
652      Record.clear();
653    }
654  }
655
656  // Write named metadata.
657  for (Module::const_named_metadata_iterator I = M->named_metadata_begin(),
658       E = M->named_metadata_end(); I != E; ++I) {
659    const NamedMDNode *NMD = I;
660    if (!StartedMetadataBlock)  {
661      Stream.EnterSubblock(bitc::METADATA_BLOCK_ID, 3);
662      StartedMetadataBlock = true;
663    }
664
665    // Write name.
666    StringRef Str = NMD->getName();
667    for (unsigned i = 0, e = Str.size(); i != e; ++i)
668      Record.push_back(Str[i]);
669    Stream.EmitRecord(bitc::METADATA_NAME, Record, 0/*TODO*/);
670    Record.clear();
671
672    // Write named metadata operands.
673    for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i)
674      Record.push_back(VE.getValueID(NMD->getOperand(i)));
675    Stream.EmitRecord(METADATA_NAMED_NODE_2_7, Record, 0);
676    Record.clear();
677  }
678
679  if (StartedMetadataBlock)
680    Stream.ExitBlock();
681}
682
683static void WriteFunctionLocalMetadata(const Function &F,
684                                       const ValueEnumerator &VE,
685                                       BitstreamWriter &Stream) {
686  bool StartedMetadataBlock = false;
687  SmallVector<uint64_t, 64> Record;
688  const SmallVector<const MDNode *, 8> &Vals = VE.getFunctionLocalMDValues();
689  for (unsigned i = 0, e = Vals.size(); i != e; ++i)
690    if (const MDNode *N = Vals[i])
691      if (N->isFunctionLocal() && N->getFunction() == &F) {
692        if (!StartedMetadataBlock) {
693          Stream.EnterSubblock(bitc::METADATA_BLOCK_ID, 3);
694          StartedMetadataBlock = true;
695        }
696        WriteMDNode(N, VE, Stream, Record);
697      }
698
699  if (StartedMetadataBlock)
700    Stream.ExitBlock();
701}
702
703static void WriteMetadataAttachment(const Function &F,
704                                    const ValueEnumerator &VE,
705                                    BitstreamWriter &Stream) {
706  Stream.EnterSubblock(bitc::METADATA_ATTACHMENT_ID, 3);
707
708  SmallVector<uint64_t, 64> Record;
709
710  // Write metadata attachments
711  // METADATA_ATTACHMENT - [m x [value, [n x [id, mdnode]]]
712  SmallVector<std::pair<unsigned, MDNode*>, 4> MDs;
713
714  for (Function::const_iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
715    for (BasicBlock::const_iterator I = BB->begin(), E = BB->end();
716         I != E; ++I) {
717      MDs.clear();
718      I->getAllMetadataOtherThanDebugLoc(MDs);
719
720      // If no metadata, ignore instruction.
721      if (MDs.empty()) continue;
722
723      Record.push_back(VE.getInstructionID(I));
724
725      for (unsigned i = 0, e = MDs.size(); i != e; ++i) {
726        Record.push_back(MDs[i].first);
727        Record.push_back(VE.getValueID(MDs[i].second));
728      }
729      Stream.EmitRecord(METADATA_ATTACHMENT_2_7, Record, 0);
730      Record.clear();
731    }
732
733  Stream.ExitBlock();
734}
735
736static void WriteModuleMetadataStore(const Module *M, BitstreamWriter &Stream) {
737  SmallVector<uint64_t, 64> Record;
738
739  // Write metadata kinds
740  // METADATA_KIND - [n x [id, name]]
741  SmallVector<StringRef, 4> Names;
742  M->getMDKindNames(Names);
743
744  if (Names.empty()) return;
745
746  Stream.EnterSubblock(bitc::METADATA_BLOCK_ID, 3);
747
748  for (unsigned MDKindID = 0, e = Names.size(); MDKindID != e; ++MDKindID) {
749    Record.push_back(MDKindID);
750    StringRef KName = Names[MDKindID];
751    Record.append(KName.begin(), KName.end());
752
753    Stream.EmitRecord(bitc::METADATA_KIND, Record, 0);
754    Record.clear();
755  }
756
757  Stream.ExitBlock();
758}
759
760static void WriteConstants(unsigned FirstVal, unsigned LastVal,
761                           const ValueEnumerator &VE,
762                           BitstreamWriter &Stream, bool isGlobal) {
763  if (FirstVal == LastVal) return;
764
765  Stream.EnterSubblock(bitc::CONSTANTS_BLOCK_ID, 4);
766
767  unsigned AggregateAbbrev = 0;
768  unsigned String8Abbrev = 0;
769  unsigned CString7Abbrev = 0;
770  unsigned CString6Abbrev = 0;
771  // If this is a constant pool for the module, emit module-specific abbrevs.
772  if (isGlobal) {
773    // Abbrev for CST_CODE_AGGREGATE.
774    BitCodeAbbrev *Abbv = new BitCodeAbbrev();
775    Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_AGGREGATE));
776    Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
777    Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, Log2_32_Ceil(LastVal+1)));
778    AggregateAbbrev = Stream.EmitAbbrev(Abbv);
779
780    // Abbrev for CST_CODE_STRING.
781    Abbv = new BitCodeAbbrev();
782    Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_STRING));
783    Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
784    Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
785    String8Abbrev = Stream.EmitAbbrev(Abbv);
786    // Abbrev for CST_CODE_CSTRING.
787    Abbv = new BitCodeAbbrev();
788    Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_CSTRING));
789    Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
790    Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7));
791    CString7Abbrev = Stream.EmitAbbrev(Abbv);
792    // Abbrev for CST_CODE_CSTRING.
793    Abbv = new BitCodeAbbrev();
794    Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_CSTRING));
795    Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
796    Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
797    CString6Abbrev = Stream.EmitAbbrev(Abbv);
798  }
799
800  SmallVector<uint64_t, 64> Record;
801
802  const ValueEnumerator::ValueList &Vals = VE.getValues();
803  Type *LastTy = 0;
804  for (unsigned i = FirstVal; i != LastVal; ++i) {
805    const Value *V = Vals[i].first;
806    // If we need to switch types, do so now.
807    if (V->getType() != LastTy) {
808      LastTy = V->getType();
809      Record.push_back(VE.getTypeID(LastTy));
810      Stream.EmitRecord(bitc::CST_CODE_SETTYPE, Record,
811                        CONSTANTS_SETTYPE_ABBREV);
812      Record.clear();
813    }
814
815    if (const InlineAsm *IA = dyn_cast<InlineAsm>(V)) {
816      Record.push_back(unsigned(IA->hasSideEffects()) |
817                       unsigned(IA->isAlignStack()) << 1);
818
819      // Add the asm string.
820      const std::string &AsmStr = IA->getAsmString();
821      Record.push_back(AsmStr.size());
822      for (unsigned i = 0, e = AsmStr.size(); i != e; ++i)
823        Record.push_back(AsmStr[i]);
824
825      // Add the constraint string.
826      const std::string &ConstraintStr = IA->getConstraintString();
827      Record.push_back(ConstraintStr.size());
828      for (unsigned i = 0, e = ConstraintStr.size(); i != e; ++i)
829        Record.push_back(ConstraintStr[i]);
830      Stream.EmitRecord(bitc::CST_CODE_INLINEASM, Record);
831      Record.clear();
832      continue;
833    }
834    const Constant *C = cast<Constant>(V);
835    unsigned Code = -1U;
836    unsigned AbbrevToUse = 0;
837    if (C->isNullValue()) {
838      Code = bitc::CST_CODE_NULL;
839    } else if (isa<UndefValue>(C)) {
840      Code = bitc::CST_CODE_UNDEF;
841    } else if (const ConstantInt *IV = dyn_cast<ConstantInt>(C)) {
842      if (IV->getBitWidth() <= 64) {
843        uint64_t V = IV->getSExtValue();
844        if ((int64_t)V >= 0)
845          Record.push_back(V << 1);
846        else
847          Record.push_back((-V << 1) | 1);
848        Code = bitc::CST_CODE_INTEGER;
849        AbbrevToUse = CONSTANTS_INTEGER_ABBREV;
850      } else {                             // Wide integers, > 64 bits in size.
851        // We have an arbitrary precision integer value to write whose
852        // bit width is > 64. However, in canonical unsigned integer
853        // format it is likely that the high bits are going to be zero.
854        // So, we only write the number of active words.
855        unsigned NWords = IV->getValue().getActiveWords();
856        const uint64_t *RawWords = IV->getValue().getRawData();
857        for (unsigned i = 0; i != NWords; ++i) {
858          int64_t V = RawWords[i];
859          if (V >= 0)
860            Record.push_back(V << 1);
861          else
862            Record.push_back((-V << 1) | 1);
863        }
864        Code = bitc::CST_CODE_WIDE_INTEGER;
865      }
866    } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
867      Code = bitc::CST_CODE_FLOAT;
868      Type *Ty = CFP->getType();
869      if (Ty->isFloatTy() || Ty->isDoubleTy()) {
870        Record.push_back(CFP->getValueAPF().bitcastToAPInt().getZExtValue());
871      } else if (Ty->isX86_FP80Ty()) {
872        // api needed to prevent premature destruction
873        // bits are not in the same order as a normal i80 APInt, compensate.
874        APInt api = CFP->getValueAPF().bitcastToAPInt();
875        const uint64_t *p = api.getRawData();
876        Record.push_back((p[1] << 48) | (p[0] >> 16));
877        Record.push_back(p[0] & 0xffffLL);
878      } else if (Ty->isFP128Ty() || Ty->isPPC_FP128Ty()) {
879        APInt api = CFP->getValueAPF().bitcastToAPInt();
880        const uint64_t *p = api.getRawData();
881        Record.push_back(p[0]);
882        Record.push_back(p[1]);
883      } else {
884        assert (0 && "Unknown FP type!");
885      }
886    } else if (isa<ConstantDataSequential>(C) &&
887               cast<ConstantDataSequential>(C)->isString()) {
888      const ConstantDataSequential *Str = cast<ConstantDataSequential>(C);
889      // Emit constant strings specially.
890      unsigned NumElts = Str->getNumElements();
891      // If this is a null-terminated string, use the denser CSTRING encoding.
892      if (Str->isCString()) {
893        Code = bitc::CST_CODE_CSTRING;
894        --NumElts;  // Don't encode the null, which isn't allowed by char6.
895      } else {
896        Code = bitc::CST_CODE_STRING;
897        AbbrevToUse = String8Abbrev;
898      }
899      bool isCStr7 = Code == bitc::CST_CODE_CSTRING;
900      bool isCStrChar6 = Code == bitc::CST_CODE_CSTRING;
901      for (unsigned i = 0; i != NumElts; ++i) {
902        unsigned char V = Str->getElementAsInteger(i);
903        Record.push_back(V);
904        isCStr7 &= (V & 128) == 0;
905        if (isCStrChar6)
906          isCStrChar6 = BitCodeAbbrevOp::isChar6(V);
907      }
908
909      if (isCStrChar6)
910        AbbrevToUse = CString6Abbrev;
911      else if (isCStr7)
912        AbbrevToUse = CString7Abbrev;
913    } else if (const ConstantDataSequential *CDS =
914                  dyn_cast<ConstantDataSequential>(C)) {
915      Code = bitc::CST_CODE_DATA;
916      Type *EltTy = CDS->getType()->getElementType();
917      if (isa<IntegerType>(EltTy)) {
918        for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i)
919          Record.push_back(CDS->getElementAsInteger(i));
920      } else if (EltTy->isFloatTy()) {
921        for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
922          union { float F; uint32_t I; };
923          F = CDS->getElementAsFloat(i);
924          Record.push_back(I);
925        }
926      } else {
927        assert(EltTy->isDoubleTy() && "Unknown ConstantData element type");
928        for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
929          union { double F; uint64_t I; };
930          F = CDS->getElementAsDouble(i);
931          Record.push_back(I);
932        }
933      }
934    } else if (isa<ConstantArray>(C) || isa<ConstantStruct>(C) ||
935               isa<ConstantVector>(C)) {
936      Code = bitc::CST_CODE_AGGREGATE;
937      for (unsigned i = 0, e = C->getNumOperands(); i != e; ++i)
938        Record.push_back(VE.getValueID(C->getOperand(i)));
939      AbbrevToUse = AggregateAbbrev;
940    } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
941      switch (CE->getOpcode()) {
942      default:
943        if (Instruction::isCast(CE->getOpcode())) {
944          Code = bitc::CST_CODE_CE_CAST;
945          Record.push_back(GetEncodedCastOpcode(CE->getOpcode()));
946          Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
947          Record.push_back(VE.getValueID(C->getOperand(0)));
948          AbbrevToUse = CONSTANTS_CE_CAST_Abbrev;
949        } else {
950          assert(CE->getNumOperands() == 2 && "Unknown constant expr!");
951          Code = bitc::CST_CODE_CE_BINOP;
952          Record.push_back(GetEncodedBinaryOpcode(CE->getOpcode()));
953          Record.push_back(VE.getValueID(C->getOperand(0)));
954          Record.push_back(VE.getValueID(C->getOperand(1)));
955          uint64_t Flags = GetOptimizationFlags(CE);
956          if (Flags != 0)
957            Record.push_back(Flags);
958        }
959        break;
960      case Instruction::GetElementPtr:
961        Code = bitc::CST_CODE_CE_GEP;
962        if (cast<GEPOperator>(C)->isInBounds())
963          Code = bitc::CST_CODE_CE_INBOUNDS_GEP;
964        for (unsigned i = 0, e = CE->getNumOperands(); i != e; ++i) {
965          Record.push_back(VE.getTypeID(C->getOperand(i)->getType()));
966          Record.push_back(VE.getValueID(C->getOperand(i)));
967        }
968        break;
969      case Instruction::Select:
970        Code = bitc::CST_CODE_CE_SELECT;
971        Record.push_back(VE.getValueID(C->getOperand(0)));
972        Record.push_back(VE.getValueID(C->getOperand(1)));
973        Record.push_back(VE.getValueID(C->getOperand(2)));
974        break;
975      case Instruction::ExtractElement:
976        Code = bitc::CST_CODE_CE_EXTRACTELT;
977        Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
978        Record.push_back(VE.getValueID(C->getOperand(0)));
979        Record.push_back(VE.getValueID(C->getOperand(1)));
980        break;
981      case Instruction::InsertElement:
982        Code = bitc::CST_CODE_CE_INSERTELT;
983        Record.push_back(VE.getValueID(C->getOperand(0)));
984        Record.push_back(VE.getValueID(C->getOperand(1)));
985        Record.push_back(VE.getValueID(C->getOperand(2)));
986        break;
987      case Instruction::ShuffleVector:
988        // If the return type and argument types are the same, this is a
989        // standard shufflevector instruction.  If the types are different,
990        // then the shuffle is widening or truncating the input vectors, and
991        // the argument type must also be encoded.
992        if (C->getType() == C->getOperand(0)->getType()) {
993          Code = bitc::CST_CODE_CE_SHUFFLEVEC;
994        } else {
995          Code = bitc::CST_CODE_CE_SHUFVEC_EX;
996          Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
997        }
998        Record.push_back(VE.getValueID(C->getOperand(0)));
999        Record.push_back(VE.getValueID(C->getOperand(1)));
1000        Record.push_back(VE.getValueID(C->getOperand(2)));
1001        break;
1002      case Instruction::ICmp:
1003      case Instruction::FCmp:
1004        Code = bitc::CST_CODE_CE_CMP;
1005        Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
1006        Record.push_back(VE.getValueID(C->getOperand(0)));
1007        Record.push_back(VE.getValueID(C->getOperand(1)));
1008        Record.push_back(CE->getPredicate());
1009        break;
1010      }
1011    } else if (const BlockAddress *BA = dyn_cast<BlockAddress>(C)) {
1012      Code = bitc::CST_CODE_BLOCKADDRESS;
1013      Record.push_back(VE.getTypeID(BA->getFunction()->getType()));
1014      Record.push_back(VE.getValueID(BA->getFunction()));
1015      Record.push_back(VE.getGlobalBasicBlockID(BA->getBasicBlock()));
1016    } else {
1017#ifndef NDEBUG
1018      C->dump();
1019#endif
1020      llvm_unreachable("Unknown constant!");
1021    }
1022    Stream.EmitRecord(Code, Record, AbbrevToUse);
1023    Record.clear();
1024  }
1025
1026  Stream.ExitBlock();
1027}
1028
1029static void WriteModuleConstants(const ValueEnumerator &VE,
1030                                 BitstreamWriter &Stream) {
1031  const ValueEnumerator::ValueList &Vals = VE.getValues();
1032
1033  // Find the first constant to emit, which is the first non-globalvalue value.
1034  // We know globalvalues have been emitted by WriteModuleInfo.
1035  for (unsigned i = 0, e = Vals.size(); i != e; ++i) {
1036    if (!isa<GlobalValue>(Vals[i].first)) {
1037      WriteConstants(i, Vals.size(), VE, Stream, true);
1038      return;
1039    }
1040  }
1041}
1042
1043/// PushValueAndType - The file has to encode both the value and type id for
1044/// many values, because we need to know what type to create for forward
1045/// references.  However, most operands are not forward references, so this type
1046/// field is not needed.
1047///
1048/// This function adds V's value ID to Vals.  If the value ID is higher than the
1049/// instruction ID, then it is a forward reference, and it also includes the
1050/// type ID.
1051static bool PushValueAndType(const Value *V, unsigned InstID,
1052                             SmallVector<unsigned, 64> &Vals,
1053                             ValueEnumerator &VE) {
1054  unsigned ValID = VE.getValueID(V);
1055  Vals.push_back(ValID);
1056  if (ValID >= InstID) {
1057    Vals.push_back(VE.getTypeID(V->getType()));
1058    return true;
1059  }
1060  return false;
1061}
1062
1063/// WriteInstruction - Emit an instruction to the specified stream.
1064static void WriteInstruction(const Instruction &I, unsigned InstID,
1065                             ValueEnumerator &VE, BitstreamWriter &Stream,
1066                             SmallVector<unsigned, 64> &Vals) {
1067  unsigned Code = 0;
1068  unsigned AbbrevToUse = 0;
1069  VE.setInstructionID(&I);
1070  switch (I.getOpcode()) {
1071  default:
1072    if (Instruction::isCast(I.getOpcode())) {
1073      Code = bitc::FUNC_CODE_INST_CAST;
1074      if (!PushValueAndType(I.getOperand(0), InstID, Vals, VE))
1075        AbbrevToUse = FUNCTION_INST_CAST_ABBREV;
1076      Vals.push_back(VE.getTypeID(I.getType()));
1077      Vals.push_back(GetEncodedCastOpcode(I.getOpcode()));
1078    } else {
1079      assert(isa<BinaryOperator>(I) && "Unknown instruction!");
1080      Code = bitc::FUNC_CODE_INST_BINOP;
1081      if (!PushValueAndType(I.getOperand(0), InstID, Vals, VE))
1082        AbbrevToUse = FUNCTION_INST_BINOP_ABBREV;
1083      Vals.push_back(VE.getValueID(I.getOperand(1)));
1084      Vals.push_back(GetEncodedBinaryOpcode(I.getOpcode()));
1085      uint64_t Flags = GetOptimizationFlags(&I);
1086      if (Flags != 0) {
1087        if (AbbrevToUse == FUNCTION_INST_BINOP_ABBREV)
1088          AbbrevToUse = FUNCTION_INST_BINOP_FLAGS_ABBREV;
1089        Vals.push_back(Flags);
1090      }
1091    }
1092    break;
1093
1094  case Instruction::GetElementPtr:
1095    Code = bitc::FUNC_CODE_INST_GEP;
1096    if (cast<GEPOperator>(&I)->isInBounds())
1097      Code = bitc::FUNC_CODE_INST_INBOUNDS_GEP;
1098    for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
1099      PushValueAndType(I.getOperand(i), InstID, Vals, VE);
1100    break;
1101  case Instruction::ExtractValue: {
1102    Code = bitc::FUNC_CODE_INST_EXTRACTVAL;
1103    PushValueAndType(I.getOperand(0), InstID, Vals, VE);
1104    const ExtractValueInst *EVI = cast<ExtractValueInst>(&I);
1105    for (const unsigned *i = EVI->idx_begin(), *e = EVI->idx_end(); i != e; ++i)
1106      Vals.push_back(*i);
1107    break;
1108  }
1109  case Instruction::InsertValue: {
1110    Code = bitc::FUNC_CODE_INST_INSERTVAL;
1111    PushValueAndType(I.getOperand(0), InstID, Vals, VE);
1112    PushValueAndType(I.getOperand(1), InstID, Vals, VE);
1113    const InsertValueInst *IVI = cast<InsertValueInst>(&I);
1114    for (const unsigned *i = IVI->idx_begin(), *e = IVI->idx_end(); i != e; ++i)
1115      Vals.push_back(*i);
1116    break;
1117  }
1118  case Instruction::Select:
1119    Code = bitc::FUNC_CODE_INST_VSELECT;
1120    PushValueAndType(I.getOperand(1), InstID, Vals, VE);
1121    Vals.push_back(VE.getValueID(I.getOperand(2)));
1122    PushValueAndType(I.getOperand(0), InstID, Vals, VE);
1123    break;
1124  case Instruction::ExtractElement:
1125    Code = bitc::FUNC_CODE_INST_EXTRACTELT;
1126    PushValueAndType(I.getOperand(0), InstID, Vals, VE);
1127    Vals.push_back(VE.getValueID(I.getOperand(1)));
1128    break;
1129  case Instruction::InsertElement:
1130    Code = bitc::FUNC_CODE_INST_INSERTELT;
1131    PushValueAndType(I.getOperand(0), InstID, Vals, VE);
1132    Vals.push_back(VE.getValueID(I.getOperand(1)));
1133    Vals.push_back(VE.getValueID(I.getOperand(2)));
1134    break;
1135  case Instruction::ShuffleVector:
1136    Code = bitc::FUNC_CODE_INST_SHUFFLEVEC;
1137    PushValueAndType(I.getOperand(0), InstID, Vals, VE);
1138    Vals.push_back(VE.getValueID(I.getOperand(1)));
1139    Vals.push_back(VE.getValueID(I.getOperand(2)));
1140    break;
1141  case Instruction::ICmp:
1142  case Instruction::FCmp:
1143    // compare returning Int1Ty or vector of Int1Ty
1144    Code = bitc::FUNC_CODE_INST_CMP2;
1145    PushValueAndType(I.getOperand(0), InstID, Vals, VE);
1146    Vals.push_back(VE.getValueID(I.getOperand(1)));
1147    Vals.push_back(cast<CmpInst>(I).getPredicate());
1148    break;
1149
1150  case Instruction::Ret:
1151    {
1152      Code = bitc::FUNC_CODE_INST_RET;
1153      unsigned NumOperands = I.getNumOperands();
1154      if (NumOperands == 0)
1155        AbbrevToUse = FUNCTION_INST_RET_VOID_ABBREV;
1156      else if (NumOperands == 1) {
1157        if (!PushValueAndType(I.getOperand(0), InstID, Vals, VE))
1158          AbbrevToUse = FUNCTION_INST_RET_VAL_ABBREV;
1159      } else {
1160        for (unsigned i = 0, e = NumOperands; i != e; ++i)
1161          PushValueAndType(I.getOperand(i), InstID, Vals, VE);
1162      }
1163    }
1164    break;
1165  case Instruction::Br:
1166    {
1167      Code = bitc::FUNC_CODE_INST_BR;
1168      BranchInst &II = cast<BranchInst>(I);
1169      Vals.push_back(VE.getValueID(II.getSuccessor(0)));
1170      if (II.isConditional()) {
1171        Vals.push_back(VE.getValueID(II.getSuccessor(1)));
1172        Vals.push_back(VE.getValueID(II.getCondition()));
1173      }
1174    }
1175    break;
1176  case Instruction::Switch:
1177    Code = bitc::FUNC_CODE_INST_SWITCH;
1178    Vals.push_back(VE.getTypeID(I.getOperand(0)->getType()));
1179    for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
1180      Vals.push_back(VE.getValueID(I.getOperand(i)));
1181    break;
1182  case Instruction::IndirectBr:
1183    Code = bitc::FUNC_CODE_INST_INDIRECTBR;
1184    Vals.push_back(VE.getTypeID(I.getOperand(0)->getType()));
1185    for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
1186      Vals.push_back(VE.getValueID(I.getOperand(i)));
1187    break;
1188
1189  case Instruction::Invoke: {
1190    const InvokeInst *II = cast<InvokeInst>(&I);
1191    const Value *Callee(II->getCalledValue());
1192    PointerType *PTy = cast<PointerType>(Callee->getType());
1193    FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
1194    Code = bitc::FUNC_CODE_INST_INVOKE;
1195
1196    Vals.push_back(VE.getAttributeID(II->getAttributes()));
1197    Vals.push_back(II->getCallingConv());
1198    Vals.push_back(VE.getValueID(II->getNormalDest()));
1199    Vals.push_back(VE.getValueID(II->getUnwindDest()));
1200    PushValueAndType(Callee, InstID, Vals, VE);
1201
1202    // Emit value #'s for the fixed parameters.
1203    for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
1204      Vals.push_back(VE.getValueID(I.getOperand(i)));  // fixed param.
1205
1206    // Emit type/value pairs for varargs params.
1207    if (FTy->isVarArg()) {
1208      for (unsigned i = FTy->getNumParams(), e = I.getNumOperands()-3;
1209           i != e; ++i)
1210        PushValueAndType(I.getOperand(i), InstID, Vals, VE); // vararg
1211    }
1212    break;
1213  }
1214  case Instruction::Unreachable:
1215    Code = bitc::FUNC_CODE_INST_UNREACHABLE;
1216    AbbrevToUse = FUNCTION_INST_UNREACHABLE_ABBREV;
1217    break;
1218
1219  case Instruction::PHI: {
1220    const PHINode &PN = cast<PHINode>(I);
1221    Code = bitc::FUNC_CODE_INST_PHI;
1222    Vals.push_back(VE.getTypeID(PN.getType()));
1223    for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
1224      Vals.push_back(VE.getValueID(PN.getIncomingValue(i)));
1225      Vals.push_back(VE.getValueID(PN.getIncomingBlock(i)));
1226    }
1227    break;
1228  }
1229
1230  case Instruction::Alloca:
1231    Code = bitc::FUNC_CODE_INST_ALLOCA;
1232    Vals.push_back(VE.getTypeID(I.getType()));
1233    Vals.push_back(VE.getTypeID(I.getOperand(0)->getType()));
1234    Vals.push_back(VE.getValueID(I.getOperand(0))); // size.
1235    Vals.push_back(Log2_32(cast<AllocaInst>(I).getAlignment())+1);
1236    break;
1237
1238  case Instruction::Load:
1239    Code = bitc::FUNC_CODE_INST_LOAD;
1240    if (!PushValueAndType(I.getOperand(0), InstID, Vals, VE))  // ptr
1241      AbbrevToUse = FUNCTION_INST_LOAD_ABBREV;
1242
1243    Vals.push_back(Log2_32(cast<LoadInst>(I).getAlignment())+1);
1244    Vals.push_back(cast<LoadInst>(I).isVolatile());
1245    break;
1246  case Instruction::Store:
1247    Code = bitc::FUNC_CODE_INST_STORE;
1248    PushValueAndType(I.getOperand(1), InstID, Vals, VE);  // ptrty + ptr
1249    Vals.push_back(VE.getValueID(I.getOperand(0)));       // val.
1250    Vals.push_back(Log2_32(cast<StoreInst>(I).getAlignment())+1);
1251    Vals.push_back(cast<StoreInst>(I).isVolatile());
1252    break;
1253  case Instruction::Call: {
1254    const CallInst &CI = cast<CallInst>(I);
1255    PointerType *PTy = cast<PointerType>(CI.getCalledValue()->getType());
1256    FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
1257
1258    Code = FUNC_CODE_INST_CALL_2_7;
1259
1260    Vals.push_back(VE.getAttributeID(CI.getAttributes()));
1261    Vals.push_back((CI.getCallingConv() << 1) | unsigned(CI.isTailCall()));
1262    PushValueAndType(CI.getCalledValue(), InstID, Vals, VE);  // Callee
1263
1264    // Emit value #'s for the fixed parameters.
1265    for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
1266      Vals.push_back(VE.getValueID(CI.getArgOperand(i)));  // fixed param.
1267
1268    // Emit type/value pairs for varargs params.
1269    if (FTy->isVarArg()) {
1270      for (unsigned i = FTy->getNumParams(), e = CI.getNumArgOperands();
1271           i != e; ++i)
1272        PushValueAndType(CI.getArgOperand(i), InstID, Vals, VE);  // varargs
1273    }
1274    break;
1275  }
1276  case Instruction::VAArg:
1277    Code = bitc::FUNC_CODE_INST_VAARG;
1278    Vals.push_back(VE.getTypeID(I.getOperand(0)->getType()));   // valistty
1279    Vals.push_back(VE.getValueID(I.getOperand(0))); // valist.
1280    Vals.push_back(VE.getTypeID(I.getType())); // restype.
1281    break;
1282  }
1283
1284  Stream.EmitRecord(Code, Vals, AbbrevToUse);
1285  Vals.clear();
1286}
1287
1288// Emit names for globals/functions etc.
1289static void WriteValueSymbolTable(const ValueSymbolTable &VST,
1290                                  const ValueEnumerator &VE,
1291                                  BitstreamWriter &Stream) {
1292  if (VST.empty()) return;
1293  Stream.EnterSubblock(bitc::VALUE_SYMTAB_BLOCK_ID, 4);
1294
1295  // FIXME: Set up the abbrev, we know how many values there are!
1296  // FIXME: We know if the type names can use 7-bit ascii.
1297  SmallVector<unsigned, 64> NameVals;
1298
1299  for (ValueSymbolTable::const_iterator SI = VST.begin(), SE = VST.end();
1300       SI != SE; ++SI) {
1301
1302    const ValueName &Name = *SI;
1303
1304    // Figure out the encoding to use for the name.
1305    bool is7Bit = true;
1306    bool isChar6 = true;
1307    for (const char *C = Name.getKeyData(), *E = C+Name.getKeyLength();
1308         C != E; ++C) {
1309      if (isChar6)
1310        isChar6 = BitCodeAbbrevOp::isChar6(*C);
1311      if ((unsigned char)*C & 128) {
1312        is7Bit = false;
1313        break;  // don't bother scanning the rest.
1314      }
1315    }
1316
1317    unsigned AbbrevToUse = VST_ENTRY_8_ABBREV;
1318
1319    // VST_ENTRY:   [valueid, namechar x N]
1320    // VST_BBENTRY: [bbid, namechar x N]
1321    unsigned Code;
1322    if (isa<BasicBlock>(SI->getValue())) {
1323      Code = bitc::VST_CODE_BBENTRY;
1324      if (isChar6)
1325        AbbrevToUse = VST_BBENTRY_6_ABBREV;
1326    } else {
1327      Code = bitc::VST_CODE_ENTRY;
1328      if (isChar6)
1329        AbbrevToUse = VST_ENTRY_6_ABBREV;
1330      else if (is7Bit)
1331        AbbrevToUse = VST_ENTRY_7_ABBREV;
1332    }
1333
1334    NameVals.push_back(VE.getValueID(SI->getValue()));
1335    for (const char *P = Name.getKeyData(),
1336         *E = Name.getKeyData()+Name.getKeyLength(); P != E; ++P)
1337      NameVals.push_back((unsigned char)*P);
1338
1339    // Emit the finished record.
1340    Stream.EmitRecord(Code, NameVals, AbbrevToUse);
1341    NameVals.clear();
1342  }
1343  Stream.ExitBlock();
1344}
1345
1346/// WriteFunction - Emit a function body to the module stream.
1347static void WriteFunction(const Function &F, ValueEnumerator &VE,
1348                          BitstreamWriter &Stream) {
1349  Stream.EnterSubblock(bitc::FUNCTION_BLOCK_ID, 4);
1350  VE.incorporateFunction(F);
1351
1352  SmallVector<unsigned, 64> Vals;
1353
1354  // Emit the number of basic blocks, so the reader can create them ahead of
1355  // time.
1356  Vals.push_back(VE.getBasicBlocks().size());
1357  Stream.EmitRecord(bitc::FUNC_CODE_DECLAREBLOCKS, Vals);
1358  Vals.clear();
1359
1360  // If there are function-local constants, emit them now.
1361  unsigned CstStart, CstEnd;
1362  VE.getFunctionConstantRange(CstStart, CstEnd);
1363  WriteConstants(CstStart, CstEnd, VE, Stream, false);
1364
1365  // If there is function-local metadata, emit it now.
1366  WriteFunctionLocalMetadata(F, VE, Stream);
1367
1368  // Keep a running idea of what the instruction ID is.
1369  unsigned InstID = CstEnd;
1370
1371  bool NeedsMetadataAttachment = false;
1372
1373  DebugLoc LastDL;
1374
1375  // Finally, emit all the instructions, in order.
1376  for (Function::const_iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
1377    for (BasicBlock::const_iterator I = BB->begin(), E = BB->end();
1378         I != E; ++I) {
1379      WriteInstruction(*I, InstID, VE, Stream, Vals);
1380
1381      if (!I->getType()->isVoidTy())
1382        ++InstID;
1383
1384      // If the instruction has metadata, write a metadata attachment later.
1385      NeedsMetadataAttachment |= I->hasMetadataOtherThanDebugLoc();
1386
1387      // If the instruction has a debug location, emit it.
1388      DebugLoc DL = I->getDebugLoc();
1389      if (DL.isUnknown()) {
1390        // nothing todo.
1391      } else if (DL == LastDL) {
1392        // Just repeat the same debug loc as last time.
1393        Stream.EmitRecord(bitc::FUNC_CODE_DEBUG_LOC_AGAIN, Vals);
1394      } else {
1395        MDNode *Scope, *IA;
1396        DL.getScopeAndInlinedAt(Scope, IA, I->getContext());
1397
1398        Vals.push_back(DL.getLine());
1399        Vals.push_back(DL.getCol());
1400        Vals.push_back(Scope ? VE.getValueID(Scope)+1 : 0);
1401        Vals.push_back(IA ? VE.getValueID(IA)+1 : 0);
1402        Stream.EmitRecord(FUNC_CODE_DEBUG_LOC_2_7, Vals);
1403        Vals.clear();
1404
1405        LastDL = DL;
1406      }
1407    }
1408
1409  // Emit names for all the instructions etc.
1410  WriteValueSymbolTable(F.getValueSymbolTable(), VE, Stream);
1411
1412  if (NeedsMetadataAttachment)
1413    WriteMetadataAttachment(F, VE, Stream);
1414  VE.purgeFunction();
1415  Stream.ExitBlock();
1416}
1417
1418// Emit blockinfo, which defines the standard abbreviations etc.
1419static void WriteBlockInfo(const ValueEnumerator &VE, 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  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