[WinEH] Add cleanupendpad instruction
[oota-llvm.git] / lib / Bitcode / Writer / BitcodeWriter.cpp
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 "ValueEnumerator.h"
16 #include "llvm/ADT/Triple.h"
17 #include "llvm/Bitcode/BitstreamWriter.h"
18 #include "llvm/Bitcode/LLVMBitCodes.h"
19 #include "llvm/IR/Constants.h"
20 #include "llvm/IR/DebugInfoMetadata.h"
21 #include "llvm/IR/DerivedTypes.h"
22 #include "llvm/IR/InlineAsm.h"
23 #include "llvm/IR/Instructions.h"
24 #include "llvm/IR/Module.h"
25 #include "llvm/IR/Operator.h"
26 #include "llvm/IR/UseListOrder.h"
27 #include "llvm/IR/ValueSymbolTable.h"
28 #include "llvm/Support/CommandLine.h"
29 #include "llvm/Support/ErrorHandling.h"
30 #include "llvm/Support/MathExtras.h"
31 #include "llvm/Support/Program.h"
32 #include "llvm/Support/raw_ostream.h"
33 #include <cctype>
34 #include <map>
35 using namespace llvm;
36
37 /// These are manifest constants used by the bitcode writer. They do not need to
38 /// be kept in sync with the reader, but need to be consistent within this file.
39 enum {
40   // VALUE_SYMTAB_BLOCK abbrev id's.
41   VST_ENTRY_8_ABBREV = bitc::FIRST_APPLICATION_ABBREV,
42   VST_ENTRY_7_ABBREV,
43   VST_ENTRY_6_ABBREV,
44   VST_BBENTRY_6_ABBREV,
45
46   // CONSTANTS_BLOCK abbrev id's.
47   CONSTANTS_SETTYPE_ABBREV = bitc::FIRST_APPLICATION_ABBREV,
48   CONSTANTS_INTEGER_ABBREV,
49   CONSTANTS_CE_CAST_Abbrev,
50   CONSTANTS_NULL_Abbrev,
51
52   // FUNCTION_BLOCK abbrev id's.
53   FUNCTION_INST_LOAD_ABBREV = bitc::FIRST_APPLICATION_ABBREV,
54   FUNCTION_INST_BINOP_ABBREV,
55   FUNCTION_INST_BINOP_FLAGS_ABBREV,
56   FUNCTION_INST_CAST_ABBREV,
57   FUNCTION_INST_RET_VOID_ABBREV,
58   FUNCTION_INST_RET_VAL_ABBREV,
59   FUNCTION_INST_UNREACHABLE_ABBREV,
60   FUNCTION_INST_GEP_ABBREV,
61 };
62
63 static unsigned GetEncodedCastOpcode(unsigned Opcode) {
64   switch (Opcode) {
65   default: llvm_unreachable("Unknown cast instruction!");
66   case Instruction::Trunc   : return bitc::CAST_TRUNC;
67   case Instruction::ZExt    : return bitc::CAST_ZEXT;
68   case Instruction::SExt    : return bitc::CAST_SEXT;
69   case Instruction::FPToUI  : return bitc::CAST_FPTOUI;
70   case Instruction::FPToSI  : return bitc::CAST_FPTOSI;
71   case Instruction::UIToFP  : return bitc::CAST_UITOFP;
72   case Instruction::SIToFP  : return bitc::CAST_SITOFP;
73   case Instruction::FPTrunc : return bitc::CAST_FPTRUNC;
74   case Instruction::FPExt   : return bitc::CAST_FPEXT;
75   case Instruction::PtrToInt: return bitc::CAST_PTRTOINT;
76   case Instruction::IntToPtr: return bitc::CAST_INTTOPTR;
77   case Instruction::BitCast : return bitc::CAST_BITCAST;
78   case Instruction::AddrSpaceCast: return bitc::CAST_ADDRSPACECAST;
79   }
80 }
81
82 static unsigned GetEncodedBinaryOpcode(unsigned Opcode) {
83   switch (Opcode) {
84   default: llvm_unreachable("Unknown binary instruction!");
85   case Instruction::Add:
86   case Instruction::FAdd: return bitc::BINOP_ADD;
87   case Instruction::Sub:
88   case Instruction::FSub: return bitc::BINOP_SUB;
89   case Instruction::Mul:
90   case Instruction::FMul: return bitc::BINOP_MUL;
91   case Instruction::UDiv: return bitc::BINOP_UDIV;
92   case Instruction::FDiv:
93   case Instruction::SDiv: return bitc::BINOP_SDIV;
94   case Instruction::URem: return bitc::BINOP_UREM;
95   case Instruction::FRem:
96   case Instruction::SRem: return bitc::BINOP_SREM;
97   case Instruction::Shl:  return bitc::BINOP_SHL;
98   case Instruction::LShr: return bitc::BINOP_LSHR;
99   case Instruction::AShr: return bitc::BINOP_ASHR;
100   case Instruction::And:  return bitc::BINOP_AND;
101   case Instruction::Or:   return bitc::BINOP_OR;
102   case Instruction::Xor:  return bitc::BINOP_XOR;
103   }
104 }
105
106 static unsigned GetEncodedRMWOperation(AtomicRMWInst::BinOp Op) {
107   switch (Op) {
108   default: llvm_unreachable("Unknown RMW operation!");
109   case AtomicRMWInst::Xchg: return bitc::RMW_XCHG;
110   case AtomicRMWInst::Add: return bitc::RMW_ADD;
111   case AtomicRMWInst::Sub: return bitc::RMW_SUB;
112   case AtomicRMWInst::And: return bitc::RMW_AND;
113   case AtomicRMWInst::Nand: return bitc::RMW_NAND;
114   case AtomicRMWInst::Or: return bitc::RMW_OR;
115   case AtomicRMWInst::Xor: return bitc::RMW_XOR;
116   case AtomicRMWInst::Max: return bitc::RMW_MAX;
117   case AtomicRMWInst::Min: return bitc::RMW_MIN;
118   case AtomicRMWInst::UMax: return bitc::RMW_UMAX;
119   case AtomicRMWInst::UMin: return bitc::RMW_UMIN;
120   }
121 }
122
123 static unsigned GetEncodedOrdering(AtomicOrdering Ordering) {
124   switch (Ordering) {
125   case NotAtomic: return bitc::ORDERING_NOTATOMIC;
126   case Unordered: return bitc::ORDERING_UNORDERED;
127   case Monotonic: return bitc::ORDERING_MONOTONIC;
128   case Acquire: return bitc::ORDERING_ACQUIRE;
129   case Release: return bitc::ORDERING_RELEASE;
130   case AcquireRelease: return bitc::ORDERING_ACQREL;
131   case SequentiallyConsistent: return bitc::ORDERING_SEQCST;
132   }
133   llvm_unreachable("Invalid ordering");
134 }
135
136 static unsigned GetEncodedSynchScope(SynchronizationScope SynchScope) {
137   switch (SynchScope) {
138   case SingleThread: return bitc::SYNCHSCOPE_SINGLETHREAD;
139   case CrossThread: return bitc::SYNCHSCOPE_CROSSTHREAD;
140   }
141   llvm_unreachable("Invalid synch scope");
142 }
143
144 static void WriteStringRecord(unsigned Code, StringRef Str,
145                               unsigned AbbrevToUse, BitstreamWriter &Stream) {
146   SmallVector<unsigned, 64> Vals;
147
148   // Code: [strchar x N]
149   for (unsigned i = 0, e = Str.size(); i != e; ++i) {
150     if (AbbrevToUse && !BitCodeAbbrevOp::isChar6(Str[i]))
151       AbbrevToUse = 0;
152     Vals.push_back(Str[i]);
153   }
154
155   // Emit the finished record.
156   Stream.EmitRecord(Code, Vals, AbbrevToUse);
157 }
158
159 static uint64_t getAttrKindEncoding(Attribute::AttrKind Kind) {
160   switch (Kind) {
161   case Attribute::Alignment:
162     return bitc::ATTR_KIND_ALIGNMENT;
163   case Attribute::AlwaysInline:
164     return bitc::ATTR_KIND_ALWAYS_INLINE;
165   case Attribute::ArgMemOnly:
166     return bitc::ATTR_KIND_ARGMEMONLY;
167   case Attribute::Builtin:
168     return bitc::ATTR_KIND_BUILTIN;
169   case Attribute::ByVal:
170     return bitc::ATTR_KIND_BY_VAL;
171   case Attribute::Convergent:
172     return bitc::ATTR_KIND_CONVERGENT;
173   case Attribute::InAlloca:
174     return bitc::ATTR_KIND_IN_ALLOCA;
175   case Attribute::Cold:
176     return bitc::ATTR_KIND_COLD;
177   case Attribute::InlineHint:
178     return bitc::ATTR_KIND_INLINE_HINT;
179   case Attribute::InReg:
180     return bitc::ATTR_KIND_IN_REG;
181   case Attribute::JumpTable:
182     return bitc::ATTR_KIND_JUMP_TABLE;
183   case Attribute::MinSize:
184     return bitc::ATTR_KIND_MIN_SIZE;
185   case Attribute::Naked:
186     return bitc::ATTR_KIND_NAKED;
187   case Attribute::Nest:
188     return bitc::ATTR_KIND_NEST;
189   case Attribute::NoAlias:
190     return bitc::ATTR_KIND_NO_ALIAS;
191   case Attribute::NoBuiltin:
192     return bitc::ATTR_KIND_NO_BUILTIN;
193   case Attribute::NoCapture:
194     return bitc::ATTR_KIND_NO_CAPTURE;
195   case Attribute::NoDuplicate:
196     return bitc::ATTR_KIND_NO_DUPLICATE;
197   case Attribute::NoImplicitFloat:
198     return bitc::ATTR_KIND_NO_IMPLICIT_FLOAT;
199   case Attribute::NoInline:
200     return bitc::ATTR_KIND_NO_INLINE;
201   case Attribute::NonLazyBind:
202     return bitc::ATTR_KIND_NON_LAZY_BIND;
203   case Attribute::NonNull:
204     return bitc::ATTR_KIND_NON_NULL;
205   case Attribute::Dereferenceable:
206     return bitc::ATTR_KIND_DEREFERENCEABLE;
207   case Attribute::DereferenceableOrNull:
208     return bitc::ATTR_KIND_DEREFERENCEABLE_OR_NULL;
209   case Attribute::NoRedZone:
210     return bitc::ATTR_KIND_NO_RED_ZONE;
211   case Attribute::NoReturn:
212     return bitc::ATTR_KIND_NO_RETURN;
213   case Attribute::NoUnwind:
214     return bitc::ATTR_KIND_NO_UNWIND;
215   case Attribute::OptimizeForSize:
216     return bitc::ATTR_KIND_OPTIMIZE_FOR_SIZE;
217   case Attribute::OptimizeNone:
218     return bitc::ATTR_KIND_OPTIMIZE_NONE;
219   case Attribute::ReadNone:
220     return bitc::ATTR_KIND_READ_NONE;
221   case Attribute::ReadOnly:
222     return bitc::ATTR_KIND_READ_ONLY;
223   case Attribute::Returned:
224     return bitc::ATTR_KIND_RETURNED;
225   case Attribute::ReturnsTwice:
226     return bitc::ATTR_KIND_RETURNS_TWICE;
227   case Attribute::SExt:
228     return bitc::ATTR_KIND_S_EXT;
229   case Attribute::StackAlignment:
230     return bitc::ATTR_KIND_STACK_ALIGNMENT;
231   case Attribute::StackProtect:
232     return bitc::ATTR_KIND_STACK_PROTECT;
233   case Attribute::StackProtectReq:
234     return bitc::ATTR_KIND_STACK_PROTECT_REQ;
235   case Attribute::StackProtectStrong:
236     return bitc::ATTR_KIND_STACK_PROTECT_STRONG;
237   case Attribute::SafeStack:
238     return bitc::ATTR_KIND_SAFESTACK;
239   case Attribute::StructRet:
240     return bitc::ATTR_KIND_STRUCT_RET;
241   case Attribute::SanitizeAddress:
242     return bitc::ATTR_KIND_SANITIZE_ADDRESS;
243   case Attribute::SanitizeThread:
244     return bitc::ATTR_KIND_SANITIZE_THREAD;
245   case Attribute::SanitizeMemory:
246     return bitc::ATTR_KIND_SANITIZE_MEMORY;
247   case Attribute::UWTable:
248     return bitc::ATTR_KIND_UW_TABLE;
249   case Attribute::ZExt:
250     return bitc::ATTR_KIND_Z_EXT;
251   case Attribute::EndAttrKinds:
252     llvm_unreachable("Can not encode end-attribute kinds marker.");
253   case Attribute::None:
254     llvm_unreachable("Can not encode none-attribute.");
255   }
256
257   llvm_unreachable("Trying to encode unknown attribute");
258 }
259
260 static void WriteAttributeGroupTable(const ValueEnumerator &VE,
261                                      BitstreamWriter &Stream) {
262   const std::vector<AttributeSet> &AttrGrps = VE.getAttributeGroups();
263   if (AttrGrps.empty()) return;
264
265   Stream.EnterSubblock(bitc::PARAMATTR_GROUP_BLOCK_ID, 3);
266
267   SmallVector<uint64_t, 64> Record;
268   for (unsigned i = 0, e = AttrGrps.size(); i != e; ++i) {
269     AttributeSet AS = AttrGrps[i];
270     for (unsigned i = 0, e = AS.getNumSlots(); i != e; ++i) {
271       AttributeSet A = AS.getSlotAttributes(i);
272
273       Record.push_back(VE.getAttributeGroupID(A));
274       Record.push_back(AS.getSlotIndex(i));
275
276       for (AttributeSet::iterator I = AS.begin(0), E = AS.end(0);
277            I != E; ++I) {
278         Attribute Attr = *I;
279         if (Attr.isEnumAttribute()) {
280           Record.push_back(0);
281           Record.push_back(getAttrKindEncoding(Attr.getKindAsEnum()));
282         } else if (Attr.isIntAttribute()) {
283           Record.push_back(1);
284           Record.push_back(getAttrKindEncoding(Attr.getKindAsEnum()));
285           Record.push_back(Attr.getValueAsInt());
286         } else {
287           StringRef Kind = Attr.getKindAsString();
288           StringRef Val = Attr.getValueAsString();
289
290           Record.push_back(Val.empty() ? 3 : 4);
291           Record.append(Kind.begin(), Kind.end());
292           Record.push_back(0);
293           if (!Val.empty()) {
294             Record.append(Val.begin(), Val.end());
295             Record.push_back(0);
296           }
297         }
298       }
299
300       Stream.EmitRecord(bitc::PARAMATTR_GRP_CODE_ENTRY, Record);
301       Record.clear();
302     }
303   }
304
305   Stream.ExitBlock();
306 }
307
308 static void WriteAttributeTable(const ValueEnumerator &VE,
309                                 BitstreamWriter &Stream) {
310   const std::vector<AttributeSet> &Attrs = VE.getAttributes();
311   if (Attrs.empty()) return;
312
313   Stream.EnterSubblock(bitc::PARAMATTR_BLOCK_ID, 3);
314
315   SmallVector<uint64_t, 64> Record;
316   for (unsigned i = 0, e = Attrs.size(); i != e; ++i) {
317     const AttributeSet &A = Attrs[i];
318     for (unsigned i = 0, e = A.getNumSlots(); i != e; ++i)
319       Record.push_back(VE.getAttributeGroupID(A.getSlotAttributes(i)));
320
321     Stream.EmitRecord(bitc::PARAMATTR_CODE_ENTRY, Record);
322     Record.clear();
323   }
324
325   Stream.ExitBlock();
326 }
327
328 /// WriteTypeTable - Write out the type table for a module.
329 static void WriteTypeTable(const ValueEnumerator &VE, BitstreamWriter &Stream) {
330   const ValueEnumerator::TypeList &TypeList = VE.getTypes();
331
332   Stream.EnterSubblock(bitc::TYPE_BLOCK_ID_NEW, 4 /*count from # abbrevs */);
333   SmallVector<uint64_t, 64> TypeVals;
334
335   uint64_t NumBits = VE.computeBitsRequiredForTypeIndicies();
336
337   // Abbrev for TYPE_CODE_POINTER.
338   BitCodeAbbrev *Abbv = new BitCodeAbbrev();
339   Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_POINTER));
340   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
341   Abbv->Add(BitCodeAbbrevOp(0));  // Addrspace = 0
342   unsigned PtrAbbrev = Stream.EmitAbbrev(Abbv);
343
344   // Abbrev for TYPE_CODE_FUNCTION.
345   Abbv = new BitCodeAbbrev();
346   Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_FUNCTION));
347   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));  // isvararg
348   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
349   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
350
351   unsigned FunctionAbbrev = Stream.EmitAbbrev(Abbv);
352
353   // Abbrev for TYPE_CODE_STRUCT_ANON.
354   Abbv = new BitCodeAbbrev();
355   Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_STRUCT_ANON));
356   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));  // ispacked
357   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
358   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
359
360   unsigned StructAnonAbbrev = Stream.EmitAbbrev(Abbv);
361
362   // Abbrev for TYPE_CODE_STRUCT_NAME.
363   Abbv = new BitCodeAbbrev();
364   Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_STRUCT_NAME));
365   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
366   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
367   unsigned StructNameAbbrev = Stream.EmitAbbrev(Abbv);
368
369   // Abbrev for TYPE_CODE_STRUCT_NAMED.
370   Abbv = new BitCodeAbbrev();
371   Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_STRUCT_NAMED));
372   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));  // ispacked
373   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
374   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
375
376   unsigned StructNamedAbbrev = Stream.EmitAbbrev(Abbv);
377
378   // Abbrev for TYPE_CODE_ARRAY.
379   Abbv = new BitCodeAbbrev();
380   Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_ARRAY));
381   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));   // size
382   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
383
384   unsigned ArrayAbbrev = Stream.EmitAbbrev(Abbv);
385
386   // Emit an entry count so the reader can reserve space.
387   TypeVals.push_back(TypeList.size());
388   Stream.EmitRecord(bitc::TYPE_CODE_NUMENTRY, TypeVals);
389   TypeVals.clear();
390
391   // Loop over all of the types, emitting each in turn.
392   for (unsigned i = 0, e = TypeList.size(); i != e; ++i) {
393     Type *T = TypeList[i];
394     int AbbrevToUse = 0;
395     unsigned Code = 0;
396
397     switch (T->getTypeID()) {
398     case Type::VoidTyID:      Code = bitc::TYPE_CODE_VOID;      break;
399     case Type::HalfTyID:      Code = bitc::TYPE_CODE_HALF;      break;
400     case Type::FloatTyID:     Code = bitc::TYPE_CODE_FLOAT;     break;
401     case Type::DoubleTyID:    Code = bitc::TYPE_CODE_DOUBLE;    break;
402     case Type::X86_FP80TyID:  Code = bitc::TYPE_CODE_X86_FP80;  break;
403     case Type::FP128TyID:     Code = bitc::TYPE_CODE_FP128;     break;
404     case Type::PPC_FP128TyID: Code = bitc::TYPE_CODE_PPC_FP128; break;
405     case Type::LabelTyID:     Code = bitc::TYPE_CODE_LABEL;     break;
406     case Type::MetadataTyID:  Code = bitc::TYPE_CODE_METADATA;  break;
407     case Type::X86_MMXTyID:   Code = bitc::TYPE_CODE_X86_MMX;   break;
408     case Type::TokenTyID:     Code = bitc::TYPE_CODE_TOKEN;     break;
409     case Type::IntegerTyID:
410       // INTEGER: [width]
411       Code = bitc::TYPE_CODE_INTEGER;
412       TypeVals.push_back(cast<IntegerType>(T)->getBitWidth());
413       break;
414     case Type::PointerTyID: {
415       PointerType *PTy = cast<PointerType>(T);
416       // POINTER: [pointee type, address space]
417       Code = bitc::TYPE_CODE_POINTER;
418       TypeVals.push_back(VE.getTypeID(PTy->getElementType()));
419       unsigned AddressSpace = PTy->getAddressSpace();
420       TypeVals.push_back(AddressSpace);
421       if (AddressSpace == 0) AbbrevToUse = PtrAbbrev;
422       break;
423     }
424     case Type::FunctionTyID: {
425       FunctionType *FT = cast<FunctionType>(T);
426       // FUNCTION: [isvararg, retty, paramty x N]
427       Code = bitc::TYPE_CODE_FUNCTION;
428       TypeVals.push_back(FT->isVarArg());
429       TypeVals.push_back(VE.getTypeID(FT->getReturnType()));
430       for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i)
431         TypeVals.push_back(VE.getTypeID(FT->getParamType(i)));
432       AbbrevToUse = FunctionAbbrev;
433       break;
434     }
435     case Type::StructTyID: {
436       StructType *ST = cast<StructType>(T);
437       // STRUCT: [ispacked, eltty x N]
438       TypeVals.push_back(ST->isPacked());
439       // Output all of the element types.
440       for (StructType::element_iterator I = ST->element_begin(),
441            E = ST->element_end(); I != E; ++I)
442         TypeVals.push_back(VE.getTypeID(*I));
443
444       if (ST->isLiteral()) {
445         Code = bitc::TYPE_CODE_STRUCT_ANON;
446         AbbrevToUse = StructAnonAbbrev;
447       } else {
448         if (ST->isOpaque()) {
449           Code = bitc::TYPE_CODE_OPAQUE;
450         } else {
451           Code = bitc::TYPE_CODE_STRUCT_NAMED;
452           AbbrevToUse = StructNamedAbbrev;
453         }
454
455         // Emit the name if it is present.
456         if (!ST->getName().empty())
457           WriteStringRecord(bitc::TYPE_CODE_STRUCT_NAME, ST->getName(),
458                             StructNameAbbrev, Stream);
459       }
460       break;
461     }
462     case Type::ArrayTyID: {
463       ArrayType *AT = cast<ArrayType>(T);
464       // ARRAY: [numelts, eltty]
465       Code = bitc::TYPE_CODE_ARRAY;
466       TypeVals.push_back(AT->getNumElements());
467       TypeVals.push_back(VE.getTypeID(AT->getElementType()));
468       AbbrevToUse = ArrayAbbrev;
469       break;
470     }
471     case Type::VectorTyID: {
472       VectorType *VT = cast<VectorType>(T);
473       // VECTOR [numelts, eltty]
474       Code = bitc::TYPE_CODE_VECTOR;
475       TypeVals.push_back(VT->getNumElements());
476       TypeVals.push_back(VE.getTypeID(VT->getElementType()));
477       break;
478     }
479     }
480
481     // Emit the finished record.
482     Stream.EmitRecord(Code, TypeVals, AbbrevToUse);
483     TypeVals.clear();
484   }
485
486   Stream.ExitBlock();
487 }
488
489 static unsigned getEncodedLinkage(const GlobalValue &GV) {
490   switch (GV.getLinkage()) {
491   case GlobalValue::ExternalLinkage:
492     return 0;
493   case GlobalValue::WeakAnyLinkage:
494     return 16;
495   case GlobalValue::AppendingLinkage:
496     return 2;
497   case GlobalValue::InternalLinkage:
498     return 3;
499   case GlobalValue::LinkOnceAnyLinkage:
500     return 18;
501   case GlobalValue::ExternalWeakLinkage:
502     return 7;
503   case GlobalValue::CommonLinkage:
504     return 8;
505   case GlobalValue::PrivateLinkage:
506     return 9;
507   case GlobalValue::WeakODRLinkage:
508     return 17;
509   case GlobalValue::LinkOnceODRLinkage:
510     return 19;
511   case GlobalValue::AvailableExternallyLinkage:
512     return 12;
513   }
514   llvm_unreachable("Invalid linkage");
515 }
516
517 static unsigned getEncodedVisibility(const GlobalValue &GV) {
518   switch (GV.getVisibility()) {
519   case GlobalValue::DefaultVisibility:   return 0;
520   case GlobalValue::HiddenVisibility:    return 1;
521   case GlobalValue::ProtectedVisibility: return 2;
522   }
523   llvm_unreachable("Invalid visibility");
524 }
525
526 static unsigned getEncodedDLLStorageClass(const GlobalValue &GV) {
527   switch (GV.getDLLStorageClass()) {
528   case GlobalValue::DefaultStorageClass:   return 0;
529   case GlobalValue::DLLImportStorageClass: return 1;
530   case GlobalValue::DLLExportStorageClass: return 2;
531   }
532   llvm_unreachable("Invalid DLL storage class");
533 }
534
535 static unsigned getEncodedThreadLocalMode(const GlobalValue &GV) {
536   switch (GV.getThreadLocalMode()) {
537     case GlobalVariable::NotThreadLocal:         return 0;
538     case GlobalVariable::GeneralDynamicTLSModel: return 1;
539     case GlobalVariable::LocalDynamicTLSModel:   return 2;
540     case GlobalVariable::InitialExecTLSModel:    return 3;
541     case GlobalVariable::LocalExecTLSModel:      return 4;
542   }
543   llvm_unreachable("Invalid TLS model");
544 }
545
546 static unsigned getEncodedComdatSelectionKind(const Comdat &C) {
547   switch (C.getSelectionKind()) {
548   case Comdat::Any:
549     return bitc::COMDAT_SELECTION_KIND_ANY;
550   case Comdat::ExactMatch:
551     return bitc::COMDAT_SELECTION_KIND_EXACT_MATCH;
552   case Comdat::Largest:
553     return bitc::COMDAT_SELECTION_KIND_LARGEST;
554   case Comdat::NoDuplicates:
555     return bitc::COMDAT_SELECTION_KIND_NO_DUPLICATES;
556   case Comdat::SameSize:
557     return bitc::COMDAT_SELECTION_KIND_SAME_SIZE;
558   }
559   llvm_unreachable("Invalid selection kind");
560 }
561
562 static void writeComdats(const ValueEnumerator &VE, BitstreamWriter &Stream) {
563   SmallVector<uint16_t, 64> Vals;
564   for (const Comdat *C : VE.getComdats()) {
565     // COMDAT: [selection_kind, name]
566     Vals.push_back(getEncodedComdatSelectionKind(*C));
567     size_t Size = C->getName().size();
568     assert(isUInt<16>(Size));
569     Vals.push_back(Size);
570     for (char Chr : C->getName())
571       Vals.push_back((unsigned char)Chr);
572     Stream.EmitRecord(bitc::MODULE_CODE_COMDAT, Vals, /*AbbrevToUse=*/0);
573     Vals.clear();
574   }
575 }
576
577 // Emit top-level description of module, including target triple, inline asm,
578 // descriptors for global variables, and function prototype info.
579 static void WriteModuleInfo(const Module *M, const ValueEnumerator &VE,
580                             BitstreamWriter &Stream) {
581   // Emit various pieces of data attached to a module.
582   if (!M->getTargetTriple().empty())
583     WriteStringRecord(bitc::MODULE_CODE_TRIPLE, M->getTargetTriple(),
584                       0/*TODO*/, Stream);
585   const std::string &DL = M->getDataLayoutStr();
586   if (!DL.empty())
587     WriteStringRecord(bitc::MODULE_CODE_DATALAYOUT, DL, 0 /*TODO*/, Stream);
588   if (!M->getModuleInlineAsm().empty())
589     WriteStringRecord(bitc::MODULE_CODE_ASM, M->getModuleInlineAsm(),
590                       0/*TODO*/, Stream);
591
592   // Emit information about sections and GC, computing how many there are. Also
593   // compute the maximum alignment value.
594   std::map<std::string, unsigned> SectionMap;
595   std::map<std::string, unsigned> GCMap;
596   unsigned MaxAlignment = 0;
597   unsigned MaxGlobalType = 0;
598   for (const GlobalValue &GV : M->globals()) {
599     MaxAlignment = std::max(MaxAlignment, GV.getAlignment());
600     MaxGlobalType = std::max(MaxGlobalType, VE.getTypeID(GV.getValueType()));
601     if (GV.hasSection()) {
602       // Give section names unique ID's.
603       unsigned &Entry = SectionMap[GV.getSection()];
604       if (!Entry) {
605         WriteStringRecord(bitc::MODULE_CODE_SECTIONNAME, GV.getSection(),
606                           0/*TODO*/, Stream);
607         Entry = SectionMap.size();
608       }
609     }
610   }
611   for (const Function &F : *M) {
612     MaxAlignment = std::max(MaxAlignment, F.getAlignment());
613     if (F.hasSection()) {
614       // Give section names unique ID's.
615       unsigned &Entry = SectionMap[F.getSection()];
616       if (!Entry) {
617         WriteStringRecord(bitc::MODULE_CODE_SECTIONNAME, F.getSection(),
618                           0/*TODO*/, Stream);
619         Entry = SectionMap.size();
620       }
621     }
622     if (F.hasGC()) {
623       // Same for GC names.
624       unsigned &Entry = GCMap[F.getGC()];
625       if (!Entry) {
626         WriteStringRecord(bitc::MODULE_CODE_GCNAME, F.getGC(),
627                           0/*TODO*/, Stream);
628         Entry = GCMap.size();
629       }
630     }
631   }
632
633   // Emit abbrev for globals, now that we know # sections and max alignment.
634   unsigned SimpleGVarAbbrev = 0;
635   if (!M->global_empty()) {
636     // Add an abbrev for common globals with no visibility or thread localness.
637     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
638     Abbv->Add(BitCodeAbbrevOp(bitc::MODULE_CODE_GLOBALVAR));
639     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
640                               Log2_32_Ceil(MaxGlobalType+1)));
641     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));   // AddrSpace << 2
642                                                            //| explicitType << 1
643                                                            //| constant
644     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));   // Initializer.
645     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 5)); // Linkage.
646     if (MaxAlignment == 0)                                 // Alignment.
647       Abbv->Add(BitCodeAbbrevOp(0));
648     else {
649       unsigned MaxEncAlignment = Log2_32(MaxAlignment)+1;
650       Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
651                                Log2_32_Ceil(MaxEncAlignment+1)));
652     }
653     if (SectionMap.empty())                                    // Section.
654       Abbv->Add(BitCodeAbbrevOp(0));
655     else
656       Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
657                                Log2_32_Ceil(SectionMap.size()+1)));
658     // Don't bother emitting vis + thread local.
659     SimpleGVarAbbrev = Stream.EmitAbbrev(Abbv);
660   }
661
662   // Emit the global variable information.
663   SmallVector<unsigned, 64> Vals;
664   for (const GlobalVariable &GV : M->globals()) {
665     unsigned AbbrevToUse = 0;
666
667     // GLOBALVAR: [type, isconst, initid,
668     //             linkage, alignment, section, visibility, threadlocal,
669     //             unnamed_addr, externally_initialized, dllstorageclass,
670     //             comdat]
671     Vals.push_back(VE.getTypeID(GV.getValueType()));
672     Vals.push_back(GV.getType()->getAddressSpace() << 2 | 2 | GV.isConstant());
673     Vals.push_back(GV.isDeclaration() ? 0 :
674                    (VE.getValueID(GV.getInitializer()) + 1));
675     Vals.push_back(getEncodedLinkage(GV));
676     Vals.push_back(Log2_32(GV.getAlignment())+1);
677     Vals.push_back(GV.hasSection() ? SectionMap[GV.getSection()] : 0);
678     if (GV.isThreadLocal() ||
679         GV.getVisibility() != GlobalValue::DefaultVisibility ||
680         GV.hasUnnamedAddr() || GV.isExternallyInitialized() ||
681         GV.getDLLStorageClass() != GlobalValue::DefaultStorageClass ||
682         GV.hasComdat()) {
683       Vals.push_back(getEncodedVisibility(GV));
684       Vals.push_back(getEncodedThreadLocalMode(GV));
685       Vals.push_back(GV.hasUnnamedAddr());
686       Vals.push_back(GV.isExternallyInitialized());
687       Vals.push_back(getEncodedDLLStorageClass(GV));
688       Vals.push_back(GV.hasComdat() ? VE.getComdatID(GV.getComdat()) : 0);
689     } else {
690       AbbrevToUse = SimpleGVarAbbrev;
691     }
692
693     Stream.EmitRecord(bitc::MODULE_CODE_GLOBALVAR, Vals, AbbrevToUse);
694     Vals.clear();
695   }
696
697   // Emit the function proto information.
698   for (const Function &F : *M) {
699     // FUNCTION:  [type, callingconv, isproto, linkage, paramattrs, alignment,
700     //             section, visibility, gc, unnamed_addr, prologuedata,
701     //             dllstorageclass, comdat, prefixdata, personalityfn]
702     Vals.push_back(VE.getTypeID(F.getFunctionType()));
703     Vals.push_back(F.getCallingConv());
704     Vals.push_back(F.isDeclaration());
705     Vals.push_back(getEncodedLinkage(F));
706     Vals.push_back(VE.getAttributeID(F.getAttributes()));
707     Vals.push_back(Log2_32(F.getAlignment())+1);
708     Vals.push_back(F.hasSection() ? SectionMap[F.getSection()] : 0);
709     Vals.push_back(getEncodedVisibility(F));
710     Vals.push_back(F.hasGC() ? GCMap[F.getGC()] : 0);
711     Vals.push_back(F.hasUnnamedAddr());
712     Vals.push_back(F.hasPrologueData() ? (VE.getValueID(F.getPrologueData()) + 1)
713                                        : 0);
714     Vals.push_back(getEncodedDLLStorageClass(F));
715     Vals.push_back(F.hasComdat() ? VE.getComdatID(F.getComdat()) : 0);
716     Vals.push_back(F.hasPrefixData() ? (VE.getValueID(F.getPrefixData()) + 1)
717                                      : 0);
718     Vals.push_back(
719         F.hasPersonalityFn() ? (VE.getValueID(F.getPersonalityFn()) + 1) : 0);
720
721     unsigned AbbrevToUse = 0;
722     Stream.EmitRecord(bitc::MODULE_CODE_FUNCTION, Vals, AbbrevToUse);
723     Vals.clear();
724   }
725
726   // Emit the alias information.
727   for (const GlobalAlias &A : M->aliases()) {
728     // ALIAS: [alias type, aliasee val#, linkage, visibility]
729     Vals.push_back(VE.getTypeID(A.getType()));
730     Vals.push_back(VE.getValueID(A.getAliasee()));
731     Vals.push_back(getEncodedLinkage(A));
732     Vals.push_back(getEncodedVisibility(A));
733     Vals.push_back(getEncodedDLLStorageClass(A));
734     Vals.push_back(getEncodedThreadLocalMode(A));
735     Vals.push_back(A.hasUnnamedAddr());
736     unsigned AbbrevToUse = 0;
737     Stream.EmitRecord(bitc::MODULE_CODE_ALIAS, Vals, AbbrevToUse);
738     Vals.clear();
739   }
740 }
741
742 static uint64_t GetOptimizationFlags(const Value *V) {
743   uint64_t Flags = 0;
744
745   if (const auto *OBO = dyn_cast<OverflowingBinaryOperator>(V)) {
746     if (OBO->hasNoSignedWrap())
747       Flags |= 1 << bitc::OBO_NO_SIGNED_WRAP;
748     if (OBO->hasNoUnsignedWrap())
749       Flags |= 1 << bitc::OBO_NO_UNSIGNED_WRAP;
750   } else if (const auto *PEO = dyn_cast<PossiblyExactOperator>(V)) {
751     if (PEO->isExact())
752       Flags |= 1 << bitc::PEO_EXACT;
753   } else if (const auto *FPMO = dyn_cast<FPMathOperator>(V)) {
754     if (FPMO->hasUnsafeAlgebra())
755       Flags |= FastMathFlags::UnsafeAlgebra;
756     if (FPMO->hasNoNaNs())
757       Flags |= FastMathFlags::NoNaNs;
758     if (FPMO->hasNoInfs())
759       Flags |= FastMathFlags::NoInfs;
760     if (FPMO->hasNoSignedZeros())
761       Flags |= FastMathFlags::NoSignedZeros;
762     if (FPMO->hasAllowReciprocal())
763       Flags |= FastMathFlags::AllowReciprocal;
764   }
765
766   return Flags;
767 }
768
769 static void WriteValueAsMetadata(const ValueAsMetadata *MD,
770                                  const ValueEnumerator &VE,
771                                  BitstreamWriter &Stream,
772                                  SmallVectorImpl<uint64_t> &Record) {
773   // Mimic an MDNode with a value as one operand.
774   Value *V = MD->getValue();
775   Record.push_back(VE.getTypeID(V->getType()));
776   Record.push_back(VE.getValueID(V));
777   Stream.EmitRecord(bitc::METADATA_VALUE, Record, 0);
778   Record.clear();
779 }
780
781 static void WriteMDTuple(const MDTuple *N, const ValueEnumerator &VE,
782                          BitstreamWriter &Stream,
783                          SmallVectorImpl<uint64_t> &Record, unsigned Abbrev) {
784   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
785     Metadata *MD = N->getOperand(i);
786     assert(!(MD && isa<LocalAsMetadata>(MD)) &&
787            "Unexpected function-local metadata");
788     Record.push_back(VE.getMetadataOrNullID(MD));
789   }
790   Stream.EmitRecord(N->isDistinct() ? bitc::METADATA_DISTINCT_NODE
791                                     : bitc::METADATA_NODE,
792                     Record, Abbrev);
793   Record.clear();
794 }
795
796 static void WriteDILocation(const DILocation *N, const ValueEnumerator &VE,
797                             BitstreamWriter &Stream,
798                             SmallVectorImpl<uint64_t> &Record,
799                             unsigned Abbrev) {
800   Record.push_back(N->isDistinct());
801   Record.push_back(N->getLine());
802   Record.push_back(N->getColumn());
803   Record.push_back(VE.getMetadataID(N->getScope()));
804   Record.push_back(VE.getMetadataOrNullID(N->getInlinedAt()));
805
806   Stream.EmitRecord(bitc::METADATA_LOCATION, Record, Abbrev);
807   Record.clear();
808 }
809
810 static void WriteGenericDINode(const GenericDINode *N,
811                                const ValueEnumerator &VE,
812                                BitstreamWriter &Stream,
813                                SmallVectorImpl<uint64_t> &Record,
814                                unsigned Abbrev) {
815   Record.push_back(N->isDistinct());
816   Record.push_back(N->getTag());
817   Record.push_back(0); // Per-tag version field; unused for now.
818
819   for (auto &I : N->operands())
820     Record.push_back(VE.getMetadataOrNullID(I));
821
822   Stream.EmitRecord(bitc::METADATA_GENERIC_DEBUG, Record, Abbrev);
823   Record.clear();
824 }
825
826 static uint64_t rotateSign(int64_t I) {
827   uint64_t U = I;
828   return I < 0 ? ~(U << 1) : U << 1;
829 }
830
831 static void WriteDISubrange(const DISubrange *N, const ValueEnumerator &,
832                             BitstreamWriter &Stream,
833                             SmallVectorImpl<uint64_t> &Record,
834                             unsigned Abbrev) {
835   Record.push_back(N->isDistinct());
836   Record.push_back(N->getCount());
837   Record.push_back(rotateSign(N->getLowerBound()));
838
839   Stream.EmitRecord(bitc::METADATA_SUBRANGE, Record, Abbrev);
840   Record.clear();
841 }
842
843 static void WriteDIEnumerator(const DIEnumerator *N, const ValueEnumerator &VE,
844                               BitstreamWriter &Stream,
845                               SmallVectorImpl<uint64_t> &Record,
846                               unsigned Abbrev) {
847   Record.push_back(N->isDistinct());
848   Record.push_back(rotateSign(N->getValue()));
849   Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
850
851   Stream.EmitRecord(bitc::METADATA_ENUMERATOR, Record, Abbrev);
852   Record.clear();
853 }
854
855 static void WriteDIBasicType(const DIBasicType *N, const ValueEnumerator &VE,
856                              BitstreamWriter &Stream,
857                              SmallVectorImpl<uint64_t> &Record,
858                              unsigned Abbrev) {
859   Record.push_back(N->isDistinct());
860   Record.push_back(N->getTag());
861   Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
862   Record.push_back(N->getSizeInBits());
863   Record.push_back(N->getAlignInBits());
864   Record.push_back(N->getEncoding());
865
866   Stream.EmitRecord(bitc::METADATA_BASIC_TYPE, Record, Abbrev);
867   Record.clear();
868 }
869
870 static void WriteDIDerivedType(const DIDerivedType *N,
871                                const ValueEnumerator &VE,
872                                BitstreamWriter &Stream,
873                                SmallVectorImpl<uint64_t> &Record,
874                                unsigned Abbrev) {
875   Record.push_back(N->isDistinct());
876   Record.push_back(N->getTag());
877   Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
878   Record.push_back(VE.getMetadataOrNullID(N->getFile()));
879   Record.push_back(N->getLine());
880   Record.push_back(VE.getMetadataOrNullID(N->getScope()));
881   Record.push_back(VE.getMetadataOrNullID(N->getBaseType()));
882   Record.push_back(N->getSizeInBits());
883   Record.push_back(N->getAlignInBits());
884   Record.push_back(N->getOffsetInBits());
885   Record.push_back(N->getFlags());
886   Record.push_back(VE.getMetadataOrNullID(N->getExtraData()));
887
888   Stream.EmitRecord(bitc::METADATA_DERIVED_TYPE, Record, Abbrev);
889   Record.clear();
890 }
891
892 static void WriteDICompositeType(const DICompositeType *N,
893                                  const ValueEnumerator &VE,
894                                  BitstreamWriter &Stream,
895                                  SmallVectorImpl<uint64_t> &Record,
896                                  unsigned Abbrev) {
897   Record.push_back(N->isDistinct());
898   Record.push_back(N->getTag());
899   Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
900   Record.push_back(VE.getMetadataOrNullID(N->getFile()));
901   Record.push_back(N->getLine());
902   Record.push_back(VE.getMetadataOrNullID(N->getScope()));
903   Record.push_back(VE.getMetadataOrNullID(N->getBaseType()));
904   Record.push_back(N->getSizeInBits());
905   Record.push_back(N->getAlignInBits());
906   Record.push_back(N->getOffsetInBits());
907   Record.push_back(N->getFlags());
908   Record.push_back(VE.getMetadataOrNullID(N->getElements().get()));
909   Record.push_back(N->getRuntimeLang());
910   Record.push_back(VE.getMetadataOrNullID(N->getVTableHolder()));
911   Record.push_back(VE.getMetadataOrNullID(N->getTemplateParams().get()));
912   Record.push_back(VE.getMetadataOrNullID(N->getRawIdentifier()));
913
914   Stream.EmitRecord(bitc::METADATA_COMPOSITE_TYPE, Record, Abbrev);
915   Record.clear();
916 }
917
918 static void WriteDISubroutineType(const DISubroutineType *N,
919                                   const ValueEnumerator &VE,
920                                   BitstreamWriter &Stream,
921                                   SmallVectorImpl<uint64_t> &Record,
922                                   unsigned Abbrev) {
923   Record.push_back(N->isDistinct());
924   Record.push_back(N->getFlags());
925   Record.push_back(VE.getMetadataOrNullID(N->getTypeArray().get()));
926
927   Stream.EmitRecord(bitc::METADATA_SUBROUTINE_TYPE, Record, Abbrev);
928   Record.clear();
929 }
930
931 static void WriteDIFile(const DIFile *N, const ValueEnumerator &VE,
932                         BitstreamWriter &Stream,
933                         SmallVectorImpl<uint64_t> &Record, unsigned Abbrev) {
934   Record.push_back(N->isDistinct());
935   Record.push_back(VE.getMetadataOrNullID(N->getRawFilename()));
936   Record.push_back(VE.getMetadataOrNullID(N->getRawDirectory()));
937
938   Stream.EmitRecord(bitc::METADATA_FILE, Record, Abbrev);
939   Record.clear();
940 }
941
942 static void WriteDICompileUnit(const DICompileUnit *N,
943                                const ValueEnumerator &VE,
944                                BitstreamWriter &Stream,
945                                SmallVectorImpl<uint64_t> &Record,
946                                unsigned Abbrev) {
947   assert(N->isDistinct() && "Expected distinct compile units");
948   Record.push_back(/* IsDistinct */ true);
949   Record.push_back(N->getSourceLanguage());
950   Record.push_back(VE.getMetadataOrNullID(N->getFile()));
951   Record.push_back(VE.getMetadataOrNullID(N->getRawProducer()));
952   Record.push_back(N->isOptimized());
953   Record.push_back(VE.getMetadataOrNullID(N->getRawFlags()));
954   Record.push_back(N->getRuntimeVersion());
955   Record.push_back(VE.getMetadataOrNullID(N->getRawSplitDebugFilename()));
956   Record.push_back(N->getEmissionKind());
957   Record.push_back(VE.getMetadataOrNullID(N->getEnumTypes().get()));
958   Record.push_back(VE.getMetadataOrNullID(N->getRetainedTypes().get()));
959   Record.push_back(VE.getMetadataOrNullID(N->getSubprograms().get()));
960   Record.push_back(VE.getMetadataOrNullID(N->getGlobalVariables().get()));
961   Record.push_back(VE.getMetadataOrNullID(N->getImportedEntities().get()));
962   Record.push_back(N->getDWOId());
963
964   Stream.EmitRecord(bitc::METADATA_COMPILE_UNIT, Record, Abbrev);
965   Record.clear();
966 }
967
968 static void WriteDISubprogram(const DISubprogram *N, const ValueEnumerator &VE,
969                               BitstreamWriter &Stream,
970                               SmallVectorImpl<uint64_t> &Record,
971                               unsigned Abbrev) {
972   Record.push_back(N->isDistinct());
973   Record.push_back(VE.getMetadataOrNullID(N->getScope()));
974   Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
975   Record.push_back(VE.getMetadataOrNullID(N->getRawLinkageName()));
976   Record.push_back(VE.getMetadataOrNullID(N->getFile()));
977   Record.push_back(N->getLine());
978   Record.push_back(VE.getMetadataOrNullID(N->getType()));
979   Record.push_back(N->isLocalToUnit());
980   Record.push_back(N->isDefinition());
981   Record.push_back(N->getScopeLine());
982   Record.push_back(VE.getMetadataOrNullID(N->getContainingType()));
983   Record.push_back(N->getVirtuality());
984   Record.push_back(N->getVirtualIndex());
985   Record.push_back(N->getFlags());
986   Record.push_back(N->isOptimized());
987   Record.push_back(VE.getMetadataOrNullID(N->getRawFunction()));
988   Record.push_back(VE.getMetadataOrNullID(N->getTemplateParams().get()));
989   Record.push_back(VE.getMetadataOrNullID(N->getDeclaration()));
990   Record.push_back(VE.getMetadataOrNullID(N->getVariables().get()));
991
992   Stream.EmitRecord(bitc::METADATA_SUBPROGRAM, Record, Abbrev);
993   Record.clear();
994 }
995
996 static void WriteDILexicalBlock(const DILexicalBlock *N,
997                                 const ValueEnumerator &VE,
998                                 BitstreamWriter &Stream,
999                                 SmallVectorImpl<uint64_t> &Record,
1000                                 unsigned Abbrev) {
1001   Record.push_back(N->isDistinct());
1002   Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1003   Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1004   Record.push_back(N->getLine());
1005   Record.push_back(N->getColumn());
1006
1007   Stream.EmitRecord(bitc::METADATA_LEXICAL_BLOCK, Record, Abbrev);
1008   Record.clear();
1009 }
1010
1011 static void WriteDILexicalBlockFile(const DILexicalBlockFile *N,
1012                                     const ValueEnumerator &VE,
1013                                     BitstreamWriter &Stream,
1014                                     SmallVectorImpl<uint64_t> &Record,
1015                                     unsigned Abbrev) {
1016   Record.push_back(N->isDistinct());
1017   Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1018   Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1019   Record.push_back(N->getDiscriminator());
1020
1021   Stream.EmitRecord(bitc::METADATA_LEXICAL_BLOCK_FILE, Record, Abbrev);
1022   Record.clear();
1023 }
1024
1025 static void WriteDINamespace(const DINamespace *N, const ValueEnumerator &VE,
1026                              BitstreamWriter &Stream,
1027                              SmallVectorImpl<uint64_t> &Record,
1028                              unsigned Abbrev) {
1029   Record.push_back(N->isDistinct());
1030   Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1031   Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1032   Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1033   Record.push_back(N->getLine());
1034
1035   Stream.EmitRecord(bitc::METADATA_NAMESPACE, Record, Abbrev);
1036   Record.clear();
1037 }
1038
1039 static void WriteDIModule(const DIModule *N, const ValueEnumerator &VE,
1040                           BitstreamWriter &Stream,
1041                           SmallVectorImpl<uint64_t> &Record, unsigned Abbrev) {
1042   Record.push_back(N->isDistinct());
1043   for (auto &I : N->operands())
1044     Record.push_back(VE.getMetadataOrNullID(I));
1045
1046   Stream.EmitRecord(bitc::METADATA_MODULE, Record, Abbrev);
1047   Record.clear();
1048 }
1049
1050 static void WriteDITemplateTypeParameter(const DITemplateTypeParameter *N,
1051                                          const ValueEnumerator &VE,
1052                                          BitstreamWriter &Stream,
1053                                          SmallVectorImpl<uint64_t> &Record,
1054                                          unsigned Abbrev) {
1055   Record.push_back(N->isDistinct());
1056   Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1057   Record.push_back(VE.getMetadataOrNullID(N->getType()));
1058
1059   Stream.EmitRecord(bitc::METADATA_TEMPLATE_TYPE, Record, Abbrev);
1060   Record.clear();
1061 }
1062
1063 static void WriteDITemplateValueParameter(const DITemplateValueParameter *N,
1064                                           const ValueEnumerator &VE,
1065                                           BitstreamWriter &Stream,
1066                                           SmallVectorImpl<uint64_t> &Record,
1067                                           unsigned Abbrev) {
1068   Record.push_back(N->isDistinct());
1069   Record.push_back(N->getTag());
1070   Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1071   Record.push_back(VE.getMetadataOrNullID(N->getType()));
1072   Record.push_back(VE.getMetadataOrNullID(N->getValue()));
1073
1074   Stream.EmitRecord(bitc::METADATA_TEMPLATE_VALUE, Record, Abbrev);
1075   Record.clear();
1076 }
1077
1078 static void WriteDIGlobalVariable(const DIGlobalVariable *N,
1079                                   const ValueEnumerator &VE,
1080                                   BitstreamWriter &Stream,
1081                                   SmallVectorImpl<uint64_t> &Record,
1082                                   unsigned Abbrev) {
1083   Record.push_back(N->isDistinct());
1084   Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1085   Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1086   Record.push_back(VE.getMetadataOrNullID(N->getRawLinkageName()));
1087   Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1088   Record.push_back(N->getLine());
1089   Record.push_back(VE.getMetadataOrNullID(N->getType()));
1090   Record.push_back(N->isLocalToUnit());
1091   Record.push_back(N->isDefinition());
1092   Record.push_back(VE.getMetadataOrNullID(N->getRawVariable()));
1093   Record.push_back(VE.getMetadataOrNullID(N->getStaticDataMemberDeclaration()));
1094
1095   Stream.EmitRecord(bitc::METADATA_GLOBAL_VAR, Record, Abbrev);
1096   Record.clear();
1097 }
1098
1099 static void WriteDILocalVariable(const DILocalVariable *N,
1100                                  const ValueEnumerator &VE,
1101                                  BitstreamWriter &Stream,
1102                                  SmallVectorImpl<uint64_t> &Record,
1103                                  unsigned Abbrev) {
1104   Record.push_back(N->isDistinct());
1105   Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1106   Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1107   Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1108   Record.push_back(N->getLine());
1109   Record.push_back(VE.getMetadataOrNullID(N->getType()));
1110   Record.push_back(N->getArg());
1111   Record.push_back(N->getFlags());
1112
1113   Stream.EmitRecord(bitc::METADATA_LOCAL_VAR, Record, Abbrev);
1114   Record.clear();
1115 }
1116
1117 static void WriteDIExpression(const DIExpression *N, const ValueEnumerator &,
1118                               BitstreamWriter &Stream,
1119                               SmallVectorImpl<uint64_t> &Record,
1120                               unsigned Abbrev) {
1121   Record.reserve(N->getElements().size() + 1);
1122
1123   Record.push_back(N->isDistinct());
1124   Record.append(N->elements_begin(), N->elements_end());
1125
1126   Stream.EmitRecord(bitc::METADATA_EXPRESSION, Record, Abbrev);
1127   Record.clear();
1128 }
1129
1130 static void WriteDIObjCProperty(const DIObjCProperty *N,
1131                                 const ValueEnumerator &VE,
1132                                 BitstreamWriter &Stream,
1133                                 SmallVectorImpl<uint64_t> &Record,
1134                                 unsigned Abbrev) {
1135   Record.push_back(N->isDistinct());
1136   Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1137   Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1138   Record.push_back(N->getLine());
1139   Record.push_back(VE.getMetadataOrNullID(N->getRawSetterName()));
1140   Record.push_back(VE.getMetadataOrNullID(N->getRawGetterName()));
1141   Record.push_back(N->getAttributes());
1142   Record.push_back(VE.getMetadataOrNullID(N->getType()));
1143
1144   Stream.EmitRecord(bitc::METADATA_OBJC_PROPERTY, Record, Abbrev);
1145   Record.clear();
1146 }
1147
1148 static void WriteDIImportedEntity(const DIImportedEntity *N,
1149                                   const ValueEnumerator &VE,
1150                                   BitstreamWriter &Stream,
1151                                   SmallVectorImpl<uint64_t> &Record,
1152                                   unsigned Abbrev) {
1153   Record.push_back(N->isDistinct());
1154   Record.push_back(N->getTag());
1155   Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1156   Record.push_back(VE.getMetadataOrNullID(N->getEntity()));
1157   Record.push_back(N->getLine());
1158   Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1159
1160   Stream.EmitRecord(bitc::METADATA_IMPORTED_ENTITY, Record, Abbrev);
1161   Record.clear();
1162 }
1163
1164 static void WriteModuleMetadata(const Module *M,
1165                                 const ValueEnumerator &VE,
1166                                 BitstreamWriter &Stream) {
1167   const auto &MDs = VE.getMDs();
1168   if (MDs.empty() && M->named_metadata_empty())
1169     return;
1170
1171   Stream.EnterSubblock(bitc::METADATA_BLOCK_ID, 3);
1172
1173   unsigned MDSAbbrev = 0;
1174   if (VE.hasMDString()) {
1175     // Abbrev for METADATA_STRING.
1176     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1177     Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_STRING));
1178     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1179     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
1180     MDSAbbrev = Stream.EmitAbbrev(Abbv);
1181   }
1182
1183   // Initialize MDNode abbreviations.
1184 #define HANDLE_MDNODE_LEAF(CLASS) unsigned CLASS##Abbrev = 0;
1185 #include "llvm/IR/Metadata.def"
1186
1187   if (VE.hasDILocation()) {
1188     // Abbrev for METADATA_LOCATION.
1189     //
1190     // Assume the column is usually under 128, and always output the inlined-at
1191     // location (it's never more expensive than building an array size 1).
1192     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1193     Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_LOCATION));
1194     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));
1195     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
1196     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
1197     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
1198     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
1199     DILocationAbbrev = Stream.EmitAbbrev(Abbv);
1200   }
1201
1202   if (VE.hasGenericDINode()) {
1203     // Abbrev for METADATA_GENERIC_DEBUG.
1204     //
1205     // Assume the column is usually under 128, and always output the inlined-at
1206     // location (it's never more expensive than building an array size 1).
1207     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1208     Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_GENERIC_DEBUG));
1209     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));
1210     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
1211     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));
1212     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
1213     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1214     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
1215     GenericDINodeAbbrev = Stream.EmitAbbrev(Abbv);
1216   }
1217
1218   unsigned NameAbbrev = 0;
1219   if (!M->named_metadata_empty()) {
1220     // Abbrev for METADATA_NAME.
1221     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1222     Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_NAME));
1223     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1224     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
1225     NameAbbrev = Stream.EmitAbbrev(Abbv);
1226   }
1227
1228   SmallVector<uint64_t, 64> Record;
1229   for (const Metadata *MD : MDs) {
1230     if (const MDNode *N = dyn_cast<MDNode>(MD)) {
1231       assert(N->isResolved() && "Expected forward references to be resolved");
1232
1233       switch (N->getMetadataID()) {
1234       default:
1235         llvm_unreachable("Invalid MDNode subclass");
1236 #define HANDLE_MDNODE_LEAF(CLASS)                                              \
1237   case Metadata::CLASS##Kind:                                                  \
1238     Write##CLASS(cast<CLASS>(N), VE, Stream, Record, CLASS##Abbrev);           \
1239     continue;
1240 #include "llvm/IR/Metadata.def"
1241       }
1242     }
1243     if (const auto *MDC = dyn_cast<ConstantAsMetadata>(MD)) {
1244       WriteValueAsMetadata(MDC, VE, Stream, Record);
1245       continue;
1246     }
1247     const MDString *MDS = cast<MDString>(MD);
1248     // Code: [strchar x N]
1249     Record.append(MDS->bytes_begin(), MDS->bytes_end());
1250
1251     // Emit the finished record.
1252     Stream.EmitRecord(bitc::METADATA_STRING, Record, MDSAbbrev);
1253     Record.clear();
1254   }
1255
1256   // Write named metadata.
1257   for (const NamedMDNode &NMD : M->named_metadata()) {
1258     // Write name.
1259     StringRef Str = NMD.getName();
1260     Record.append(Str.bytes_begin(), Str.bytes_end());
1261     Stream.EmitRecord(bitc::METADATA_NAME, Record, NameAbbrev);
1262     Record.clear();
1263
1264     // Write named metadata operands.
1265     for (const MDNode *N : NMD.operands())
1266       Record.push_back(VE.getMetadataID(N));
1267     Stream.EmitRecord(bitc::METADATA_NAMED_NODE, Record, 0);
1268     Record.clear();
1269   }
1270
1271   Stream.ExitBlock();
1272 }
1273
1274 static void WriteFunctionLocalMetadata(const Function &F,
1275                                        const ValueEnumerator &VE,
1276                                        BitstreamWriter &Stream) {
1277   bool StartedMetadataBlock = false;
1278   SmallVector<uint64_t, 64> Record;
1279   const SmallVectorImpl<const LocalAsMetadata *> &MDs =
1280       VE.getFunctionLocalMDs();
1281   for (unsigned i = 0, e = MDs.size(); i != e; ++i) {
1282     assert(MDs[i] && "Expected valid function-local metadata");
1283     if (!StartedMetadataBlock) {
1284       Stream.EnterSubblock(bitc::METADATA_BLOCK_ID, 3);
1285       StartedMetadataBlock = true;
1286     }
1287     WriteValueAsMetadata(MDs[i], VE, Stream, Record);
1288   }
1289
1290   if (StartedMetadataBlock)
1291     Stream.ExitBlock();
1292 }
1293
1294 static void WriteMetadataAttachment(const Function &F,
1295                                     const ValueEnumerator &VE,
1296                                     BitstreamWriter &Stream) {
1297   Stream.EnterSubblock(bitc::METADATA_ATTACHMENT_ID, 3);
1298
1299   SmallVector<uint64_t, 64> Record;
1300
1301   // Write metadata attachments
1302   // METADATA_ATTACHMENT - [m x [value, [n x [id, mdnode]]]
1303   SmallVector<std::pair<unsigned, MDNode *>, 4> MDs;
1304   F.getAllMetadata(MDs);
1305   if (!MDs.empty()) {
1306     for (const auto &I : MDs) {
1307       Record.push_back(I.first);
1308       Record.push_back(VE.getMetadataID(I.second));
1309     }
1310     Stream.EmitRecord(bitc::METADATA_ATTACHMENT, Record, 0);
1311     Record.clear();
1312   }
1313
1314   for (Function::const_iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
1315     for (BasicBlock::const_iterator I = BB->begin(), E = BB->end();
1316          I != E; ++I) {
1317       MDs.clear();
1318       I->getAllMetadataOtherThanDebugLoc(MDs);
1319
1320       // If no metadata, ignore instruction.
1321       if (MDs.empty()) continue;
1322
1323       Record.push_back(VE.getInstructionID(I));
1324
1325       for (unsigned i = 0, e = MDs.size(); i != e; ++i) {
1326         Record.push_back(MDs[i].first);
1327         Record.push_back(VE.getMetadataID(MDs[i].second));
1328       }
1329       Stream.EmitRecord(bitc::METADATA_ATTACHMENT, Record, 0);
1330       Record.clear();
1331     }
1332
1333   Stream.ExitBlock();
1334 }
1335
1336 static void WriteModuleMetadataStore(const Module *M, BitstreamWriter &Stream) {
1337   SmallVector<uint64_t, 64> Record;
1338
1339   // Write metadata kinds
1340   // METADATA_KIND - [n x [id, name]]
1341   SmallVector<StringRef, 8> Names;
1342   M->getMDKindNames(Names);
1343
1344   if (Names.empty()) return;
1345
1346   Stream.EnterSubblock(bitc::METADATA_BLOCK_ID, 3);
1347
1348   for (unsigned MDKindID = 0, e = Names.size(); MDKindID != e; ++MDKindID) {
1349     Record.push_back(MDKindID);
1350     StringRef KName = Names[MDKindID];
1351     Record.append(KName.begin(), KName.end());
1352
1353     Stream.EmitRecord(bitc::METADATA_KIND, Record, 0);
1354     Record.clear();
1355   }
1356
1357   Stream.ExitBlock();
1358 }
1359
1360 static void emitSignedInt64(SmallVectorImpl<uint64_t> &Vals, uint64_t V) {
1361   if ((int64_t)V >= 0)
1362     Vals.push_back(V << 1);
1363   else
1364     Vals.push_back((-V << 1) | 1);
1365 }
1366
1367 static void WriteConstants(unsigned FirstVal, unsigned LastVal,
1368                            const ValueEnumerator &VE,
1369                            BitstreamWriter &Stream, bool isGlobal) {
1370   if (FirstVal == LastVal) return;
1371
1372   Stream.EnterSubblock(bitc::CONSTANTS_BLOCK_ID, 4);
1373
1374   unsigned AggregateAbbrev = 0;
1375   unsigned String8Abbrev = 0;
1376   unsigned CString7Abbrev = 0;
1377   unsigned CString6Abbrev = 0;
1378   // If this is a constant pool for the module, emit module-specific abbrevs.
1379   if (isGlobal) {
1380     // Abbrev for CST_CODE_AGGREGATE.
1381     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1382     Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_AGGREGATE));
1383     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1384     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, Log2_32_Ceil(LastVal+1)));
1385     AggregateAbbrev = Stream.EmitAbbrev(Abbv);
1386
1387     // Abbrev for CST_CODE_STRING.
1388     Abbv = new BitCodeAbbrev();
1389     Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_STRING));
1390     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1391     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
1392     String8Abbrev = Stream.EmitAbbrev(Abbv);
1393     // Abbrev for CST_CODE_CSTRING.
1394     Abbv = new BitCodeAbbrev();
1395     Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_CSTRING));
1396     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1397     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7));
1398     CString7Abbrev = Stream.EmitAbbrev(Abbv);
1399     // Abbrev for CST_CODE_CSTRING.
1400     Abbv = new BitCodeAbbrev();
1401     Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_CSTRING));
1402     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1403     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
1404     CString6Abbrev = Stream.EmitAbbrev(Abbv);
1405   }
1406
1407   SmallVector<uint64_t, 64> Record;
1408
1409   const ValueEnumerator::ValueList &Vals = VE.getValues();
1410   Type *LastTy = nullptr;
1411   for (unsigned i = FirstVal; i != LastVal; ++i) {
1412     const Value *V = Vals[i].first;
1413     // If we need to switch types, do so now.
1414     if (V->getType() != LastTy) {
1415       LastTy = V->getType();
1416       Record.push_back(VE.getTypeID(LastTy));
1417       Stream.EmitRecord(bitc::CST_CODE_SETTYPE, Record,
1418                         CONSTANTS_SETTYPE_ABBREV);
1419       Record.clear();
1420     }
1421
1422     if (const InlineAsm *IA = dyn_cast<InlineAsm>(V)) {
1423       Record.push_back(unsigned(IA->hasSideEffects()) |
1424                        unsigned(IA->isAlignStack()) << 1 |
1425                        unsigned(IA->getDialect()&1) << 2);
1426
1427       // Add the asm string.
1428       const std::string &AsmStr = IA->getAsmString();
1429       Record.push_back(AsmStr.size());
1430       Record.append(AsmStr.begin(), AsmStr.end());
1431
1432       // Add the constraint string.
1433       const std::string &ConstraintStr = IA->getConstraintString();
1434       Record.push_back(ConstraintStr.size());
1435       Record.append(ConstraintStr.begin(), ConstraintStr.end());
1436       Stream.EmitRecord(bitc::CST_CODE_INLINEASM, Record);
1437       Record.clear();
1438       continue;
1439     }
1440     const Constant *C = cast<Constant>(V);
1441     unsigned Code = -1U;
1442     unsigned AbbrevToUse = 0;
1443     if (C->isNullValue()) {
1444       Code = bitc::CST_CODE_NULL;
1445     } else if (isa<UndefValue>(C)) {
1446       Code = bitc::CST_CODE_UNDEF;
1447     } else if (const ConstantInt *IV = dyn_cast<ConstantInt>(C)) {
1448       if (IV->getBitWidth() <= 64) {
1449         uint64_t V = IV->getSExtValue();
1450         emitSignedInt64(Record, V);
1451         Code = bitc::CST_CODE_INTEGER;
1452         AbbrevToUse = CONSTANTS_INTEGER_ABBREV;
1453       } else {                             // Wide integers, > 64 bits in size.
1454         // We have an arbitrary precision integer value to write whose
1455         // bit width is > 64. However, in canonical unsigned integer
1456         // format it is likely that the high bits are going to be zero.
1457         // So, we only write the number of active words.
1458         unsigned NWords = IV->getValue().getActiveWords();
1459         const uint64_t *RawWords = IV->getValue().getRawData();
1460         for (unsigned i = 0; i != NWords; ++i) {
1461           emitSignedInt64(Record, RawWords[i]);
1462         }
1463         Code = bitc::CST_CODE_WIDE_INTEGER;
1464       }
1465     } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
1466       Code = bitc::CST_CODE_FLOAT;
1467       Type *Ty = CFP->getType();
1468       if (Ty->isHalfTy() || Ty->isFloatTy() || Ty->isDoubleTy()) {
1469         Record.push_back(CFP->getValueAPF().bitcastToAPInt().getZExtValue());
1470       } else if (Ty->isX86_FP80Ty()) {
1471         // api needed to prevent premature destruction
1472         // bits are not in the same order as a normal i80 APInt, compensate.
1473         APInt api = CFP->getValueAPF().bitcastToAPInt();
1474         const uint64_t *p = api.getRawData();
1475         Record.push_back((p[1] << 48) | (p[0] >> 16));
1476         Record.push_back(p[0] & 0xffffLL);
1477       } else if (Ty->isFP128Ty() || Ty->isPPC_FP128Ty()) {
1478         APInt api = CFP->getValueAPF().bitcastToAPInt();
1479         const uint64_t *p = api.getRawData();
1480         Record.push_back(p[0]);
1481         Record.push_back(p[1]);
1482       } else {
1483         assert (0 && "Unknown FP type!");
1484       }
1485     } else if (isa<ConstantDataSequential>(C) &&
1486                cast<ConstantDataSequential>(C)->isString()) {
1487       const ConstantDataSequential *Str = cast<ConstantDataSequential>(C);
1488       // Emit constant strings specially.
1489       unsigned NumElts = Str->getNumElements();
1490       // If this is a null-terminated string, use the denser CSTRING encoding.
1491       if (Str->isCString()) {
1492         Code = bitc::CST_CODE_CSTRING;
1493         --NumElts;  // Don't encode the null, which isn't allowed by char6.
1494       } else {
1495         Code = bitc::CST_CODE_STRING;
1496         AbbrevToUse = String8Abbrev;
1497       }
1498       bool isCStr7 = Code == bitc::CST_CODE_CSTRING;
1499       bool isCStrChar6 = Code == bitc::CST_CODE_CSTRING;
1500       for (unsigned i = 0; i != NumElts; ++i) {
1501         unsigned char V = Str->getElementAsInteger(i);
1502         Record.push_back(V);
1503         isCStr7 &= (V & 128) == 0;
1504         if (isCStrChar6)
1505           isCStrChar6 = BitCodeAbbrevOp::isChar6(V);
1506       }
1507
1508       if (isCStrChar6)
1509         AbbrevToUse = CString6Abbrev;
1510       else if (isCStr7)
1511         AbbrevToUse = CString7Abbrev;
1512     } else if (const ConstantDataSequential *CDS =
1513                   dyn_cast<ConstantDataSequential>(C)) {
1514       Code = bitc::CST_CODE_DATA;
1515       Type *EltTy = CDS->getType()->getElementType();
1516       if (isa<IntegerType>(EltTy)) {
1517         for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i)
1518           Record.push_back(CDS->getElementAsInteger(i));
1519       } else if (EltTy->isFloatTy()) {
1520         for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
1521           union { float F; uint32_t I; };
1522           F = CDS->getElementAsFloat(i);
1523           Record.push_back(I);
1524         }
1525       } else {
1526         assert(EltTy->isDoubleTy() && "Unknown ConstantData element type");
1527         for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
1528           union { double F; uint64_t I; };
1529           F = CDS->getElementAsDouble(i);
1530           Record.push_back(I);
1531         }
1532       }
1533     } else if (isa<ConstantArray>(C) || isa<ConstantStruct>(C) ||
1534                isa<ConstantVector>(C)) {
1535       Code = bitc::CST_CODE_AGGREGATE;
1536       for (const Value *Op : C->operands())
1537         Record.push_back(VE.getValueID(Op));
1538       AbbrevToUse = AggregateAbbrev;
1539     } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
1540       switch (CE->getOpcode()) {
1541       default:
1542         if (Instruction::isCast(CE->getOpcode())) {
1543           Code = bitc::CST_CODE_CE_CAST;
1544           Record.push_back(GetEncodedCastOpcode(CE->getOpcode()));
1545           Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
1546           Record.push_back(VE.getValueID(C->getOperand(0)));
1547           AbbrevToUse = CONSTANTS_CE_CAST_Abbrev;
1548         } else {
1549           assert(CE->getNumOperands() == 2 && "Unknown constant expr!");
1550           Code = bitc::CST_CODE_CE_BINOP;
1551           Record.push_back(GetEncodedBinaryOpcode(CE->getOpcode()));
1552           Record.push_back(VE.getValueID(C->getOperand(0)));
1553           Record.push_back(VE.getValueID(C->getOperand(1)));
1554           uint64_t Flags = GetOptimizationFlags(CE);
1555           if (Flags != 0)
1556             Record.push_back(Flags);
1557         }
1558         break;
1559       case Instruction::GetElementPtr: {
1560         Code = bitc::CST_CODE_CE_GEP;
1561         const auto *GO = cast<GEPOperator>(C);
1562         if (GO->isInBounds())
1563           Code = bitc::CST_CODE_CE_INBOUNDS_GEP;
1564         Record.push_back(VE.getTypeID(GO->getSourceElementType()));
1565         for (unsigned i = 0, e = CE->getNumOperands(); i != e; ++i) {
1566           Record.push_back(VE.getTypeID(C->getOperand(i)->getType()));
1567           Record.push_back(VE.getValueID(C->getOperand(i)));
1568         }
1569         break;
1570       }
1571       case Instruction::Select:
1572         Code = bitc::CST_CODE_CE_SELECT;
1573         Record.push_back(VE.getValueID(C->getOperand(0)));
1574         Record.push_back(VE.getValueID(C->getOperand(1)));
1575         Record.push_back(VE.getValueID(C->getOperand(2)));
1576         break;
1577       case Instruction::ExtractElement:
1578         Code = bitc::CST_CODE_CE_EXTRACTELT;
1579         Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
1580         Record.push_back(VE.getValueID(C->getOperand(0)));
1581         Record.push_back(VE.getTypeID(C->getOperand(1)->getType()));
1582         Record.push_back(VE.getValueID(C->getOperand(1)));
1583         break;
1584       case Instruction::InsertElement:
1585         Code = bitc::CST_CODE_CE_INSERTELT;
1586         Record.push_back(VE.getValueID(C->getOperand(0)));
1587         Record.push_back(VE.getValueID(C->getOperand(1)));
1588         Record.push_back(VE.getTypeID(C->getOperand(2)->getType()));
1589         Record.push_back(VE.getValueID(C->getOperand(2)));
1590         break;
1591       case Instruction::ShuffleVector:
1592         // If the return type and argument types are the same, this is a
1593         // standard shufflevector instruction.  If the types are different,
1594         // then the shuffle is widening or truncating the input vectors, and
1595         // the argument type must also be encoded.
1596         if (C->getType() == C->getOperand(0)->getType()) {
1597           Code = bitc::CST_CODE_CE_SHUFFLEVEC;
1598         } else {
1599           Code = bitc::CST_CODE_CE_SHUFVEC_EX;
1600           Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
1601         }
1602         Record.push_back(VE.getValueID(C->getOperand(0)));
1603         Record.push_back(VE.getValueID(C->getOperand(1)));
1604         Record.push_back(VE.getValueID(C->getOperand(2)));
1605         break;
1606       case Instruction::ICmp:
1607       case Instruction::FCmp:
1608         Code = bitc::CST_CODE_CE_CMP;
1609         Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
1610         Record.push_back(VE.getValueID(C->getOperand(0)));
1611         Record.push_back(VE.getValueID(C->getOperand(1)));
1612         Record.push_back(CE->getPredicate());
1613         break;
1614       }
1615     } else if (const BlockAddress *BA = dyn_cast<BlockAddress>(C)) {
1616       Code = bitc::CST_CODE_BLOCKADDRESS;
1617       Record.push_back(VE.getTypeID(BA->getFunction()->getType()));
1618       Record.push_back(VE.getValueID(BA->getFunction()));
1619       Record.push_back(VE.getGlobalBasicBlockID(BA->getBasicBlock()));
1620     } else {
1621 #ifndef NDEBUG
1622       C->dump();
1623 #endif
1624       llvm_unreachable("Unknown constant!");
1625     }
1626     Stream.EmitRecord(Code, Record, AbbrevToUse);
1627     Record.clear();
1628   }
1629
1630   Stream.ExitBlock();
1631 }
1632
1633 static void WriteModuleConstants(const ValueEnumerator &VE,
1634                                  BitstreamWriter &Stream) {
1635   const ValueEnumerator::ValueList &Vals = VE.getValues();
1636
1637   // Find the first constant to emit, which is the first non-globalvalue value.
1638   // We know globalvalues have been emitted by WriteModuleInfo.
1639   for (unsigned i = 0, e = Vals.size(); i != e; ++i) {
1640     if (!isa<GlobalValue>(Vals[i].first)) {
1641       WriteConstants(i, Vals.size(), VE, Stream, true);
1642       return;
1643     }
1644   }
1645 }
1646
1647 /// PushValueAndType - The file has to encode both the value and type id for
1648 /// many values, because we need to know what type to create for forward
1649 /// references.  However, most operands are not forward references, so this type
1650 /// field is not needed.
1651 ///
1652 /// This function adds V's value ID to Vals.  If the value ID is higher than the
1653 /// instruction ID, then it is a forward reference, and it also includes the
1654 /// type ID.  The value ID that is written is encoded relative to the InstID.
1655 static bool PushValueAndType(const Value *V, unsigned InstID,
1656                              SmallVectorImpl<unsigned> &Vals,
1657                              ValueEnumerator &VE) {
1658   unsigned ValID = VE.getValueID(V);
1659   // Make encoding relative to the InstID.
1660   Vals.push_back(InstID - ValID);
1661   if (ValID >= InstID) {
1662     Vals.push_back(VE.getTypeID(V->getType()));
1663     return true;
1664   }
1665   return false;
1666 }
1667
1668 /// pushValue - Like PushValueAndType, but where the type of the value is
1669 /// omitted (perhaps it was already encoded in an earlier operand).
1670 static void pushValue(const Value *V, unsigned InstID,
1671                       SmallVectorImpl<unsigned> &Vals,
1672                       ValueEnumerator &VE) {
1673   unsigned ValID = VE.getValueID(V);
1674   Vals.push_back(InstID - ValID);
1675 }
1676
1677 static void pushValueSigned(const Value *V, unsigned InstID,
1678                             SmallVectorImpl<uint64_t> &Vals,
1679                             ValueEnumerator &VE) {
1680   unsigned ValID = VE.getValueID(V);
1681   int64_t diff = ((int32_t)InstID - (int32_t)ValID);
1682   emitSignedInt64(Vals, diff);
1683 }
1684
1685 /// WriteInstruction - Emit an instruction to the specified stream.
1686 static void WriteInstruction(const Instruction &I, unsigned InstID,
1687                              ValueEnumerator &VE, BitstreamWriter &Stream,
1688                              SmallVectorImpl<unsigned> &Vals) {
1689   unsigned Code = 0;
1690   unsigned AbbrevToUse = 0;
1691   VE.setInstructionID(&I);
1692   switch (I.getOpcode()) {
1693   default:
1694     if (Instruction::isCast(I.getOpcode())) {
1695       Code = bitc::FUNC_CODE_INST_CAST;
1696       if (!PushValueAndType(I.getOperand(0), InstID, Vals, VE))
1697         AbbrevToUse = FUNCTION_INST_CAST_ABBREV;
1698       Vals.push_back(VE.getTypeID(I.getType()));
1699       Vals.push_back(GetEncodedCastOpcode(I.getOpcode()));
1700     } else {
1701       assert(isa<BinaryOperator>(I) && "Unknown instruction!");
1702       Code = bitc::FUNC_CODE_INST_BINOP;
1703       if (!PushValueAndType(I.getOperand(0), InstID, Vals, VE))
1704         AbbrevToUse = FUNCTION_INST_BINOP_ABBREV;
1705       pushValue(I.getOperand(1), InstID, Vals, VE);
1706       Vals.push_back(GetEncodedBinaryOpcode(I.getOpcode()));
1707       uint64_t Flags = GetOptimizationFlags(&I);
1708       if (Flags != 0) {
1709         if (AbbrevToUse == FUNCTION_INST_BINOP_ABBREV)
1710           AbbrevToUse = FUNCTION_INST_BINOP_FLAGS_ABBREV;
1711         Vals.push_back(Flags);
1712       }
1713     }
1714     break;
1715
1716   case Instruction::GetElementPtr: {
1717     Code = bitc::FUNC_CODE_INST_GEP;
1718     AbbrevToUse = FUNCTION_INST_GEP_ABBREV;
1719     auto &GEPInst = cast<GetElementPtrInst>(I);
1720     Vals.push_back(GEPInst.isInBounds());
1721     Vals.push_back(VE.getTypeID(GEPInst.getSourceElementType()));
1722     for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
1723       PushValueAndType(I.getOperand(i), InstID, Vals, VE);
1724     break;
1725   }
1726   case Instruction::ExtractValue: {
1727     Code = bitc::FUNC_CODE_INST_EXTRACTVAL;
1728     PushValueAndType(I.getOperand(0), InstID, Vals, VE);
1729     const ExtractValueInst *EVI = cast<ExtractValueInst>(&I);
1730     Vals.append(EVI->idx_begin(), EVI->idx_end());
1731     break;
1732   }
1733   case Instruction::InsertValue: {
1734     Code = bitc::FUNC_CODE_INST_INSERTVAL;
1735     PushValueAndType(I.getOperand(0), InstID, Vals, VE);
1736     PushValueAndType(I.getOperand(1), InstID, Vals, VE);
1737     const InsertValueInst *IVI = cast<InsertValueInst>(&I);
1738     Vals.append(IVI->idx_begin(), IVI->idx_end());
1739     break;
1740   }
1741   case Instruction::Select:
1742     Code = bitc::FUNC_CODE_INST_VSELECT;
1743     PushValueAndType(I.getOperand(1), InstID, Vals, VE);
1744     pushValue(I.getOperand(2), InstID, Vals, VE);
1745     PushValueAndType(I.getOperand(0), InstID, Vals, VE);
1746     break;
1747   case Instruction::ExtractElement:
1748     Code = bitc::FUNC_CODE_INST_EXTRACTELT;
1749     PushValueAndType(I.getOperand(0), InstID, Vals, VE);
1750     PushValueAndType(I.getOperand(1), InstID, Vals, VE);
1751     break;
1752   case Instruction::InsertElement:
1753     Code = bitc::FUNC_CODE_INST_INSERTELT;
1754     PushValueAndType(I.getOperand(0), InstID, Vals, VE);
1755     pushValue(I.getOperand(1), InstID, Vals, VE);
1756     PushValueAndType(I.getOperand(2), InstID, Vals, VE);
1757     break;
1758   case Instruction::ShuffleVector:
1759     Code = bitc::FUNC_CODE_INST_SHUFFLEVEC;
1760     PushValueAndType(I.getOperand(0), InstID, Vals, VE);
1761     pushValue(I.getOperand(1), InstID, Vals, VE);
1762     pushValue(I.getOperand(2), InstID, Vals, VE);
1763     break;
1764   case Instruction::ICmp:
1765   case Instruction::FCmp: {
1766     // compare returning Int1Ty or vector of Int1Ty
1767     Code = bitc::FUNC_CODE_INST_CMP2;
1768     PushValueAndType(I.getOperand(0), InstID, Vals, VE);
1769     pushValue(I.getOperand(1), InstID, Vals, VE);
1770     Vals.push_back(cast<CmpInst>(I).getPredicate());
1771     uint64_t Flags = GetOptimizationFlags(&I);
1772     if (Flags != 0)
1773       Vals.push_back(Flags);
1774     break;
1775   }
1776
1777   case Instruction::Ret:
1778     {
1779       Code = bitc::FUNC_CODE_INST_RET;
1780       unsigned NumOperands = I.getNumOperands();
1781       if (NumOperands == 0)
1782         AbbrevToUse = FUNCTION_INST_RET_VOID_ABBREV;
1783       else if (NumOperands == 1) {
1784         if (!PushValueAndType(I.getOperand(0), InstID, Vals, VE))
1785           AbbrevToUse = FUNCTION_INST_RET_VAL_ABBREV;
1786       } else {
1787         for (unsigned i = 0, e = NumOperands; i != e; ++i)
1788           PushValueAndType(I.getOperand(i), InstID, Vals, VE);
1789       }
1790     }
1791     break;
1792   case Instruction::Br:
1793     {
1794       Code = bitc::FUNC_CODE_INST_BR;
1795       const BranchInst &II = cast<BranchInst>(I);
1796       Vals.push_back(VE.getValueID(II.getSuccessor(0)));
1797       if (II.isConditional()) {
1798         Vals.push_back(VE.getValueID(II.getSuccessor(1)));
1799         pushValue(II.getCondition(), InstID, Vals, VE);
1800       }
1801     }
1802     break;
1803   case Instruction::Switch:
1804     {
1805       Code = bitc::FUNC_CODE_INST_SWITCH;
1806       const SwitchInst &SI = cast<SwitchInst>(I);
1807       Vals.push_back(VE.getTypeID(SI.getCondition()->getType()));
1808       pushValue(SI.getCondition(), InstID, Vals, VE);
1809       Vals.push_back(VE.getValueID(SI.getDefaultDest()));
1810       for (SwitchInst::ConstCaseIt i = SI.case_begin(), e = SI.case_end();
1811            i != e; ++i) {
1812         Vals.push_back(VE.getValueID(i.getCaseValue()));
1813         Vals.push_back(VE.getValueID(i.getCaseSuccessor()));
1814       }
1815     }
1816     break;
1817   case Instruction::IndirectBr:
1818     Code = bitc::FUNC_CODE_INST_INDIRECTBR;
1819     Vals.push_back(VE.getTypeID(I.getOperand(0)->getType()));
1820     // Encode the address operand as relative, but not the basic blocks.
1821     pushValue(I.getOperand(0), InstID, Vals, VE);
1822     for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i)
1823       Vals.push_back(VE.getValueID(I.getOperand(i)));
1824     break;
1825
1826   case Instruction::Invoke: {
1827     const InvokeInst *II = cast<InvokeInst>(&I);
1828     const Value *Callee = II->getCalledValue();
1829     FunctionType *FTy = II->getFunctionType();
1830     Code = bitc::FUNC_CODE_INST_INVOKE;
1831
1832     Vals.push_back(VE.getAttributeID(II->getAttributes()));
1833     Vals.push_back(II->getCallingConv() | 1 << 13);
1834     Vals.push_back(VE.getValueID(II->getNormalDest()));
1835     Vals.push_back(VE.getValueID(II->getUnwindDest()));
1836     Vals.push_back(VE.getTypeID(FTy));
1837     PushValueAndType(Callee, InstID, Vals, VE);
1838
1839     // Emit value #'s for the fixed parameters.
1840     for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
1841       pushValue(I.getOperand(i), InstID, Vals, VE);  // fixed param.
1842
1843     // Emit type/value pairs for varargs params.
1844     if (FTy->isVarArg()) {
1845       for (unsigned i = FTy->getNumParams(), e = I.getNumOperands()-3;
1846            i != e; ++i)
1847         PushValueAndType(I.getOperand(i), InstID, Vals, VE); // vararg
1848     }
1849     break;
1850   }
1851   case Instruction::Resume:
1852     Code = bitc::FUNC_CODE_INST_RESUME;
1853     PushValueAndType(I.getOperand(0), InstID, Vals, VE);
1854     break;
1855   case Instruction::CleanupRet: {
1856     Code = bitc::FUNC_CODE_INST_CLEANUPRET;
1857     const auto &CRI = cast<CleanupReturnInst>(I);
1858     pushValue(CRI.getCleanupPad(), InstID, Vals, VE);
1859     if (CRI.hasUnwindDest())
1860       Vals.push_back(VE.getValueID(CRI.getUnwindDest()));
1861     break;
1862   }
1863   case Instruction::CatchRet: {
1864     Code = bitc::FUNC_CODE_INST_CATCHRET;
1865     const auto &CRI = cast<CatchReturnInst>(I);
1866     pushValue(CRI.getCatchPad(), InstID, Vals, VE);
1867     Vals.push_back(VE.getValueID(CRI.getSuccessor()));
1868     break;
1869   }
1870   case Instruction::CatchPad: {
1871     Code = bitc::FUNC_CODE_INST_CATCHPAD;
1872     const auto &CPI = cast<CatchPadInst>(I);
1873     Vals.push_back(VE.getValueID(CPI.getNormalDest()));
1874     Vals.push_back(VE.getValueID(CPI.getUnwindDest()));
1875     unsigned NumArgOperands = CPI.getNumArgOperands();
1876     Vals.push_back(NumArgOperands);
1877     for (unsigned Op = 0; Op != NumArgOperands; ++Op)
1878       PushValueAndType(CPI.getArgOperand(Op), InstID, Vals, VE);
1879     break;
1880   }
1881   case Instruction::TerminatePad: {
1882     Code = bitc::FUNC_CODE_INST_TERMINATEPAD;
1883     const auto &TPI = cast<TerminatePadInst>(I);
1884     Vals.push_back(TPI.hasUnwindDest());
1885     if (TPI.hasUnwindDest())
1886       Vals.push_back(VE.getValueID(TPI.getUnwindDest()));
1887     unsigned NumArgOperands = TPI.getNumArgOperands();
1888     Vals.push_back(NumArgOperands);
1889     for (unsigned Op = 0; Op != NumArgOperands; ++Op)
1890       PushValueAndType(TPI.getArgOperand(Op), InstID, Vals, VE);
1891     break;
1892   }
1893   case Instruction::CleanupPad: {
1894     Code = bitc::FUNC_CODE_INST_CLEANUPPAD;
1895     const auto &CPI = cast<CleanupPadInst>(I);
1896     unsigned NumOperands = CPI.getNumOperands();
1897     Vals.push_back(NumOperands);
1898     for (unsigned Op = 0; Op != NumOperands; ++Op)
1899       PushValueAndType(CPI.getOperand(Op), InstID, Vals, VE);
1900     break;
1901   }
1902   case Instruction::CatchEndPad: {
1903     Code = bitc::FUNC_CODE_INST_CATCHENDPAD;
1904     const auto &CEPI = cast<CatchEndPadInst>(I);
1905     if (CEPI.hasUnwindDest())
1906       Vals.push_back(VE.getValueID(CEPI.getUnwindDest()));
1907     break;
1908   }
1909   case Instruction::CleanupEndPad: {
1910     Code = bitc::FUNC_CODE_INST_CLEANUPENDPAD;
1911     const auto &CEPI = cast<CleanupEndPadInst>(I);
1912     pushValue(CEPI.getCleanupPad(), InstID, Vals, VE);
1913     if (CEPI.hasUnwindDest())
1914       Vals.push_back(VE.getValueID(CEPI.getUnwindDest()));
1915     break;
1916   }
1917   case Instruction::Unreachable:
1918     Code = bitc::FUNC_CODE_INST_UNREACHABLE;
1919     AbbrevToUse = FUNCTION_INST_UNREACHABLE_ABBREV;
1920     break;
1921
1922   case Instruction::PHI: {
1923     const PHINode &PN = cast<PHINode>(I);
1924     Code = bitc::FUNC_CODE_INST_PHI;
1925     // With the newer instruction encoding, forward references could give
1926     // negative valued IDs.  This is most common for PHIs, so we use
1927     // signed VBRs.
1928     SmallVector<uint64_t, 128> Vals64;
1929     Vals64.push_back(VE.getTypeID(PN.getType()));
1930     for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
1931       pushValueSigned(PN.getIncomingValue(i), InstID, Vals64, VE);
1932       Vals64.push_back(VE.getValueID(PN.getIncomingBlock(i)));
1933     }
1934     // Emit a Vals64 vector and exit.
1935     Stream.EmitRecord(Code, Vals64, AbbrevToUse);
1936     Vals64.clear();
1937     return;
1938   }
1939
1940   case Instruction::LandingPad: {
1941     const LandingPadInst &LP = cast<LandingPadInst>(I);
1942     Code = bitc::FUNC_CODE_INST_LANDINGPAD;
1943     Vals.push_back(VE.getTypeID(LP.getType()));
1944     Vals.push_back(LP.isCleanup());
1945     Vals.push_back(LP.getNumClauses());
1946     for (unsigned I = 0, E = LP.getNumClauses(); I != E; ++I) {
1947       if (LP.isCatch(I))
1948         Vals.push_back(LandingPadInst::Catch);
1949       else
1950         Vals.push_back(LandingPadInst::Filter);
1951       PushValueAndType(LP.getClause(I), InstID, Vals, VE);
1952     }
1953     break;
1954   }
1955
1956   case Instruction::Alloca: {
1957     Code = bitc::FUNC_CODE_INST_ALLOCA;
1958     const AllocaInst &AI = cast<AllocaInst>(I);
1959     Vals.push_back(VE.getTypeID(AI.getAllocatedType()));
1960     Vals.push_back(VE.getTypeID(I.getOperand(0)->getType()));
1961     Vals.push_back(VE.getValueID(I.getOperand(0))); // size.
1962     unsigned AlignRecord = Log2_32(AI.getAlignment()) + 1;
1963     assert(Log2_32(Value::MaximumAlignment) + 1 < 1 << 5 &&
1964            "not enough bits for maximum alignment");
1965     assert(AlignRecord < 1 << 5 && "alignment greater than 1 << 64");
1966     AlignRecord |= AI.isUsedWithInAlloca() << 5;
1967     AlignRecord |= 1 << 6;
1968     // Reserve bit 7 for SwiftError flag.
1969     // AlignRecord |= AI.isSwiftError() << 7;
1970     Vals.push_back(AlignRecord);
1971     break;
1972   }
1973
1974   case Instruction::Load:
1975     if (cast<LoadInst>(I).isAtomic()) {
1976       Code = bitc::FUNC_CODE_INST_LOADATOMIC;
1977       PushValueAndType(I.getOperand(0), InstID, Vals, VE);
1978     } else {
1979       Code = bitc::FUNC_CODE_INST_LOAD;
1980       if (!PushValueAndType(I.getOperand(0), InstID, Vals, VE))  // ptr
1981         AbbrevToUse = FUNCTION_INST_LOAD_ABBREV;
1982     }
1983     Vals.push_back(VE.getTypeID(I.getType()));
1984     Vals.push_back(Log2_32(cast<LoadInst>(I).getAlignment())+1);
1985     Vals.push_back(cast<LoadInst>(I).isVolatile());
1986     if (cast<LoadInst>(I).isAtomic()) {
1987       Vals.push_back(GetEncodedOrdering(cast<LoadInst>(I).getOrdering()));
1988       Vals.push_back(GetEncodedSynchScope(cast<LoadInst>(I).getSynchScope()));
1989     }
1990     break;
1991   case Instruction::Store:
1992     if (cast<StoreInst>(I).isAtomic())
1993       Code = bitc::FUNC_CODE_INST_STOREATOMIC;
1994     else
1995       Code = bitc::FUNC_CODE_INST_STORE;
1996     PushValueAndType(I.getOperand(1), InstID, Vals, VE);  // ptrty + ptr
1997     PushValueAndType(I.getOperand(0), InstID, Vals, VE);  // valty + val
1998     Vals.push_back(Log2_32(cast<StoreInst>(I).getAlignment())+1);
1999     Vals.push_back(cast<StoreInst>(I).isVolatile());
2000     if (cast<StoreInst>(I).isAtomic()) {
2001       Vals.push_back(GetEncodedOrdering(cast<StoreInst>(I).getOrdering()));
2002       Vals.push_back(GetEncodedSynchScope(cast<StoreInst>(I).getSynchScope()));
2003     }
2004     break;
2005   case Instruction::AtomicCmpXchg:
2006     Code = bitc::FUNC_CODE_INST_CMPXCHG;
2007     PushValueAndType(I.getOperand(0), InstID, Vals, VE);  // ptrty + ptr
2008     PushValueAndType(I.getOperand(1), InstID, Vals, VE);         // cmp.
2009     pushValue(I.getOperand(2), InstID, Vals, VE);         // newval.
2010     Vals.push_back(cast<AtomicCmpXchgInst>(I).isVolatile());
2011     Vals.push_back(GetEncodedOrdering(
2012                      cast<AtomicCmpXchgInst>(I).getSuccessOrdering()));
2013     Vals.push_back(GetEncodedSynchScope(
2014                      cast<AtomicCmpXchgInst>(I).getSynchScope()));
2015     Vals.push_back(GetEncodedOrdering(
2016                      cast<AtomicCmpXchgInst>(I).getFailureOrdering()));
2017     Vals.push_back(cast<AtomicCmpXchgInst>(I).isWeak());
2018     break;
2019   case Instruction::AtomicRMW:
2020     Code = bitc::FUNC_CODE_INST_ATOMICRMW;
2021     PushValueAndType(I.getOperand(0), InstID, Vals, VE);  // ptrty + ptr
2022     pushValue(I.getOperand(1), InstID, Vals, VE);         // val.
2023     Vals.push_back(GetEncodedRMWOperation(
2024                      cast<AtomicRMWInst>(I).getOperation()));
2025     Vals.push_back(cast<AtomicRMWInst>(I).isVolatile());
2026     Vals.push_back(GetEncodedOrdering(cast<AtomicRMWInst>(I).getOrdering()));
2027     Vals.push_back(GetEncodedSynchScope(
2028                      cast<AtomicRMWInst>(I).getSynchScope()));
2029     break;
2030   case Instruction::Fence:
2031     Code = bitc::FUNC_CODE_INST_FENCE;
2032     Vals.push_back(GetEncodedOrdering(cast<FenceInst>(I).getOrdering()));
2033     Vals.push_back(GetEncodedSynchScope(cast<FenceInst>(I).getSynchScope()));
2034     break;
2035   case Instruction::Call: {
2036     const CallInst &CI = cast<CallInst>(I);
2037     FunctionType *FTy = CI.getFunctionType();
2038
2039     Code = bitc::FUNC_CODE_INST_CALL;
2040
2041     Vals.push_back(VE.getAttributeID(CI.getAttributes()));
2042     Vals.push_back((CI.getCallingConv() << 1) | unsigned(CI.isTailCall()) |
2043                    unsigned(CI.isMustTailCall()) << 14 | 1 << 15);
2044     Vals.push_back(VE.getTypeID(FTy));
2045     PushValueAndType(CI.getCalledValue(), InstID, Vals, VE);  // Callee
2046
2047     // Emit value #'s for the fixed parameters.
2048     for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i) {
2049       // Check for labels (can happen with asm labels).
2050       if (FTy->getParamType(i)->isLabelTy())
2051         Vals.push_back(VE.getValueID(CI.getArgOperand(i)));
2052       else
2053         pushValue(CI.getArgOperand(i), InstID, Vals, VE);  // fixed param.
2054     }
2055
2056     // Emit type/value pairs for varargs params.
2057     if (FTy->isVarArg()) {
2058       for (unsigned i = FTy->getNumParams(), e = CI.getNumArgOperands();
2059            i != e; ++i)
2060         PushValueAndType(CI.getArgOperand(i), InstID, Vals, VE);  // varargs
2061     }
2062     break;
2063   }
2064   case Instruction::VAArg:
2065     Code = bitc::FUNC_CODE_INST_VAARG;
2066     Vals.push_back(VE.getTypeID(I.getOperand(0)->getType()));   // valistty
2067     pushValue(I.getOperand(0), InstID, Vals, VE); // valist.
2068     Vals.push_back(VE.getTypeID(I.getType())); // restype.
2069     break;
2070   }
2071
2072   Stream.EmitRecord(Code, Vals, AbbrevToUse);
2073   Vals.clear();
2074 }
2075
2076 // Emit names for globals/functions etc.
2077 static void WriteValueSymbolTable(const ValueSymbolTable &VST,
2078                                   const ValueEnumerator &VE,
2079                                   BitstreamWriter &Stream) {
2080   if (VST.empty()) return;
2081   Stream.EnterSubblock(bitc::VALUE_SYMTAB_BLOCK_ID, 4);
2082
2083   // FIXME: Set up the abbrev, we know how many values there are!
2084   // FIXME: We know if the type names can use 7-bit ascii.
2085   SmallVector<unsigned, 64> NameVals;
2086
2087   for (const ValueName &Name : VST) {
2088
2089     // Figure out the encoding to use for the name.
2090     bool is7Bit = true;
2091     bool isChar6 = true;
2092     for (const char *C = Name.getKeyData(), *E = C+Name.getKeyLength();
2093          C != E; ++C) {
2094       if (isChar6)
2095         isChar6 = BitCodeAbbrevOp::isChar6(*C);
2096       if ((unsigned char)*C & 128) {
2097         is7Bit = false;
2098         break;  // don't bother scanning the rest.
2099       }
2100     }
2101
2102     unsigned AbbrevToUse = VST_ENTRY_8_ABBREV;
2103
2104     // VST_ENTRY:   [valueid, namechar x N]
2105     // VST_BBENTRY: [bbid, namechar x N]
2106     unsigned Code;
2107     if (isa<BasicBlock>(Name.getValue())) {
2108       Code = bitc::VST_CODE_BBENTRY;
2109       if (isChar6)
2110         AbbrevToUse = VST_BBENTRY_6_ABBREV;
2111     } else {
2112       Code = bitc::VST_CODE_ENTRY;
2113       if (isChar6)
2114         AbbrevToUse = VST_ENTRY_6_ABBREV;
2115       else if (is7Bit)
2116         AbbrevToUse = VST_ENTRY_7_ABBREV;
2117     }
2118
2119     NameVals.push_back(VE.getValueID(Name.getValue()));
2120     for (const char *P = Name.getKeyData(),
2121          *E = Name.getKeyData()+Name.getKeyLength(); P != E; ++P)
2122       NameVals.push_back((unsigned char)*P);
2123
2124     // Emit the finished record.
2125     Stream.EmitRecord(Code, NameVals, AbbrevToUse);
2126     NameVals.clear();
2127   }
2128   Stream.ExitBlock();
2129 }
2130
2131 static void WriteUseList(ValueEnumerator &VE, UseListOrder &&Order,
2132                          BitstreamWriter &Stream) {
2133   assert(Order.Shuffle.size() >= 2 && "Shuffle too small");
2134   unsigned Code;
2135   if (isa<BasicBlock>(Order.V))
2136     Code = bitc::USELIST_CODE_BB;
2137   else
2138     Code = bitc::USELIST_CODE_DEFAULT;
2139
2140   SmallVector<uint64_t, 64> Record(Order.Shuffle.begin(), Order.Shuffle.end());
2141   Record.push_back(VE.getValueID(Order.V));
2142   Stream.EmitRecord(Code, Record);
2143 }
2144
2145 static void WriteUseListBlock(const Function *F, ValueEnumerator &VE,
2146                               BitstreamWriter &Stream) {
2147   assert(VE.shouldPreserveUseListOrder() &&
2148          "Expected to be preserving use-list order");
2149
2150   auto hasMore = [&]() {
2151     return !VE.UseListOrders.empty() && VE.UseListOrders.back().F == F;
2152   };
2153   if (!hasMore())
2154     // Nothing to do.
2155     return;
2156
2157   Stream.EnterSubblock(bitc::USELIST_BLOCK_ID, 3);
2158   while (hasMore()) {
2159     WriteUseList(VE, std::move(VE.UseListOrders.back()), Stream);
2160     VE.UseListOrders.pop_back();
2161   }
2162   Stream.ExitBlock();
2163 }
2164
2165 /// WriteFunction - Emit a function body to the module stream.
2166 static void WriteFunction(const Function &F, ValueEnumerator &VE,
2167                           BitstreamWriter &Stream) {
2168   Stream.EnterSubblock(bitc::FUNCTION_BLOCK_ID, 4);
2169   VE.incorporateFunction(F);
2170
2171   SmallVector<unsigned, 64> Vals;
2172
2173   // Emit the number of basic blocks, so the reader can create them ahead of
2174   // time.
2175   Vals.push_back(VE.getBasicBlocks().size());
2176   Stream.EmitRecord(bitc::FUNC_CODE_DECLAREBLOCKS, Vals);
2177   Vals.clear();
2178
2179   // If there are function-local constants, emit them now.
2180   unsigned CstStart, CstEnd;
2181   VE.getFunctionConstantRange(CstStart, CstEnd);
2182   WriteConstants(CstStart, CstEnd, VE, Stream, false);
2183
2184   // If there is function-local metadata, emit it now.
2185   WriteFunctionLocalMetadata(F, VE, Stream);
2186
2187   // Keep a running idea of what the instruction ID is.
2188   unsigned InstID = CstEnd;
2189
2190   bool NeedsMetadataAttachment = F.hasMetadata();
2191
2192   DILocation *LastDL = nullptr;
2193
2194   // Finally, emit all the instructions, in order.
2195   for (Function::const_iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
2196     for (BasicBlock::const_iterator I = BB->begin(), E = BB->end();
2197          I != E; ++I) {
2198       WriteInstruction(*I, InstID, VE, Stream, Vals);
2199
2200       if (!I->getType()->isVoidTy())
2201         ++InstID;
2202
2203       // If the instruction has metadata, write a metadata attachment later.
2204       NeedsMetadataAttachment |= I->hasMetadataOtherThanDebugLoc();
2205
2206       // If the instruction has a debug location, emit it.
2207       DILocation *DL = I->getDebugLoc();
2208       if (!DL)
2209         continue;
2210
2211       if (DL == LastDL) {
2212         // Just repeat the same debug loc as last time.
2213         Stream.EmitRecord(bitc::FUNC_CODE_DEBUG_LOC_AGAIN, Vals);
2214         continue;
2215       }
2216
2217       Vals.push_back(DL->getLine());
2218       Vals.push_back(DL->getColumn());
2219       Vals.push_back(VE.getMetadataOrNullID(DL->getScope()));
2220       Vals.push_back(VE.getMetadataOrNullID(DL->getInlinedAt()));
2221       Stream.EmitRecord(bitc::FUNC_CODE_DEBUG_LOC, Vals);
2222       Vals.clear();
2223
2224       LastDL = DL;
2225     }
2226
2227   // Emit names for all the instructions etc.
2228   WriteValueSymbolTable(F.getValueSymbolTable(), VE, Stream);
2229
2230   if (NeedsMetadataAttachment)
2231     WriteMetadataAttachment(F, VE, Stream);
2232   if (VE.shouldPreserveUseListOrder())
2233     WriteUseListBlock(&F, VE, Stream);
2234   VE.purgeFunction();
2235   Stream.ExitBlock();
2236 }
2237
2238 // Emit blockinfo, which defines the standard abbreviations etc.
2239 static void WriteBlockInfo(const ValueEnumerator &VE, BitstreamWriter &Stream) {
2240   // We only want to emit block info records for blocks that have multiple
2241   // instances: CONSTANTS_BLOCK, FUNCTION_BLOCK and VALUE_SYMTAB_BLOCK.
2242   // Other blocks can define their abbrevs inline.
2243   Stream.EnterBlockInfoBlock(2);
2244
2245   { // 8-bit fixed-width VST_ENTRY/VST_BBENTRY strings.
2246     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
2247     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 3));
2248     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
2249     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
2250     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
2251     if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID,
2252                                    Abbv) != VST_ENTRY_8_ABBREV)
2253       llvm_unreachable("Unexpected abbrev ordering!");
2254   }
2255
2256   { // 7-bit fixed width VST_ENTRY strings.
2257     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
2258     Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_ENTRY));
2259     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
2260     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
2261     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7));
2262     if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID,
2263                                    Abbv) != VST_ENTRY_7_ABBREV)
2264       llvm_unreachable("Unexpected abbrev ordering!");
2265   }
2266   { // 6-bit char6 VST_ENTRY strings.
2267     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
2268     Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_ENTRY));
2269     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
2270     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
2271     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
2272     if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID,
2273                                    Abbv) != VST_ENTRY_6_ABBREV)
2274       llvm_unreachable("Unexpected abbrev ordering!");
2275   }
2276   { // 6-bit char6 VST_BBENTRY strings.
2277     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
2278     Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_BBENTRY));
2279     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
2280     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
2281     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
2282     if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID,
2283                                    Abbv) != VST_BBENTRY_6_ABBREV)
2284       llvm_unreachable("Unexpected abbrev ordering!");
2285   }
2286
2287
2288
2289   { // SETTYPE abbrev for CONSTANTS_BLOCK.
2290     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
2291     Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_SETTYPE));
2292     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
2293                               VE.computeBitsRequiredForTypeIndicies()));
2294     if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID,
2295                                    Abbv) != CONSTANTS_SETTYPE_ABBREV)
2296       llvm_unreachable("Unexpected abbrev ordering!");
2297   }
2298
2299   { // INTEGER abbrev for CONSTANTS_BLOCK.
2300     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
2301     Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_INTEGER));
2302     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
2303     if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID,
2304                                    Abbv) != CONSTANTS_INTEGER_ABBREV)
2305       llvm_unreachable("Unexpected abbrev ordering!");
2306   }
2307
2308   { // CE_CAST abbrev for CONSTANTS_BLOCK.
2309     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
2310     Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_CE_CAST));
2311     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4));  // cast opc
2312     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,       // typeid
2313                               VE.computeBitsRequiredForTypeIndicies()));
2314     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));    // value id
2315
2316     if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID,
2317                                    Abbv) != CONSTANTS_CE_CAST_Abbrev)
2318       llvm_unreachable("Unexpected abbrev ordering!");
2319   }
2320   { // NULL abbrev for CONSTANTS_BLOCK.
2321     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
2322     Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_NULL));
2323     if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID,
2324                                    Abbv) != CONSTANTS_NULL_Abbrev)
2325       llvm_unreachable("Unexpected abbrev ordering!");
2326   }
2327
2328   // FIXME: This should only use space for first class types!
2329
2330   { // INST_LOAD abbrev for FUNCTION_BLOCK.
2331     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
2332     Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_LOAD));
2333     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Ptr
2334     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,    // dest ty
2335                               VE.computeBitsRequiredForTypeIndicies()));
2336     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // Align
2337     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // volatile
2338     if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
2339                                    Abbv) != FUNCTION_INST_LOAD_ABBREV)
2340       llvm_unreachable("Unexpected abbrev ordering!");
2341   }
2342   { // INST_BINOP abbrev for FUNCTION_BLOCK.
2343     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
2344     Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_BINOP));
2345     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // LHS
2346     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // RHS
2347     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
2348     if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
2349                                    Abbv) != FUNCTION_INST_BINOP_ABBREV)
2350       llvm_unreachable("Unexpected abbrev ordering!");
2351   }
2352   { // INST_BINOP_FLAGS abbrev for FUNCTION_BLOCK.
2353     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
2354     Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_BINOP));
2355     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // LHS
2356     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // RHS
2357     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
2358     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7)); // flags
2359     if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
2360                                    Abbv) != FUNCTION_INST_BINOP_FLAGS_ABBREV)
2361       llvm_unreachable("Unexpected abbrev ordering!");
2362   }
2363   { // INST_CAST abbrev for FUNCTION_BLOCK.
2364     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
2365     Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_CAST));
2366     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));    // OpVal
2367     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,       // dest ty
2368                               VE.computeBitsRequiredForTypeIndicies()));
2369     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4));  // opc
2370     if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
2371                                    Abbv) != FUNCTION_INST_CAST_ABBREV)
2372       llvm_unreachable("Unexpected abbrev ordering!");
2373   }
2374
2375   { // INST_RET abbrev for FUNCTION_BLOCK.
2376     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
2377     Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_RET));
2378     if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
2379                                    Abbv) != FUNCTION_INST_RET_VOID_ABBREV)
2380       llvm_unreachable("Unexpected abbrev ordering!");
2381   }
2382   { // INST_RET abbrev for FUNCTION_BLOCK.
2383     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
2384     Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_RET));
2385     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // ValID
2386     if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
2387                                    Abbv) != FUNCTION_INST_RET_VAL_ABBREV)
2388       llvm_unreachable("Unexpected abbrev ordering!");
2389   }
2390   { // INST_UNREACHABLE abbrev for FUNCTION_BLOCK.
2391     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
2392     Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_UNREACHABLE));
2393     if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
2394                                    Abbv) != FUNCTION_INST_UNREACHABLE_ABBREV)
2395       llvm_unreachable("Unexpected abbrev ordering!");
2396   }
2397   {
2398     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
2399     Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_GEP));
2400     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));
2401     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, // dest ty
2402                               Log2_32_Ceil(VE.getTypes().size() + 1)));
2403     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
2404     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
2405     if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
2406         FUNCTION_INST_GEP_ABBREV)
2407       llvm_unreachable("Unexpected abbrev ordering!");
2408   }
2409
2410   Stream.ExitBlock();
2411 }
2412
2413 /// WriteModule - Emit the specified module to the bitstream.
2414 static void WriteModule(const Module *M, BitstreamWriter &Stream,
2415                         bool ShouldPreserveUseListOrder) {
2416   Stream.EnterSubblock(bitc::MODULE_BLOCK_ID, 3);
2417
2418   SmallVector<unsigned, 1> Vals;
2419   unsigned CurVersion = 1;
2420   Vals.push_back(CurVersion);
2421   Stream.EmitRecord(bitc::MODULE_CODE_VERSION, Vals);
2422
2423   // Analyze the module, enumerating globals, functions, etc.
2424   ValueEnumerator VE(*M, ShouldPreserveUseListOrder);
2425
2426   // Emit blockinfo, which defines the standard abbreviations etc.
2427   WriteBlockInfo(VE, Stream);
2428
2429   // Emit information about attribute groups.
2430   WriteAttributeGroupTable(VE, Stream);
2431
2432   // Emit information about parameter attributes.
2433   WriteAttributeTable(VE, Stream);
2434
2435   // Emit information describing all of the types in the module.
2436   WriteTypeTable(VE, Stream);
2437
2438   writeComdats(VE, Stream);
2439
2440   // Emit top-level description of module, including target triple, inline asm,
2441   // descriptors for global variables, and function prototype info.
2442   WriteModuleInfo(M, VE, Stream);
2443
2444   // Emit constants.
2445   WriteModuleConstants(VE, Stream);
2446
2447   // Emit metadata.
2448   WriteModuleMetadata(M, VE, Stream);
2449
2450   // Emit metadata.
2451   WriteModuleMetadataStore(M, Stream);
2452
2453   // Emit names for globals/functions etc.
2454   WriteValueSymbolTable(M->getValueSymbolTable(), VE, Stream);
2455
2456   // Emit module-level use-lists.
2457   if (VE.shouldPreserveUseListOrder())
2458     WriteUseListBlock(nullptr, VE, Stream);
2459
2460   // Emit function bodies.
2461   for (Module::const_iterator F = M->begin(), E = M->end(); F != E; ++F)
2462     if (!F->isDeclaration())
2463       WriteFunction(*F, VE, Stream);
2464
2465   Stream.ExitBlock();
2466 }
2467
2468 /// EmitDarwinBCHeader - If generating a bc file on darwin, we have to emit a
2469 /// header and trailer to make it compatible with the system archiver.  To do
2470 /// this we emit the following header, and then emit a trailer that pads the
2471 /// file out to be a multiple of 16 bytes.
2472 ///
2473 /// struct bc_header {
2474 ///   uint32_t Magic;         // 0x0B17C0DE
2475 ///   uint32_t Version;       // Version, currently always 0.
2476 ///   uint32_t BitcodeOffset; // Offset to traditional bitcode file.
2477 ///   uint32_t BitcodeSize;   // Size of traditional bitcode file.
2478 ///   uint32_t CPUType;       // CPU specifier.
2479 ///   ... potentially more later ...
2480 /// };
2481 enum {
2482   DarwinBCSizeFieldOffset = 3*4, // Offset to bitcode_size.
2483   DarwinBCHeaderSize = 5*4
2484 };
2485
2486 static void WriteInt32ToBuffer(uint32_t Value, SmallVectorImpl<char> &Buffer,
2487                                uint32_t &Position) {
2488   support::endian::write32le(&Buffer[Position], Value);
2489   Position += 4;
2490 }
2491
2492 static void EmitDarwinBCHeaderAndTrailer(SmallVectorImpl<char> &Buffer,
2493                                          const Triple &TT) {
2494   unsigned CPUType = ~0U;
2495
2496   // Match x86_64-*, i[3-9]86-*, powerpc-*, powerpc64-*, arm-*, thumb-*,
2497   // armv[0-9]-*, thumbv[0-9]-*, armv5te-*, or armv6t2-*. The CPUType is a magic
2498   // number from /usr/include/mach/machine.h.  It is ok to reproduce the
2499   // specific constants here because they are implicitly part of the Darwin ABI.
2500   enum {
2501     DARWIN_CPU_ARCH_ABI64      = 0x01000000,
2502     DARWIN_CPU_TYPE_X86        = 7,
2503     DARWIN_CPU_TYPE_ARM        = 12,
2504     DARWIN_CPU_TYPE_POWERPC    = 18
2505   };
2506
2507   Triple::ArchType Arch = TT.getArch();
2508   if (Arch == Triple::x86_64)
2509     CPUType = DARWIN_CPU_TYPE_X86 | DARWIN_CPU_ARCH_ABI64;
2510   else if (Arch == Triple::x86)
2511     CPUType = DARWIN_CPU_TYPE_X86;
2512   else if (Arch == Triple::ppc)
2513     CPUType = DARWIN_CPU_TYPE_POWERPC;
2514   else if (Arch == Triple::ppc64)
2515     CPUType = DARWIN_CPU_TYPE_POWERPC | DARWIN_CPU_ARCH_ABI64;
2516   else if (Arch == Triple::arm || Arch == Triple::thumb)
2517     CPUType = DARWIN_CPU_TYPE_ARM;
2518
2519   // Traditional Bitcode starts after header.
2520   assert(Buffer.size() >= DarwinBCHeaderSize &&
2521          "Expected header size to be reserved");
2522   unsigned BCOffset = DarwinBCHeaderSize;
2523   unsigned BCSize = Buffer.size()-DarwinBCHeaderSize;
2524
2525   // Write the magic and version.
2526   unsigned Position = 0;
2527   WriteInt32ToBuffer(0x0B17C0DE , Buffer, Position);
2528   WriteInt32ToBuffer(0          , Buffer, Position); // Version.
2529   WriteInt32ToBuffer(BCOffset   , Buffer, Position);
2530   WriteInt32ToBuffer(BCSize     , Buffer, Position);
2531   WriteInt32ToBuffer(CPUType    , Buffer, Position);
2532
2533   // If the file is not a multiple of 16 bytes, insert dummy padding.
2534   while (Buffer.size() & 15)
2535     Buffer.push_back(0);
2536 }
2537
2538 /// WriteBitcodeToFile - Write the specified module to the specified output
2539 /// stream.
2540 void llvm::WriteBitcodeToFile(const Module *M, raw_ostream &Out,
2541                               bool ShouldPreserveUseListOrder) {
2542   SmallVector<char, 0> Buffer;
2543   Buffer.reserve(256*1024);
2544
2545   // If this is darwin or another generic macho target, reserve space for the
2546   // header.
2547   Triple TT(M->getTargetTriple());
2548   if (TT.isOSDarwin())
2549     Buffer.insert(Buffer.begin(), DarwinBCHeaderSize, 0);
2550
2551   // Emit the module into the buffer.
2552   {
2553     BitstreamWriter Stream(Buffer);
2554
2555     // Emit the file header.
2556     Stream.Emit((unsigned)'B', 8);
2557     Stream.Emit((unsigned)'C', 8);
2558     Stream.Emit(0x0, 4);
2559     Stream.Emit(0xC, 4);
2560     Stream.Emit(0xE, 4);
2561     Stream.Emit(0xD, 4);
2562
2563     // Emit the module.
2564     WriteModule(M, Stream, ShouldPreserveUseListOrder);
2565   }
2566
2567   if (TT.isOSDarwin())
2568     EmitDarwinBCHeaderAndTrailer(Buffer, TT);
2569
2570   // Write the generated bitstream to "Out".
2571   Out.write((char*)&Buffer.front(), Buffer.size());
2572 }