BitcodeWriter.cpp revision e4977cf750eaff28275429191821420c20b0c64f
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 "llvm/Bitcode/ReaderWriter.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/TypeSymbolTable.h"
24#include "llvm/ValueSymbolTable.h"
25#include "llvm/Support/MathExtras.h"
26using namespace llvm;
27
28/// These are manifest constants used by the bitcode writer. They do not need to
29/// be kept in sync with the reader, but need to be consistent within this file.
30enum {
31  CurVersion = 0,
32
33  // VALUE_SYMTAB_BLOCK abbrev id's.
34  VST_ENTRY_8_ABBREV = bitc::FIRST_APPLICATION_ABBREV,
35  VST_ENTRY_7_ABBREV,
36  VST_ENTRY_6_ABBREV,
37  VST_BBENTRY_6_ABBREV,
38
39  // CONSTANTS_BLOCK abbrev id's.
40  CONSTANTS_SETTYPE_ABBREV = bitc::FIRST_APPLICATION_ABBREV,
41  CONSTANTS_INTEGER_ABBREV,
42  CONSTANTS_CE_CAST_Abbrev,
43  CONSTANTS_NULL_Abbrev,
44
45  // FUNCTION_BLOCK abbrev id's.
46  FUNCTION_INST_LOAD_ABBREV = bitc::FIRST_APPLICATION_ABBREV,
47  FUNCTION_INST_BINOP_ABBREV,
48  FUNCTION_INST_CAST_ABBREV,
49  FUNCTION_INST_RET_VOID_ABBREV,
50  FUNCTION_INST_RET_VAL_ABBREV,
51  FUNCTION_INST_UNREACHABLE_ABBREV
52};
53
54
55static unsigned GetEncodedCastOpcode(unsigned Opcode) {
56  switch (Opcode) {
57  default: assert(0 && "Unknown cast instruction!");
58  case Instruction::Trunc   : return bitc::CAST_TRUNC;
59  case Instruction::ZExt    : return bitc::CAST_ZEXT;
60  case Instruction::SExt    : return bitc::CAST_SEXT;
61  case Instruction::FPToUI  : return bitc::CAST_FPTOUI;
62  case Instruction::FPToSI  : return bitc::CAST_FPTOSI;
63  case Instruction::UIToFP  : return bitc::CAST_UITOFP;
64  case Instruction::SIToFP  : return bitc::CAST_SITOFP;
65  case Instruction::FPTrunc : return bitc::CAST_FPTRUNC;
66  case Instruction::FPExt   : return bitc::CAST_FPEXT;
67  case Instruction::PtrToInt: return bitc::CAST_PTRTOINT;
68  case Instruction::IntToPtr: return bitc::CAST_INTTOPTR;
69  case Instruction::BitCast : return bitc::CAST_BITCAST;
70  }
71}
72
73static unsigned GetEncodedBinaryOpcode(unsigned Opcode) {
74  switch (Opcode) {
75  default: assert(0 && "Unknown binary instruction!");
76  case Instruction::Add:  return bitc::BINOP_ADD;
77  case Instruction::Sub:  return bitc::BINOP_SUB;
78  case Instruction::Mul:  return bitc::BINOP_MUL;
79  case Instruction::UDiv: return bitc::BINOP_UDIV;
80  case Instruction::FDiv:
81  case Instruction::SDiv: return bitc::BINOP_SDIV;
82  case Instruction::URem: return bitc::BINOP_UREM;
83  case Instruction::FRem:
84  case Instruction::SRem: return bitc::BINOP_SREM;
85  case Instruction::Shl:  return bitc::BINOP_SHL;
86  case Instruction::LShr: return bitc::BINOP_LSHR;
87  case Instruction::AShr: return bitc::BINOP_ASHR;
88  case Instruction::And:  return bitc::BINOP_AND;
89  case Instruction::Or:   return bitc::BINOP_OR;
90  case Instruction::Xor:  return bitc::BINOP_XOR;
91  }
92}
93
94
95
96static void WriteStringRecord(unsigned Code, const std::string &Str,
97                              unsigned AbbrevToUse, BitstreamWriter &Stream) {
98  SmallVector<unsigned, 64> Vals;
99
100  // Code: [strchar x N]
101  for (unsigned i = 0, e = Str.size(); i != e; ++i)
102    Vals.push_back(Str[i]);
103
104  // Emit the finished record.
105  Stream.EmitRecord(Code, Vals, AbbrevToUse);
106}
107
108// Emit information about parameter attributes.
109static void WriteParamAttrTable(const ValueEnumerator &VE,
110                                BitstreamWriter &Stream) {
111  const std::vector<PAListPtr> &Attrs = VE.getParamAttrs();
112  if (Attrs.empty()) return;
113
114  Stream.EnterSubblock(bitc::PARAMATTR_BLOCK_ID, 3);
115
116  SmallVector<uint64_t, 64> Record;
117  for (unsigned i = 0, e = Attrs.size(); i != e; ++i) {
118    const PAListPtr &A = Attrs[i];
119    for (unsigned i = 0, e = A.getNumSlots(); i != e; ++i) {
120      const ParamAttrsWithIndex &PAWI = A.getSlot(i);
121      Record.push_back(PAWI.Index);
122      Record.push_back(PAWI.Attrs);
123    }
124
125    Stream.EmitRecord(bitc::PARAMATTR_CODE_ENTRY, Record);
126    Record.clear();
127  }
128
129  Stream.ExitBlock();
130}
131
132/// WriteTypeTable - Write out the type table for a module.
133static void WriteTypeTable(const ValueEnumerator &VE, BitstreamWriter &Stream) {
134  const ValueEnumerator::TypeList &TypeList = VE.getTypes();
135
136  Stream.EnterSubblock(bitc::TYPE_BLOCK_ID, 4 /*count from # abbrevs */);
137  SmallVector<uint64_t, 64> TypeVals;
138
139  // Abbrev for TYPE_CODE_POINTER.
140  BitCodeAbbrev *Abbv = new BitCodeAbbrev();
141  Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_POINTER));
142  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
143                            Log2_32_Ceil(VE.getTypes().size()+1)));
144  Abbv->Add(BitCodeAbbrevOp(0));  // Addrspace = 0
145  unsigned PtrAbbrev = Stream.EmitAbbrev(Abbv);
146
147  // Abbrev for TYPE_CODE_FUNCTION.
148  Abbv = new BitCodeAbbrev();
149  Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_FUNCTION));
150  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));  // isvararg
151  Abbv->Add(BitCodeAbbrevOp(0));  // FIXME: DEAD value, remove in LLVM 3.0
152  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
153  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
154                            Log2_32_Ceil(VE.getTypes().size()+1)));
155  unsigned FunctionAbbrev = Stream.EmitAbbrev(Abbv);
156
157  // Abbrev for TYPE_CODE_STRUCT.
158  Abbv = new BitCodeAbbrev();
159  Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_STRUCT));
160  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));  // ispacked
161  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
162  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
163                            Log2_32_Ceil(VE.getTypes().size()+1)));
164  unsigned StructAbbrev = Stream.EmitAbbrev(Abbv);
165
166  // Abbrev for TYPE_CODE_ARRAY.
167  Abbv = new BitCodeAbbrev();
168  Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_ARRAY));
169  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));   // size
170  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
171                            Log2_32_Ceil(VE.getTypes().size()+1)));
172  unsigned ArrayAbbrev = Stream.EmitAbbrev(Abbv);
173
174  // Emit an entry count so the reader can reserve space.
175  TypeVals.push_back(TypeList.size());
176  Stream.EmitRecord(bitc::TYPE_CODE_NUMENTRY, TypeVals);
177  TypeVals.clear();
178
179  // Loop over all of the types, emitting each in turn.
180  for (unsigned i = 0, e = TypeList.size(); i != e; ++i) {
181    const Type *T = TypeList[i].first;
182    int AbbrevToUse = 0;
183    unsigned Code = 0;
184
185    switch (T->getTypeID()) {
186    default: assert(0 && "Unknown type!");
187    case Type::VoidTyID:   Code = bitc::TYPE_CODE_VOID;   break;
188    case Type::FloatTyID:  Code = bitc::TYPE_CODE_FLOAT;  break;
189    case Type::DoubleTyID: Code = bitc::TYPE_CODE_DOUBLE; break;
190    case Type::X86_FP80TyID: Code = bitc::TYPE_CODE_X86_FP80; break;
191    case Type::FP128TyID: Code = bitc::TYPE_CODE_FP128; break;
192    case Type::PPC_FP128TyID: Code = bitc::TYPE_CODE_PPC_FP128; break;
193    case Type::LabelTyID:  Code = bitc::TYPE_CODE_LABEL;  break;
194    case Type::OpaqueTyID: Code = bitc::TYPE_CODE_OPAQUE; break;
195    case Type::IntegerTyID:
196      // INTEGER: [width]
197      Code = bitc::TYPE_CODE_INTEGER;
198      TypeVals.push_back(cast<IntegerType>(T)->getBitWidth());
199      break;
200    case Type::PointerTyID: {
201      const PointerType *PTy = cast<PointerType>(T);
202      // POINTER: [pointee type, address space]
203      Code = bitc::TYPE_CODE_POINTER;
204      TypeVals.push_back(VE.getTypeID(PTy->getElementType()));
205      unsigned AddressSpace = PTy->getAddressSpace();
206      TypeVals.push_back(AddressSpace);
207      if (AddressSpace == 0) AbbrevToUse = PtrAbbrev;
208      break;
209    }
210    case Type::FunctionTyID: {
211      const FunctionType *FT = cast<FunctionType>(T);
212      // FUNCTION: [isvararg, attrid, retty, paramty x N]
213      Code = bitc::TYPE_CODE_FUNCTION;
214      TypeVals.push_back(FT->isVarArg());
215      TypeVals.push_back(0);  // FIXME: DEAD: remove in llvm 3.0
216      TypeVals.push_back(VE.getTypeID(FT->getReturnType()));
217      for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i)
218        TypeVals.push_back(VE.getTypeID(FT->getParamType(i)));
219      AbbrevToUse = FunctionAbbrev;
220      break;
221    }
222    case Type::StructTyID: {
223      const StructType *ST = cast<StructType>(T);
224      // STRUCT: [ispacked, eltty x N]
225      Code = bitc::TYPE_CODE_STRUCT;
226      TypeVals.push_back(ST->isPacked());
227      // Output all of the element types.
228      for (StructType::element_iterator I = ST->element_begin(),
229           E = ST->element_end(); I != E; ++I)
230        TypeVals.push_back(VE.getTypeID(*I));
231      AbbrevToUse = StructAbbrev;
232      break;
233    }
234    case Type::ArrayTyID: {
235      const ArrayType *AT = cast<ArrayType>(T);
236      // ARRAY: [numelts, eltty]
237      Code = bitc::TYPE_CODE_ARRAY;
238      TypeVals.push_back(AT->getNumElements());
239      TypeVals.push_back(VE.getTypeID(AT->getElementType()));
240      AbbrevToUse = ArrayAbbrev;
241      break;
242    }
243    case Type::VectorTyID: {
244      const VectorType *VT = cast<VectorType>(T);
245      // VECTOR [numelts, eltty]
246      Code = bitc::TYPE_CODE_VECTOR;
247      TypeVals.push_back(VT->getNumElements());
248      TypeVals.push_back(VE.getTypeID(VT->getElementType()));
249      break;
250    }
251    }
252
253    // Emit the finished record.
254    Stream.EmitRecord(Code, TypeVals, AbbrevToUse);
255    TypeVals.clear();
256  }
257
258  Stream.ExitBlock();
259}
260
261static unsigned getEncodedLinkage(const GlobalValue *GV) {
262  switch (GV->getLinkage()) {
263  default: assert(0 && "Invalid linkage!");
264  case GlobalValue::GhostLinkage:  // Map ghost linkage onto external.
265  case GlobalValue::ExternalLinkage:     return 0;
266  case GlobalValue::WeakLinkage:         return 1;
267  case GlobalValue::AppendingLinkage:    return 2;
268  case GlobalValue::InternalLinkage:     return 3;
269  case GlobalValue::LinkOnceLinkage:     return 4;
270  case GlobalValue::DLLImportLinkage:    return 5;
271  case GlobalValue::DLLExportLinkage:    return 6;
272  case GlobalValue::ExternalWeakLinkage: return 7;
273  case GlobalValue::CommonLinkage:       return 8;
274  }
275}
276
277static unsigned getEncodedVisibility(const GlobalValue *GV) {
278  switch (GV->getVisibility()) {
279  default: assert(0 && "Invalid visibility!");
280  case GlobalValue::DefaultVisibility:   return 0;
281  case GlobalValue::HiddenVisibility:    return 1;
282  case GlobalValue::ProtectedVisibility: return 2;
283  }
284}
285
286// Emit top-level description of module, including target triple, inline asm,
287// descriptors for global variables, and function prototype info.
288static void WriteModuleInfo(const Module *M, const ValueEnumerator &VE,
289                            BitstreamWriter &Stream) {
290  // Emit the list of dependent libraries for the Module.
291  for (Module::lib_iterator I = M->lib_begin(), E = M->lib_end(); I != E; ++I)
292    WriteStringRecord(bitc::MODULE_CODE_DEPLIB, *I, 0/*TODO*/, Stream);
293
294  // Emit various pieces of data attached to a module.
295  if (!M->getTargetTriple().empty())
296    WriteStringRecord(bitc::MODULE_CODE_TRIPLE, M->getTargetTriple(),
297                      0/*TODO*/, Stream);
298  if (!M->getDataLayout().empty())
299    WriteStringRecord(bitc::MODULE_CODE_DATALAYOUT, M->getDataLayout(),
300                      0/*TODO*/, Stream);
301  if (!M->getModuleInlineAsm().empty())
302    WriteStringRecord(bitc::MODULE_CODE_ASM, M->getModuleInlineAsm(),
303                      0/*TODO*/, Stream);
304
305  // Emit information about sections and collectors, computing how many there
306  // are.  Also compute the maximum alignment value.
307  std::map<std::string, unsigned> SectionMap;
308  std::map<std::string, unsigned> CollectorMap;
309  unsigned MaxAlignment = 0;
310  unsigned MaxGlobalType = 0;
311  for (Module::const_global_iterator GV = M->global_begin(),E = M->global_end();
312       GV != E; ++GV) {
313    MaxAlignment = std::max(MaxAlignment, GV->getAlignment());
314    MaxGlobalType = std::max(MaxGlobalType, VE.getTypeID(GV->getType()));
315
316    if (!GV->hasSection()) continue;
317    // Give section names unique ID's.
318    unsigned &Entry = SectionMap[GV->getSection()];
319    if (Entry != 0) continue;
320    WriteStringRecord(bitc::MODULE_CODE_SECTIONNAME, GV->getSection(),
321                      0/*TODO*/, Stream);
322    Entry = SectionMap.size();
323  }
324  for (Module::const_iterator F = M->begin(), E = M->end(); F != E; ++F) {
325    MaxAlignment = std::max(MaxAlignment, F->getAlignment());
326    if (F->hasSection()) {
327      // Give section names unique ID's.
328      unsigned &Entry = SectionMap[F->getSection()];
329      if (!Entry) {
330        WriteStringRecord(bitc::MODULE_CODE_SECTIONNAME, F->getSection(),
331                          0/*TODO*/, Stream);
332        Entry = SectionMap.size();
333      }
334    }
335    if (F->hasCollector()) {
336      // Same for collector names.
337      unsigned &Entry = CollectorMap[F->getCollector()];
338      if (!Entry) {
339        WriteStringRecord(bitc::MODULE_CODE_COLLECTORNAME, F->getCollector(),
340                          0/*TODO*/, Stream);
341        Entry = CollectorMap.size();
342      }
343    }
344  }
345
346  // Emit abbrev for globals, now that we know # sections and max alignment.
347  unsigned SimpleGVarAbbrev = 0;
348  if (!M->global_empty()) {
349    // Add an abbrev for common globals with no visibility or thread localness.
350    BitCodeAbbrev *Abbv = new BitCodeAbbrev();
351    Abbv->Add(BitCodeAbbrevOp(bitc::MODULE_CODE_GLOBALVAR));
352    Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
353                              Log2_32_Ceil(MaxGlobalType+1)));
354    Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));      // Constant.
355    Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));        // Initializer.
356    Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4));      // Linkage.
357    if (MaxAlignment == 0)                                      // Alignment.
358      Abbv->Add(BitCodeAbbrevOp(0));
359    else {
360      unsigned MaxEncAlignment = Log2_32(MaxAlignment)+1;
361      Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
362                               Log2_32_Ceil(MaxEncAlignment+1)));
363    }
364    if (SectionMap.empty())                                    // Section.
365      Abbv->Add(BitCodeAbbrevOp(0));
366    else
367      Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
368                               Log2_32_Ceil(SectionMap.size()+1)));
369    // Don't bother emitting vis + thread local.
370    SimpleGVarAbbrev = Stream.EmitAbbrev(Abbv);
371  }
372
373  // Emit the global variable information.
374  SmallVector<unsigned, 64> Vals;
375  for (Module::const_global_iterator GV = M->global_begin(),E = M->global_end();
376       GV != E; ++GV) {
377    unsigned AbbrevToUse = 0;
378
379    // GLOBALVAR: [type, isconst, initid,
380    //             linkage, alignment, section, visibility, threadlocal]
381    Vals.push_back(VE.getTypeID(GV->getType()));
382    Vals.push_back(GV->isConstant());
383    Vals.push_back(GV->isDeclaration() ? 0 :
384                   (VE.getValueID(GV->getInitializer()) + 1));
385    Vals.push_back(getEncodedLinkage(GV));
386    Vals.push_back(Log2_32(GV->getAlignment())+1);
387    Vals.push_back(GV->hasSection() ? SectionMap[GV->getSection()] : 0);
388    if (GV->isThreadLocal() ||
389        GV->getVisibility() != GlobalValue::DefaultVisibility) {
390      Vals.push_back(getEncodedVisibility(GV));
391      Vals.push_back(GV->isThreadLocal());
392    } else {
393      AbbrevToUse = SimpleGVarAbbrev;
394    }
395
396    Stream.EmitRecord(bitc::MODULE_CODE_GLOBALVAR, Vals, AbbrevToUse);
397    Vals.clear();
398  }
399
400  // Emit the function proto information.
401  for (Module::const_iterator F = M->begin(), E = M->end(); F != E; ++F) {
402    // FUNCTION:  [type, callingconv, isproto, paramattr,
403    //             linkage, alignment, section, visibility, collector]
404    Vals.push_back(VE.getTypeID(F->getType()));
405    Vals.push_back(F->getCallingConv());
406    Vals.push_back(F->isDeclaration());
407    Vals.push_back(getEncodedLinkage(F));
408    Vals.push_back(VE.getParamAttrID(F->getParamAttrs()));
409    Vals.push_back(Log2_32(F->getAlignment())+1);
410    Vals.push_back(F->hasSection() ? SectionMap[F->getSection()] : 0);
411    Vals.push_back(getEncodedVisibility(F));
412    Vals.push_back(F->hasCollector() ? CollectorMap[F->getCollector()] : 0);
413
414    unsigned AbbrevToUse = 0;
415    Stream.EmitRecord(bitc::MODULE_CODE_FUNCTION, Vals, AbbrevToUse);
416    Vals.clear();
417  }
418
419
420  // Emit the alias information.
421  for (Module::const_alias_iterator AI = M->alias_begin(), E = M->alias_end();
422       AI != E; ++AI) {
423    Vals.push_back(VE.getTypeID(AI->getType()));
424    Vals.push_back(VE.getValueID(AI->getAliasee()));
425    Vals.push_back(getEncodedLinkage(AI));
426    Vals.push_back(getEncodedVisibility(AI));
427    unsigned AbbrevToUse = 0;
428    Stream.EmitRecord(bitc::MODULE_CODE_ALIAS, Vals, AbbrevToUse);
429    Vals.clear();
430  }
431}
432
433
434static void WriteConstants(unsigned FirstVal, unsigned LastVal,
435                           const ValueEnumerator &VE,
436                           BitstreamWriter &Stream, bool isGlobal) {
437  if (FirstVal == LastVal) return;
438
439  Stream.EnterSubblock(bitc::CONSTANTS_BLOCK_ID, 4);
440
441  unsigned AggregateAbbrev = 0;
442  unsigned String8Abbrev = 0;
443  unsigned CString7Abbrev = 0;
444  unsigned CString6Abbrev = 0;
445  // If this is a constant pool for the module, emit module-specific abbrevs.
446  if (isGlobal) {
447    // Abbrev for CST_CODE_AGGREGATE.
448    BitCodeAbbrev *Abbv = new BitCodeAbbrev();
449    Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_AGGREGATE));
450    Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
451    Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, Log2_32_Ceil(LastVal+1)));
452    AggregateAbbrev = Stream.EmitAbbrev(Abbv);
453
454    // Abbrev for CST_CODE_STRING.
455    Abbv = new BitCodeAbbrev();
456    Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_STRING));
457    Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
458    Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
459    String8Abbrev = Stream.EmitAbbrev(Abbv);
460    // Abbrev for CST_CODE_CSTRING.
461    Abbv = new BitCodeAbbrev();
462    Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_CSTRING));
463    Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
464    Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7));
465    CString7Abbrev = Stream.EmitAbbrev(Abbv);
466    // Abbrev for CST_CODE_CSTRING.
467    Abbv = new BitCodeAbbrev();
468    Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_CSTRING));
469    Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
470    Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
471    CString6Abbrev = Stream.EmitAbbrev(Abbv);
472  }
473
474  SmallVector<uint64_t, 64> Record;
475
476  const ValueEnumerator::ValueList &Vals = VE.getValues();
477  const Type *LastTy = 0;
478  for (unsigned i = FirstVal; i != LastVal; ++i) {
479    const Value *V = Vals[i].first;
480    // If we need to switch types, do so now.
481    if (V->getType() != LastTy) {
482      LastTy = V->getType();
483      Record.push_back(VE.getTypeID(LastTy));
484      Stream.EmitRecord(bitc::CST_CODE_SETTYPE, Record,
485                        CONSTANTS_SETTYPE_ABBREV);
486      Record.clear();
487    }
488
489    if (const InlineAsm *IA = dyn_cast<InlineAsm>(V)) {
490      Record.push_back(unsigned(IA->hasSideEffects()));
491
492      // Add the asm string.
493      const std::string &AsmStr = IA->getAsmString();
494      Record.push_back(AsmStr.size());
495      for (unsigned i = 0, e = AsmStr.size(); i != e; ++i)
496        Record.push_back(AsmStr[i]);
497
498      // Add the constraint string.
499      const std::string &ConstraintStr = IA->getConstraintString();
500      Record.push_back(ConstraintStr.size());
501      for (unsigned i = 0, e = ConstraintStr.size(); i != e; ++i)
502        Record.push_back(ConstraintStr[i]);
503      Stream.EmitRecord(bitc::CST_CODE_INLINEASM, Record);
504      Record.clear();
505      continue;
506    }
507    const Constant *C = cast<Constant>(V);
508    unsigned Code = -1U;
509    unsigned AbbrevToUse = 0;
510    if (C->isNullValue()) {
511      Code = bitc::CST_CODE_NULL;
512    } else if (isa<UndefValue>(C)) {
513      Code = bitc::CST_CODE_UNDEF;
514    } else if (const ConstantInt *IV = dyn_cast<ConstantInt>(C)) {
515      if (IV->getBitWidth() <= 64) {
516        int64_t V = IV->getSExtValue();
517        if (V >= 0)
518          Record.push_back(V << 1);
519        else
520          Record.push_back((-V << 1) | 1);
521        Code = bitc::CST_CODE_INTEGER;
522        AbbrevToUse = CONSTANTS_INTEGER_ABBREV;
523      } else {                             // Wide integers, > 64 bits in size.
524        // We have an arbitrary precision integer value to write whose
525        // bit width is > 64. However, in canonical unsigned integer
526        // format it is likely that the high bits are going to be zero.
527        // So, we only write the number of active words.
528        unsigned NWords = IV->getValue().getActiveWords();
529        const uint64_t *RawWords = IV->getValue().getRawData();
530        for (unsigned i = 0; i != NWords; ++i) {
531          int64_t V = RawWords[i];
532          if (V >= 0)
533            Record.push_back(V << 1);
534          else
535            Record.push_back((-V << 1) | 1);
536        }
537        Code = bitc::CST_CODE_WIDE_INTEGER;
538      }
539    } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
540      Code = bitc::CST_CODE_FLOAT;
541      const Type *Ty = CFP->getType();
542      if (Ty == Type::FloatTy || Ty == Type::DoubleTy) {
543        Record.push_back(CFP->getValueAPF().convertToAPInt().getZExtValue());
544      } else if (Ty == Type::X86_FP80Ty) {
545        // api needed to prevent premature destruction
546        APInt api = CFP->getValueAPF().convertToAPInt();
547        const uint64_t *p = api.getRawData();
548        Record.push_back(p[0]);
549        Record.push_back((uint16_t)p[1]);
550      } else if (Ty == Type::FP128Ty || Ty == Type::PPC_FP128Ty) {
551        APInt api = CFP->getValueAPF().convertToAPInt();
552        const uint64_t *p = api.getRawData();
553        Record.push_back(p[0]);
554        Record.push_back(p[1]);
555      } else {
556        assert (0 && "Unknown FP type!");
557      }
558    } else if (isa<ConstantArray>(C) && cast<ConstantArray>(C)->isString()) {
559      // Emit constant strings specially.
560      unsigned NumOps = C->getNumOperands();
561      // If this is a null-terminated string, use the denser CSTRING encoding.
562      if (C->getOperand(NumOps-1)->isNullValue()) {
563        Code = bitc::CST_CODE_CSTRING;
564        --NumOps;  // Don't encode the null, which isn't allowed by char6.
565      } else {
566        Code = bitc::CST_CODE_STRING;
567        AbbrevToUse = String8Abbrev;
568      }
569      bool isCStr7 = Code == bitc::CST_CODE_CSTRING;
570      bool isCStrChar6 = Code == bitc::CST_CODE_CSTRING;
571      for (unsigned i = 0; i != NumOps; ++i) {
572        unsigned char V = cast<ConstantInt>(C->getOperand(i))->getZExtValue();
573        Record.push_back(V);
574        isCStr7 &= (V & 128) == 0;
575        if (isCStrChar6)
576          isCStrChar6 = BitCodeAbbrevOp::isChar6(V);
577      }
578
579      if (isCStrChar6)
580        AbbrevToUse = CString6Abbrev;
581      else if (isCStr7)
582        AbbrevToUse = CString7Abbrev;
583    } else if (isa<ConstantArray>(C) || isa<ConstantStruct>(V) ||
584               isa<ConstantVector>(V)) {
585      Code = bitc::CST_CODE_AGGREGATE;
586      for (unsigned i = 0, e = C->getNumOperands(); i != e; ++i)
587        Record.push_back(VE.getValueID(C->getOperand(i)));
588      AbbrevToUse = AggregateAbbrev;
589    } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
590      switch (CE->getOpcode()) {
591      default:
592        if (Instruction::isCast(CE->getOpcode())) {
593          Code = bitc::CST_CODE_CE_CAST;
594          Record.push_back(GetEncodedCastOpcode(CE->getOpcode()));
595          Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
596          Record.push_back(VE.getValueID(C->getOperand(0)));
597          AbbrevToUse = CONSTANTS_CE_CAST_Abbrev;
598        } else {
599          assert(CE->getNumOperands() == 2 && "Unknown constant expr!");
600          Code = bitc::CST_CODE_CE_BINOP;
601          Record.push_back(GetEncodedBinaryOpcode(CE->getOpcode()));
602          Record.push_back(VE.getValueID(C->getOperand(0)));
603          Record.push_back(VE.getValueID(C->getOperand(1)));
604        }
605        break;
606      case Instruction::GetElementPtr:
607        Code = bitc::CST_CODE_CE_GEP;
608        for (unsigned i = 0, e = CE->getNumOperands(); i != e; ++i) {
609          Record.push_back(VE.getTypeID(C->getOperand(i)->getType()));
610          Record.push_back(VE.getValueID(C->getOperand(i)));
611        }
612        break;
613      case Instruction::ExtractValue:
614        Code = bitc::CST_CODE_CE_EXTRACTVAL;
615        for (unsigned i = 0, e = CE->getNumOperands(); i != e; ++i) {
616          Record.push_back(VE.getTypeID(C->getOperand(i)->getType()));
617          Record.push_back(VE.getValueID(C->getOperand(i)));
618        }
619        break;
620      case Instruction::InsertValue:
621        Code = bitc::CST_CODE_CE_INSERTVAL;
622        for (unsigned i = 0, e = CE->getNumOperands(); i != e; ++i) {
623          Record.push_back(VE.getTypeID(C->getOperand(i)->getType()));
624          Record.push_back(VE.getValueID(C->getOperand(i)));
625        }
626        break;
627      case Instruction::Select:
628        Code = bitc::CST_CODE_CE_SELECT;
629        Record.push_back(VE.getValueID(C->getOperand(0)));
630        Record.push_back(VE.getValueID(C->getOperand(1)));
631        Record.push_back(VE.getValueID(C->getOperand(2)));
632        break;
633      case Instruction::ExtractElement:
634        Code = bitc::CST_CODE_CE_EXTRACTELT;
635        Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
636        Record.push_back(VE.getValueID(C->getOperand(0)));
637        Record.push_back(VE.getValueID(C->getOperand(1)));
638        break;
639      case Instruction::InsertElement:
640        Code = bitc::CST_CODE_CE_INSERTELT;
641        Record.push_back(VE.getValueID(C->getOperand(0)));
642        Record.push_back(VE.getValueID(C->getOperand(1)));
643        Record.push_back(VE.getValueID(C->getOperand(2)));
644        break;
645      case Instruction::ShuffleVector:
646        Code = bitc::CST_CODE_CE_SHUFFLEVEC;
647        Record.push_back(VE.getValueID(C->getOperand(0)));
648        Record.push_back(VE.getValueID(C->getOperand(1)));
649        Record.push_back(VE.getValueID(C->getOperand(2)));
650        break;
651      case Instruction::ICmp:
652      case Instruction::FCmp:
653      case Instruction::VICmp:
654      case Instruction::VFCmp:
655        Code = bitc::CST_CODE_CE_CMP;
656        Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
657        Record.push_back(VE.getValueID(C->getOperand(0)));
658        Record.push_back(VE.getValueID(C->getOperand(1)));
659        Record.push_back(CE->getPredicate());
660        break;
661      }
662    } else {
663      assert(0 && "Unknown constant!");
664    }
665    Stream.EmitRecord(Code, Record, AbbrevToUse);
666    Record.clear();
667  }
668
669  Stream.ExitBlock();
670}
671
672static void WriteModuleConstants(const ValueEnumerator &VE,
673                                 BitstreamWriter &Stream) {
674  const ValueEnumerator::ValueList &Vals = VE.getValues();
675
676  // Find the first constant to emit, which is the first non-globalvalue value.
677  // We know globalvalues have been emitted by WriteModuleInfo.
678  for (unsigned i = 0, e = Vals.size(); i != e; ++i) {
679    if (!isa<GlobalValue>(Vals[i].first)) {
680      WriteConstants(i, Vals.size(), VE, Stream, true);
681      return;
682    }
683  }
684}
685
686/// PushValueAndType - The file has to encode both the value and type id for
687/// many values, because we need to know what type to create for forward
688/// references.  However, most operands are not forward references, so this type
689/// field is not needed.
690///
691/// This function adds V's value ID to Vals.  If the value ID is higher than the
692/// instruction ID, then it is a forward reference, and it also includes the
693/// type ID.
694static bool PushValueAndType(Value *V, unsigned InstID,
695                             SmallVector<unsigned, 64> &Vals,
696                             ValueEnumerator &VE) {
697  unsigned ValID = VE.getValueID(V);
698  Vals.push_back(ValID);
699  if (ValID >= InstID) {
700    Vals.push_back(VE.getTypeID(V->getType()));
701    return true;
702  }
703  return false;
704}
705
706/// WriteInstruction - Emit an instruction to the specified stream.
707static void WriteInstruction(const Instruction &I, unsigned InstID,
708                             ValueEnumerator &VE, BitstreamWriter &Stream,
709                             SmallVector<unsigned, 64> &Vals) {
710  unsigned Code = 0;
711  unsigned AbbrevToUse = 0;
712  switch (I.getOpcode()) {
713  default:
714    if (Instruction::isCast(I.getOpcode())) {
715      Code = bitc::FUNC_CODE_INST_CAST;
716      if (!PushValueAndType(I.getOperand(0), InstID, Vals, VE))
717        AbbrevToUse = FUNCTION_INST_CAST_ABBREV;
718      Vals.push_back(VE.getTypeID(I.getType()));
719      Vals.push_back(GetEncodedCastOpcode(I.getOpcode()));
720    } else {
721      assert(isa<BinaryOperator>(I) && "Unknown instruction!");
722      Code = bitc::FUNC_CODE_INST_BINOP;
723      if (!PushValueAndType(I.getOperand(0), InstID, Vals, VE))
724        AbbrevToUse = FUNCTION_INST_BINOP_ABBREV;
725      Vals.push_back(VE.getValueID(I.getOperand(1)));
726      Vals.push_back(GetEncodedBinaryOpcode(I.getOpcode()));
727    }
728    break;
729
730  case Instruction::GetElementPtr:
731    Code = bitc::FUNC_CODE_INST_GEP;
732    for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
733      PushValueAndType(I.getOperand(i), InstID, Vals, VE);
734    break;
735  case Instruction::ExtractValue:
736    Code = bitc::FUNC_CODE_INST_EXTRACTVAL;
737    for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
738      PushValueAndType(I.getOperand(i), InstID, Vals, VE);
739    break;
740  case Instruction::InsertValue:
741    Code = bitc::FUNC_CODE_INST_INSERTVAL;
742    for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
743      PushValueAndType(I.getOperand(i), InstID, Vals, VE);
744    break;
745  case Instruction::Select:
746    Code = bitc::FUNC_CODE_INST_SELECT;
747    PushValueAndType(I.getOperand(1), InstID, Vals, VE);
748    Vals.push_back(VE.getValueID(I.getOperand(2)));
749    Vals.push_back(VE.getValueID(I.getOperand(0)));
750    break;
751  case Instruction::ExtractElement:
752    Code = bitc::FUNC_CODE_INST_EXTRACTELT;
753    PushValueAndType(I.getOperand(0), InstID, Vals, VE);
754    Vals.push_back(VE.getValueID(I.getOperand(1)));
755    break;
756  case Instruction::InsertElement:
757    Code = bitc::FUNC_CODE_INST_INSERTELT;
758    PushValueAndType(I.getOperand(0), InstID, Vals, VE);
759    Vals.push_back(VE.getValueID(I.getOperand(1)));
760    Vals.push_back(VE.getValueID(I.getOperand(2)));
761    break;
762  case Instruction::ShuffleVector:
763    Code = bitc::FUNC_CODE_INST_SHUFFLEVEC;
764    PushValueAndType(I.getOperand(0), InstID, Vals, VE);
765    Vals.push_back(VE.getValueID(I.getOperand(1)));
766    Vals.push_back(VE.getValueID(I.getOperand(2)));
767    break;
768  case Instruction::ICmp:
769  case Instruction::FCmp:
770  case Instruction::VICmp:
771  case Instruction::VFCmp:
772    Code = bitc::FUNC_CODE_INST_CMP;
773    PushValueAndType(I.getOperand(0), InstID, Vals, VE);
774    Vals.push_back(VE.getValueID(I.getOperand(1)));
775    Vals.push_back(cast<CmpInst>(I).getPredicate());
776    break;
777  case Instruction::GetResult:
778    Code = bitc::FUNC_CODE_INST_GETRESULT;
779    PushValueAndType(I.getOperand(0), InstID, Vals, VE);
780    Vals.push_back(cast<GetResultInst>(I).getIndex());
781    break;
782
783  case Instruction::Ret:
784    {
785      Code = bitc::FUNC_CODE_INST_RET;
786      unsigned NumOperands = I.getNumOperands();
787      if (NumOperands == 0)
788        AbbrevToUse = FUNCTION_INST_RET_VOID_ABBREV;
789      else if (NumOperands == 1) {
790        if (!PushValueAndType(I.getOperand(0), InstID, Vals, VE))
791          AbbrevToUse = FUNCTION_INST_RET_VAL_ABBREV;
792      } else {
793        for (unsigned i = 0, e = NumOperands; i != e; ++i)
794          PushValueAndType(I.getOperand(i), InstID, Vals, VE);
795      }
796    }
797    break;
798  case Instruction::Br:
799    Code = bitc::FUNC_CODE_INST_BR;
800    Vals.push_back(VE.getValueID(I.getOperand(0)));
801    if (cast<BranchInst>(I).isConditional()) {
802      Vals.push_back(VE.getValueID(I.getOperand(1)));
803      Vals.push_back(VE.getValueID(I.getOperand(2)));
804    }
805    break;
806  case Instruction::Switch:
807    Code = bitc::FUNC_CODE_INST_SWITCH;
808    Vals.push_back(VE.getTypeID(I.getOperand(0)->getType()));
809    for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
810      Vals.push_back(VE.getValueID(I.getOperand(i)));
811    break;
812  case Instruction::Invoke: {
813    const PointerType *PTy = cast<PointerType>(I.getOperand(0)->getType());
814    const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
815    Code = bitc::FUNC_CODE_INST_INVOKE;
816
817    const InvokeInst *II = cast<InvokeInst>(&I);
818    Vals.push_back(VE.getParamAttrID(II->getParamAttrs()));
819    Vals.push_back(II->getCallingConv());
820    Vals.push_back(VE.getValueID(I.getOperand(1)));      // normal dest
821    Vals.push_back(VE.getValueID(I.getOperand(2)));      // unwind dest
822    PushValueAndType(I.getOperand(0), InstID, Vals, VE); // callee
823
824    // Emit value #'s for the fixed parameters.
825    for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
826      Vals.push_back(VE.getValueID(I.getOperand(i+3)));  // fixed param.
827
828    // Emit type/value pairs for varargs params.
829    if (FTy->isVarArg()) {
830      for (unsigned i = 3+FTy->getNumParams(), e = I.getNumOperands();
831           i != e; ++i)
832        PushValueAndType(I.getOperand(i), InstID, Vals, VE); // vararg
833    }
834    break;
835  }
836  case Instruction::Unwind:
837    Code = bitc::FUNC_CODE_INST_UNWIND;
838    break;
839  case Instruction::Unreachable:
840    Code = bitc::FUNC_CODE_INST_UNREACHABLE;
841    AbbrevToUse = FUNCTION_INST_UNREACHABLE_ABBREV;
842    break;
843
844  case Instruction::PHI:
845    Code = bitc::FUNC_CODE_INST_PHI;
846    Vals.push_back(VE.getTypeID(I.getType()));
847    for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
848      Vals.push_back(VE.getValueID(I.getOperand(i)));
849    break;
850
851  case Instruction::Malloc:
852    Code = bitc::FUNC_CODE_INST_MALLOC;
853    Vals.push_back(VE.getTypeID(I.getType()));
854    Vals.push_back(VE.getValueID(I.getOperand(0))); // size.
855    Vals.push_back(Log2_32(cast<MallocInst>(I).getAlignment())+1);
856    break;
857
858  case Instruction::Free:
859    Code = bitc::FUNC_CODE_INST_FREE;
860    PushValueAndType(I.getOperand(0), InstID, Vals, VE);
861    break;
862
863  case Instruction::Alloca:
864    Code = bitc::FUNC_CODE_INST_ALLOCA;
865    Vals.push_back(VE.getTypeID(I.getType()));
866    Vals.push_back(VE.getValueID(I.getOperand(0))); // size.
867    Vals.push_back(Log2_32(cast<AllocaInst>(I).getAlignment())+1);
868    break;
869
870  case Instruction::Load:
871    Code = bitc::FUNC_CODE_INST_LOAD;
872    if (!PushValueAndType(I.getOperand(0), InstID, Vals, VE))  // ptr
873      AbbrevToUse = FUNCTION_INST_LOAD_ABBREV;
874
875    Vals.push_back(Log2_32(cast<LoadInst>(I).getAlignment())+1);
876    Vals.push_back(cast<LoadInst>(I).isVolatile());
877    break;
878  case Instruction::Store:
879    Code = bitc::FUNC_CODE_INST_STORE2;
880    PushValueAndType(I.getOperand(1), InstID, Vals, VE);  // ptrty + ptr
881    Vals.push_back(VE.getValueID(I.getOperand(0)));       // val.
882    Vals.push_back(Log2_32(cast<StoreInst>(I).getAlignment())+1);
883    Vals.push_back(cast<StoreInst>(I).isVolatile());
884    break;
885  case Instruction::Call: {
886    const PointerType *PTy = cast<PointerType>(I.getOperand(0)->getType());
887    const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
888
889    Code = bitc::FUNC_CODE_INST_CALL;
890
891    const CallInst *CI = cast<CallInst>(&I);
892    Vals.push_back(VE.getParamAttrID(CI->getParamAttrs()));
893    Vals.push_back((CI->getCallingConv() << 1) | unsigned(CI->isTailCall()));
894    PushValueAndType(CI->getOperand(0), InstID, Vals, VE);  // Callee
895
896    // Emit value #'s for the fixed parameters.
897    for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
898      Vals.push_back(VE.getValueID(I.getOperand(i+1)));  // fixed param.
899
900    // Emit type/value pairs for varargs params.
901    if (FTy->isVarArg()) {
902      unsigned NumVarargs = I.getNumOperands()-1-FTy->getNumParams();
903      for (unsigned i = I.getNumOperands()-NumVarargs, e = I.getNumOperands();
904           i != e; ++i)
905        PushValueAndType(I.getOperand(i), InstID, Vals, VE);  // varargs
906    }
907    break;
908  }
909  case Instruction::VAArg:
910    Code = bitc::FUNC_CODE_INST_VAARG;
911    Vals.push_back(VE.getTypeID(I.getOperand(0)->getType()));   // valistty
912    Vals.push_back(VE.getValueID(I.getOperand(0))); // valist.
913    Vals.push_back(VE.getTypeID(I.getType())); // restype.
914    break;
915  }
916
917  Stream.EmitRecord(Code, Vals, AbbrevToUse);
918  Vals.clear();
919}
920
921// Emit names for globals/functions etc.
922static void WriteValueSymbolTable(const ValueSymbolTable &VST,
923                                  const ValueEnumerator &VE,
924                                  BitstreamWriter &Stream) {
925  if (VST.empty()) return;
926  Stream.EnterSubblock(bitc::VALUE_SYMTAB_BLOCK_ID, 4);
927
928  // FIXME: Set up the abbrev, we know how many values there are!
929  // FIXME: We know if the type names can use 7-bit ascii.
930  SmallVector<unsigned, 64> NameVals;
931
932  for (ValueSymbolTable::const_iterator SI = VST.begin(), SE = VST.end();
933       SI != SE; ++SI) {
934
935    const ValueName &Name = *SI;
936
937    // Figure out the encoding to use for the name.
938    bool is7Bit = true;
939    bool isChar6 = true;
940    for (const char *C = Name.getKeyData(), *E = C+Name.getKeyLength();
941         C != E; ++C) {
942      if (isChar6)
943        isChar6 = BitCodeAbbrevOp::isChar6(*C);
944      if ((unsigned char)*C & 128) {
945        is7Bit = false;
946        break;  // don't bother scanning the rest.
947      }
948    }
949
950    unsigned AbbrevToUse = VST_ENTRY_8_ABBREV;
951
952    // VST_ENTRY:   [valueid, namechar x N]
953    // VST_BBENTRY: [bbid, namechar x N]
954    unsigned Code;
955    if (isa<BasicBlock>(SI->getValue())) {
956      Code = bitc::VST_CODE_BBENTRY;
957      if (isChar6)
958        AbbrevToUse = VST_BBENTRY_6_ABBREV;
959    } else {
960      Code = bitc::VST_CODE_ENTRY;
961      if (isChar6)
962        AbbrevToUse = VST_ENTRY_6_ABBREV;
963      else if (is7Bit)
964        AbbrevToUse = VST_ENTRY_7_ABBREV;
965    }
966
967    NameVals.push_back(VE.getValueID(SI->getValue()));
968    for (const char *P = Name.getKeyData(),
969         *E = Name.getKeyData()+Name.getKeyLength(); P != E; ++P)
970      NameVals.push_back((unsigned char)*P);
971
972    // Emit the finished record.
973    Stream.EmitRecord(Code, NameVals, AbbrevToUse);
974    NameVals.clear();
975  }
976  Stream.ExitBlock();
977}
978
979/// WriteFunction - Emit a function body to the module stream.
980static void WriteFunction(const Function &F, ValueEnumerator &VE,
981                          BitstreamWriter &Stream) {
982  Stream.EnterSubblock(bitc::FUNCTION_BLOCK_ID, 4);
983  VE.incorporateFunction(F);
984
985  SmallVector<unsigned, 64> Vals;
986
987  // Emit the number of basic blocks, so the reader can create them ahead of
988  // time.
989  Vals.push_back(VE.getBasicBlocks().size());
990  Stream.EmitRecord(bitc::FUNC_CODE_DECLAREBLOCKS, Vals);
991  Vals.clear();
992
993  // If there are function-local constants, emit them now.
994  unsigned CstStart, CstEnd;
995  VE.getFunctionConstantRange(CstStart, CstEnd);
996  WriteConstants(CstStart, CstEnd, VE, Stream, false);
997
998  // Keep a running idea of what the instruction ID is.
999  unsigned InstID = CstEnd;
1000
1001  // Finally, emit all the instructions, in order.
1002  for (Function::const_iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
1003    for (BasicBlock::const_iterator I = BB->begin(), E = BB->end();
1004         I != E; ++I) {
1005      WriteInstruction(*I, InstID, VE, Stream, Vals);
1006      if (I->getType() != Type::VoidTy)
1007        ++InstID;
1008    }
1009
1010  // Emit names for all the instructions etc.
1011  WriteValueSymbolTable(F.getValueSymbolTable(), VE, Stream);
1012
1013  VE.purgeFunction();
1014  Stream.ExitBlock();
1015}
1016
1017/// WriteTypeSymbolTable - Emit a block for the specified type symtab.
1018static void WriteTypeSymbolTable(const TypeSymbolTable &TST,
1019                                 const ValueEnumerator &VE,
1020                                 BitstreamWriter &Stream) {
1021  if (TST.empty()) return;
1022
1023  Stream.EnterSubblock(bitc::TYPE_SYMTAB_BLOCK_ID, 3);
1024
1025  // 7-bit fixed width VST_CODE_ENTRY strings.
1026  BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1027  Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_ENTRY));
1028  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
1029                            Log2_32_Ceil(VE.getTypes().size()+1)));
1030  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1031  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7));
1032  unsigned V7Abbrev = Stream.EmitAbbrev(Abbv);
1033
1034  SmallVector<unsigned, 64> NameVals;
1035
1036  for (TypeSymbolTable::const_iterator TI = TST.begin(), TE = TST.end();
1037       TI != TE; ++TI) {
1038    // TST_ENTRY: [typeid, namechar x N]
1039    NameVals.push_back(VE.getTypeID(TI->second));
1040
1041    const std::string &Str = TI->first;
1042    bool is7Bit = true;
1043    for (unsigned i = 0, e = Str.size(); i != e; ++i) {
1044      NameVals.push_back((unsigned char)Str[i]);
1045      if (Str[i] & 128)
1046        is7Bit = false;
1047    }
1048
1049    // Emit the finished record.
1050    Stream.EmitRecord(bitc::VST_CODE_ENTRY, NameVals, is7Bit ? V7Abbrev : 0);
1051    NameVals.clear();
1052  }
1053
1054  Stream.ExitBlock();
1055}
1056
1057// Emit blockinfo, which defines the standard abbreviations etc.
1058static void WriteBlockInfo(const ValueEnumerator &VE, BitstreamWriter &Stream) {
1059  // We only want to emit block info records for blocks that have multiple
1060  // instances: CONSTANTS_BLOCK, FUNCTION_BLOCK and VALUE_SYMTAB_BLOCK.  Other
1061  // blocks can defined their abbrevs inline.
1062  Stream.EnterBlockInfoBlock(2);
1063
1064  { // 8-bit fixed-width VST_ENTRY/VST_BBENTRY strings.
1065    BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1066    Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 3));
1067    Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
1068    Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1069    Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
1070    if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID,
1071                                   Abbv) != VST_ENTRY_8_ABBREV)
1072      assert(0 && "Unexpected abbrev ordering!");
1073  }
1074
1075  { // 7-bit fixed width VST_ENTRY strings.
1076    BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1077    Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_ENTRY));
1078    Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
1079    Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1080    Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7));
1081    if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID,
1082                                   Abbv) != VST_ENTRY_7_ABBREV)
1083      assert(0 && "Unexpected abbrev ordering!");
1084  }
1085  { // 6-bit char6 VST_ENTRY strings.
1086    BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1087    Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_ENTRY));
1088    Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
1089    Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1090    Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
1091    if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID,
1092                                   Abbv) != VST_ENTRY_6_ABBREV)
1093      assert(0 && "Unexpected abbrev ordering!");
1094  }
1095  { // 6-bit char6 VST_BBENTRY strings.
1096    BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1097    Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_BBENTRY));
1098    Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
1099    Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1100    Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
1101    if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID,
1102                                   Abbv) != VST_BBENTRY_6_ABBREV)
1103      assert(0 && "Unexpected abbrev ordering!");
1104  }
1105
1106
1107
1108  { // SETTYPE abbrev for CONSTANTS_BLOCK.
1109    BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1110    Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_SETTYPE));
1111    Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
1112                              Log2_32_Ceil(VE.getTypes().size()+1)));
1113    if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID,
1114                                   Abbv) != CONSTANTS_SETTYPE_ABBREV)
1115      assert(0 && "Unexpected abbrev ordering!");
1116  }
1117
1118  { // INTEGER abbrev for CONSTANTS_BLOCK.
1119    BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1120    Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_INTEGER));
1121    Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
1122    if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID,
1123                                   Abbv) != CONSTANTS_INTEGER_ABBREV)
1124      assert(0 && "Unexpected abbrev ordering!");
1125  }
1126
1127  { // CE_CAST abbrev for CONSTANTS_BLOCK.
1128    BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1129    Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_CE_CAST));
1130    Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4));  // cast opc
1131    Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,       // typeid
1132                              Log2_32_Ceil(VE.getTypes().size()+1)));
1133    Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));    // value id
1134
1135    if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID,
1136                                   Abbv) != CONSTANTS_CE_CAST_Abbrev)
1137      assert(0 && "Unexpected abbrev ordering!");
1138  }
1139  { // NULL abbrev for CONSTANTS_BLOCK.
1140    BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1141    Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_NULL));
1142    if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID,
1143                                   Abbv) != CONSTANTS_NULL_Abbrev)
1144      assert(0 && "Unexpected abbrev ordering!");
1145  }
1146
1147  // FIXME: This should only use space for first class types!
1148
1149  { // INST_LOAD abbrev for FUNCTION_BLOCK.
1150    BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1151    Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_LOAD));
1152    Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Ptr
1153    Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // Align
1154    Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // volatile
1155    if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
1156                                   Abbv) != FUNCTION_INST_LOAD_ABBREV)
1157      assert(0 && "Unexpected abbrev ordering!");
1158  }
1159  { // INST_BINOP abbrev for FUNCTION_BLOCK.
1160    BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1161    Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_BINOP));
1162    Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // LHS
1163    Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // RHS
1164    Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
1165    if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
1166                                   Abbv) != FUNCTION_INST_BINOP_ABBREV)
1167      assert(0 && "Unexpected abbrev ordering!");
1168  }
1169  { // INST_CAST abbrev for FUNCTION_BLOCK.
1170    BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1171    Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_CAST));
1172    Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));    // OpVal
1173    Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,       // dest ty
1174                              Log2_32_Ceil(VE.getTypes().size()+1)));
1175    Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4));  // opc
1176    if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
1177                                   Abbv) != FUNCTION_INST_CAST_ABBREV)
1178      assert(0 && "Unexpected abbrev ordering!");
1179  }
1180
1181  { // INST_RET abbrev for FUNCTION_BLOCK.
1182    BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1183    Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_RET));
1184    if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
1185                                   Abbv) != FUNCTION_INST_RET_VOID_ABBREV)
1186      assert(0 && "Unexpected abbrev ordering!");
1187  }
1188  { // INST_RET abbrev for FUNCTION_BLOCK.
1189    BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1190    Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_RET));
1191    Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // ValID
1192    if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
1193                                   Abbv) != FUNCTION_INST_RET_VAL_ABBREV)
1194      assert(0 && "Unexpected abbrev ordering!");
1195  }
1196  { // INST_UNREACHABLE abbrev for FUNCTION_BLOCK.
1197    BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1198    Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_UNREACHABLE));
1199    if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
1200                                   Abbv) != FUNCTION_INST_UNREACHABLE_ABBREV)
1201      assert(0 && "Unexpected abbrev ordering!");
1202  }
1203
1204  Stream.ExitBlock();
1205}
1206
1207
1208/// WriteModule - Emit the specified module to the bitstream.
1209static void WriteModule(const Module *M, BitstreamWriter &Stream) {
1210  Stream.EnterSubblock(bitc::MODULE_BLOCK_ID, 3);
1211
1212  // Emit the version number if it is non-zero.
1213  if (CurVersion) {
1214    SmallVector<unsigned, 1> Vals;
1215    Vals.push_back(CurVersion);
1216    Stream.EmitRecord(bitc::MODULE_CODE_VERSION, Vals);
1217  }
1218
1219  // Analyze the module, enumerating globals, functions, etc.
1220  ValueEnumerator VE(M);
1221
1222  // Emit blockinfo, which defines the standard abbreviations etc.
1223  WriteBlockInfo(VE, Stream);
1224
1225  // Emit information about parameter attributes.
1226  WriteParamAttrTable(VE, Stream);
1227
1228  // Emit information describing all of the types in the module.
1229  WriteTypeTable(VE, Stream);
1230
1231  // Emit top-level description of module, including target triple, inline asm,
1232  // descriptors for global variables, and function prototype info.
1233  WriteModuleInfo(M, VE, Stream);
1234
1235  // Emit constants.
1236  WriteModuleConstants(VE, Stream);
1237
1238  // If we have any aggregate values in the value table, purge them - these can
1239  // only be used to initialize global variables.  Doing so makes the value
1240  // namespace smaller for code in functions.
1241  int NumNonAggregates = VE.PurgeAggregateValues();
1242  if (NumNonAggregates != -1) {
1243    SmallVector<unsigned, 1> Vals;
1244    Vals.push_back(NumNonAggregates);
1245    Stream.EmitRecord(bitc::MODULE_CODE_PURGEVALS, Vals);
1246  }
1247
1248  // Emit function bodies.
1249  for (Module::const_iterator I = M->begin(), E = M->end(); I != E; ++I)
1250    if (!I->isDeclaration())
1251      WriteFunction(*I, VE, Stream);
1252
1253  // Emit the type symbol table information.
1254  WriteTypeSymbolTable(M->getTypeSymbolTable(), VE, Stream);
1255
1256  // Emit names for globals/functions etc.
1257  WriteValueSymbolTable(M->getValueSymbolTable(), VE, Stream);
1258
1259  Stream.ExitBlock();
1260}
1261
1262
1263/// WriteBitcodeToFile - Write the specified module to the specified output
1264/// stream.
1265void llvm::WriteBitcodeToFile(const Module *M, std::ostream &Out) {
1266  std::vector<unsigned char> Buffer;
1267  BitstreamWriter Stream(Buffer);
1268
1269  Buffer.reserve(256*1024);
1270
1271  // Emit the file header.
1272  Stream.Emit((unsigned)'B', 8);
1273  Stream.Emit((unsigned)'C', 8);
1274  Stream.Emit(0x0, 4);
1275  Stream.Emit(0xC, 4);
1276  Stream.Emit(0xE, 4);
1277  Stream.Emit(0xD, 4);
1278
1279  // Emit the module.
1280  WriteModule(M, Stream);
1281
1282  // Write the generated bitstream to "Out".
1283  Out.write((char*)&Buffer.front(), Buffer.size());
1284
1285  // Make sure it hits disk now.
1286  Out.flush();
1287}
1288