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