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