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