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