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