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