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