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