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