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