xref: /llvm-project/llvm/lib/Target/DirectX/DXILWriter/DXILBitcodeWriter.cpp (revision ae6a7809b74741a4227c45a88cbfb6735c58c70a)
1 //===- Bitcode/Writer/DXILBitcodeWriter.cpp - DXIL Bitcode Writer ---------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // Bitcode writer implementation.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "DXILBitcodeWriter.h"
14 #include "DXILValueEnumerator.h"
15 #include "DirectXIRPasses/PointerTypeAnalysis.h"
16 #include "llvm/ADT/STLExtras.h"
17 #include "llvm/Bitcode/BitcodeCommon.h"
18 #include "llvm/Bitcode/BitcodeReader.h"
19 #include "llvm/Bitcode/LLVMBitCodes.h"
20 #include "llvm/Bitstream/BitCodes.h"
21 #include "llvm/Bitstream/BitstreamWriter.h"
22 #include "llvm/IR/Attributes.h"
23 #include "llvm/IR/BasicBlock.h"
24 #include "llvm/IR/Comdat.h"
25 #include "llvm/IR/Constant.h"
26 #include "llvm/IR/Constants.h"
27 #include "llvm/IR/DebugInfoMetadata.h"
28 #include "llvm/IR/DebugLoc.h"
29 #include "llvm/IR/DerivedTypes.h"
30 #include "llvm/IR/Function.h"
31 #include "llvm/IR/GlobalAlias.h"
32 #include "llvm/IR/GlobalIFunc.h"
33 #include "llvm/IR/GlobalObject.h"
34 #include "llvm/IR/GlobalValue.h"
35 #include "llvm/IR/GlobalVariable.h"
36 #include "llvm/IR/InlineAsm.h"
37 #include "llvm/IR/InstrTypes.h"
38 #include "llvm/IR/Instruction.h"
39 #include "llvm/IR/Instructions.h"
40 #include "llvm/IR/LLVMContext.h"
41 #include "llvm/IR/Metadata.h"
42 #include "llvm/IR/Module.h"
43 #include "llvm/IR/ModuleSummaryIndex.h"
44 #include "llvm/IR/Operator.h"
45 #include "llvm/IR/Type.h"
46 #include "llvm/IR/UseListOrder.h"
47 #include "llvm/IR/Value.h"
48 #include "llvm/IR/ValueSymbolTable.h"
49 #include "llvm/Object/IRSymtab.h"
50 #include "llvm/Support/ErrorHandling.h"
51 #include "llvm/Support/ModRef.h"
52 #include "llvm/Support/SHA1.h"
53 #include "llvm/TargetParser/Triple.h"
54 
55 namespace llvm {
56 namespace dxil {
57 
58 // Generates an enum to use as an index in the Abbrev array of Metadata record.
59 enum MetadataAbbrev : unsigned {
60 #define HANDLE_MDNODE_LEAF(CLASS) CLASS##AbbrevID,
61 #include "llvm/IR/Metadata.def"
62   LastPlusOne
63 };
64 
65 class DXILBitcodeWriter {
66 
67   /// These are manifest constants used by the bitcode writer. They do not need
68   /// to be kept in sync with the reader, but need to be consistent within this
69   /// file.
70   enum {
71     // VALUE_SYMTAB_BLOCK abbrev id's.
72     VST_ENTRY_8_ABBREV = bitc::FIRST_APPLICATION_ABBREV,
73     VST_ENTRY_7_ABBREV,
74     VST_ENTRY_6_ABBREV,
75     VST_BBENTRY_6_ABBREV,
76 
77     // CONSTANTS_BLOCK abbrev id's.
78     CONSTANTS_SETTYPE_ABBREV = bitc::FIRST_APPLICATION_ABBREV,
79     CONSTANTS_INTEGER_ABBREV,
80     CONSTANTS_CE_CAST_Abbrev,
81     CONSTANTS_NULL_Abbrev,
82 
83     // FUNCTION_BLOCK abbrev id's.
84     FUNCTION_INST_LOAD_ABBREV = bitc::FIRST_APPLICATION_ABBREV,
85     FUNCTION_INST_BINOP_ABBREV,
86     FUNCTION_INST_BINOP_FLAGS_ABBREV,
87     FUNCTION_INST_CAST_ABBREV,
88     FUNCTION_INST_RET_VOID_ABBREV,
89     FUNCTION_INST_RET_VAL_ABBREV,
90     FUNCTION_INST_UNREACHABLE_ABBREV,
91     FUNCTION_INST_GEP_ABBREV,
92   };
93 
94   // Cache some types
95   Type *I8Ty;
96   Type *I8PtrTy;
97 
98   /// The stream created and owned by the client.
99   BitstreamWriter &Stream;
100 
101   StringTableBuilder &StrtabBuilder;
102 
103   /// The Module to write to bitcode.
104   const Module &M;
105 
106   /// Enumerates ids for all values in the module.
107   ValueEnumerator VE;
108 
109   /// Map that holds the correspondence between GUIDs in the summary index,
110   /// that came from indirect call profiles, and a value id generated by this
111   /// class to use in the VST and summary block records.
112   std::map<GlobalValue::GUID, unsigned> GUIDToValueIdMap;
113 
114   /// Tracks the last value id recorded in the GUIDToValueMap.
115   unsigned GlobalValueId;
116 
117   /// Saves the offset of the VSTOffset record that must eventually be
118   /// backpatched with the offset of the actual VST.
119   uint64_t VSTOffsetPlaceholder = 0;
120 
121   /// Pointer to the buffer allocated by caller for bitcode writing.
122   const SmallVectorImpl<char> &Buffer;
123 
124   /// The start bit of the identification block.
125   uint64_t BitcodeStartBit;
126 
127   /// This maps values to their typed pointers
128   PointerTypeMap PointerMap;
129 
130 public:
131   /// Constructs a ModuleBitcodeWriter object for the given Module,
132   /// writing to the provided \p Buffer.
133   DXILBitcodeWriter(const Module &M, SmallVectorImpl<char> &Buffer,
134                     StringTableBuilder &StrtabBuilder, BitstreamWriter &Stream)
135       : I8Ty(Type::getInt8Ty(M.getContext())),
136         I8PtrTy(TypedPointerType::get(I8Ty, 0)), Stream(Stream),
137         StrtabBuilder(StrtabBuilder), M(M), VE(M, I8PtrTy), Buffer(Buffer),
138         BitcodeStartBit(Stream.GetCurrentBitNo()),
139         PointerMap(PointerTypeAnalysis::run(M)) {
140     GlobalValueId = VE.getValues().size();
141     // Enumerate the typed pointers
142     for (auto El : PointerMap)
143       VE.EnumerateType(El.second);
144   }
145 
146   /// Emit the current module to the bitstream.
147   void write();
148 
149   static uint64_t getAttrKindEncoding(Attribute::AttrKind Kind);
150   static void writeStringRecord(BitstreamWriter &Stream, unsigned Code,
151                                 StringRef Str, unsigned AbbrevToUse);
152   static void writeIdentificationBlock(BitstreamWriter &Stream);
153   static void emitSignedInt64(SmallVectorImpl<uint64_t> &Vals, uint64_t V);
154   static void emitWideAPInt(SmallVectorImpl<uint64_t> &Vals, const APInt &A);
155 
156   static unsigned getEncodedComdatSelectionKind(const Comdat &C);
157   static unsigned getEncodedLinkage(const GlobalValue::LinkageTypes Linkage);
158   static unsigned getEncodedLinkage(const GlobalValue &GV);
159   static unsigned getEncodedVisibility(const GlobalValue &GV);
160   static unsigned getEncodedThreadLocalMode(const GlobalValue &GV);
161   static unsigned getEncodedDLLStorageClass(const GlobalValue &GV);
162   static unsigned getEncodedCastOpcode(unsigned Opcode);
163   static unsigned getEncodedUnaryOpcode(unsigned Opcode);
164   static unsigned getEncodedBinaryOpcode(unsigned Opcode);
165   static unsigned getEncodedRMWOperation(AtomicRMWInst::BinOp Op);
166   static unsigned getEncodedOrdering(AtomicOrdering Ordering);
167   static uint64_t getOptimizationFlags(const Value *V);
168 
169 private:
170   void writeModuleVersion();
171   void writePerModuleGlobalValueSummary();
172 
173   void writePerModuleFunctionSummaryRecord(SmallVector<uint64_t, 64> &NameVals,
174                                            GlobalValueSummary *Summary,
175                                            unsigned ValueID,
176                                            unsigned FSCallsAbbrev,
177                                            unsigned FSCallsProfileAbbrev,
178                                            const Function &F);
179   void writeModuleLevelReferences(const GlobalVariable &V,
180                                   SmallVector<uint64_t, 64> &NameVals,
181                                   unsigned FSModRefsAbbrev,
182                                   unsigned FSModVTableRefsAbbrev);
183 
184   void assignValueId(GlobalValue::GUID ValGUID) {
185     GUIDToValueIdMap[ValGUID] = ++GlobalValueId;
186   }
187 
188   unsigned getValueId(GlobalValue::GUID ValGUID) {
189     const auto &VMI = GUIDToValueIdMap.find(ValGUID);
190     // Expect that any GUID value had a value Id assigned by an
191     // earlier call to assignValueId.
192     assert(VMI != GUIDToValueIdMap.end() &&
193            "GUID does not have assigned value Id");
194     return VMI->second;
195   }
196 
197   // Helper to get the valueId for the type of value recorded in VI.
198   unsigned getValueId(ValueInfo VI) {
199     if (!VI.haveGVs() || !VI.getValue())
200       return getValueId(VI.getGUID());
201     return VE.getValueID(VI.getValue());
202   }
203 
204   std::map<GlobalValue::GUID, unsigned> &valueIds() { return GUIDToValueIdMap; }
205 
206   uint64_t bitcodeStartBit() { return BitcodeStartBit; }
207 
208   size_t addToStrtab(StringRef Str);
209 
210   unsigned createDILocationAbbrev();
211   unsigned createGenericDINodeAbbrev();
212 
213   void writeAttributeGroupTable();
214   void writeAttributeTable();
215   void writeTypeTable();
216   void writeComdats();
217   void writeValueSymbolTableForwardDecl();
218   void writeModuleInfo();
219   void writeValueAsMetadata(const ValueAsMetadata *MD,
220                             SmallVectorImpl<uint64_t> &Record);
221   void writeMDTuple(const MDTuple *N, SmallVectorImpl<uint64_t> &Record,
222                     unsigned Abbrev);
223   void writeDILocation(const DILocation *N, SmallVectorImpl<uint64_t> &Record,
224                        unsigned &Abbrev);
225   void writeGenericDINode(const GenericDINode *N,
226                           SmallVectorImpl<uint64_t> &Record, unsigned &Abbrev) {
227     llvm_unreachable("DXIL cannot contain GenericDI Nodes");
228   }
229   void writeDISubrange(const DISubrange *N, SmallVectorImpl<uint64_t> &Record,
230                        unsigned Abbrev);
231   void writeDIGenericSubrange(const DIGenericSubrange *N,
232                               SmallVectorImpl<uint64_t> &Record,
233                               unsigned Abbrev) {
234     llvm_unreachable("DXIL cannot contain DIGenericSubrange Nodes");
235   }
236   void writeDIEnumerator(const DIEnumerator *N,
237                          SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
238   void writeDIBasicType(const DIBasicType *N, SmallVectorImpl<uint64_t> &Record,
239                         unsigned Abbrev);
240   void writeDIStringType(const DIStringType *N,
241                          SmallVectorImpl<uint64_t> &Record, unsigned Abbrev) {
242     llvm_unreachable("DXIL cannot contain DIStringType Nodes");
243   }
244   void writeDIDerivedType(const DIDerivedType *N,
245                           SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
246   void writeDICompositeType(const DICompositeType *N,
247                             SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
248   void writeDISubroutineType(const DISubroutineType *N,
249                              SmallVectorImpl<uint64_t> &Record,
250                              unsigned Abbrev);
251   void writeDIFile(const DIFile *N, SmallVectorImpl<uint64_t> &Record,
252                    unsigned Abbrev);
253   void writeDICompileUnit(const DICompileUnit *N,
254                           SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
255   void writeDISubprogram(const DISubprogram *N,
256                          SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
257   void writeDILexicalBlock(const DILexicalBlock *N,
258                            SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
259   void writeDILexicalBlockFile(const DILexicalBlockFile *N,
260                                SmallVectorImpl<uint64_t> &Record,
261                                unsigned Abbrev);
262   void writeDICommonBlock(const DICommonBlock *N,
263                           SmallVectorImpl<uint64_t> &Record, unsigned Abbrev) {
264     llvm_unreachable("DXIL cannot contain DICommonBlock Nodes");
265   }
266   void writeDINamespace(const DINamespace *N, SmallVectorImpl<uint64_t> &Record,
267                         unsigned Abbrev);
268   void writeDIMacro(const DIMacro *N, SmallVectorImpl<uint64_t> &Record,
269                     unsigned Abbrev) {
270     llvm_unreachable("DXIL cannot contain DIMacro Nodes");
271   }
272   void writeDIMacroFile(const DIMacroFile *N, SmallVectorImpl<uint64_t> &Record,
273                         unsigned Abbrev) {
274     llvm_unreachable("DXIL cannot contain DIMacroFile Nodes");
275   }
276   void writeDIArgList(const DIArgList *N, SmallVectorImpl<uint64_t> &Record,
277                       unsigned Abbrev) {
278     llvm_unreachable("DXIL cannot contain DIArgList Nodes");
279   }
280   void writeDIAssignID(const DIAssignID *N, SmallVectorImpl<uint64_t> &Record,
281                        unsigned Abbrev) {
282     // DIAssignID is experimental feature to track variable location in IR..
283     // FIXME: translate DIAssignID to debug info DXIL supports.
284     //   See https://github.com/llvm/llvm-project/issues/58989
285     llvm_unreachable("DXIL cannot contain DIAssignID Nodes");
286   }
287   void writeDIModule(const DIModule *N, SmallVectorImpl<uint64_t> &Record,
288                      unsigned Abbrev);
289   void writeDITemplateTypeParameter(const DITemplateTypeParameter *N,
290                                     SmallVectorImpl<uint64_t> &Record,
291                                     unsigned Abbrev);
292   void writeDITemplateValueParameter(const DITemplateValueParameter *N,
293                                      SmallVectorImpl<uint64_t> &Record,
294                                      unsigned Abbrev);
295   void writeDIGlobalVariable(const DIGlobalVariable *N,
296                              SmallVectorImpl<uint64_t> &Record,
297                              unsigned Abbrev);
298   void writeDILocalVariable(const DILocalVariable *N,
299                             SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
300   void writeDILabel(const DILabel *N, SmallVectorImpl<uint64_t> &Record,
301                     unsigned Abbrev) {
302     llvm_unreachable("DXIL cannot contain DILabel Nodes");
303   }
304   void writeDIExpression(const DIExpression *N,
305                          SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
306   void writeDIGlobalVariableExpression(const DIGlobalVariableExpression *N,
307                                        SmallVectorImpl<uint64_t> &Record,
308                                        unsigned Abbrev) {
309     llvm_unreachable("DXIL cannot contain GlobalVariableExpression Nodes");
310   }
311   void writeDIObjCProperty(const DIObjCProperty *N,
312                            SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
313   void writeDIImportedEntity(const DIImportedEntity *N,
314                              SmallVectorImpl<uint64_t> &Record,
315                              unsigned Abbrev);
316   unsigned createNamedMetadataAbbrev();
317   void writeNamedMetadata(SmallVectorImpl<uint64_t> &Record);
318   unsigned createMetadataStringsAbbrev();
319   void writeMetadataStrings(ArrayRef<const Metadata *> Strings,
320                             SmallVectorImpl<uint64_t> &Record);
321   void writeMetadataRecords(ArrayRef<const Metadata *> MDs,
322                             SmallVectorImpl<uint64_t> &Record,
323                             std::vector<unsigned> *MDAbbrevs = nullptr,
324                             std::vector<uint64_t> *IndexPos = nullptr);
325   void writeModuleMetadata();
326   void writeFunctionMetadata(const Function &F);
327   void writeFunctionMetadataAttachment(const Function &F);
328   void pushGlobalMetadataAttachment(SmallVectorImpl<uint64_t> &Record,
329                                     const GlobalObject &GO);
330   void writeModuleMetadataKinds();
331   void writeOperandBundleTags();
332   void writeSyncScopeNames();
333   void writeConstants(unsigned FirstVal, unsigned LastVal, bool isGlobal);
334   void writeModuleConstants();
335   bool pushValueAndType(const Value *V, unsigned InstID,
336                         SmallVectorImpl<unsigned> &Vals);
337   void writeOperandBundles(const CallBase &CB, unsigned InstID);
338   void pushValue(const Value *V, unsigned InstID,
339                  SmallVectorImpl<unsigned> &Vals);
340   void pushValueSigned(const Value *V, unsigned InstID,
341                        SmallVectorImpl<uint64_t> &Vals);
342   void writeInstruction(const Instruction &I, unsigned InstID,
343                         SmallVectorImpl<unsigned> &Vals);
344   void writeFunctionLevelValueSymbolTable(const ValueSymbolTable &VST);
345   void writeGlobalValueSymbolTable(
346       DenseMap<const Function *, uint64_t> &FunctionToBitcodeIndex);
347   void writeFunction(const Function &F);
348   void writeBlockInfo();
349 
350   unsigned getEncodedSyncScopeID(SyncScope::ID SSID) { return unsigned(SSID); }
351 
352   unsigned getEncodedAlign(MaybeAlign Alignment) { return encode(Alignment); }
353 
354   unsigned getTypeID(Type *T, const Value *V = nullptr);
355   /// getGlobalObjectValueTypeID - returns the element type for a GlobalObject
356   ///
357   /// GlobalObject types are saved by PointerTypeAnalysis as pointers to the
358   /// GlobalObject, but in the bitcode writer we need the pointer element type.
359   unsigned getGlobalObjectValueTypeID(Type *T, const GlobalObject *G);
360 };
361 
362 } // namespace dxil
363 } // namespace llvm
364 
365 using namespace llvm;
366 using namespace llvm::dxil;
367 
368 ////////////////////////////////////////////////////////////////////////////////
369 /// Begin dxil::BitcodeWriter Implementation
370 ////////////////////////////////////////////////////////////////////////////////
371 
372 dxil::BitcodeWriter::BitcodeWriter(SmallVectorImpl<char> &Buffer)
373     : Buffer(Buffer), Stream(new BitstreamWriter(Buffer)) {
374   // Emit the file header.
375   Stream->Emit((unsigned)'B', 8);
376   Stream->Emit((unsigned)'C', 8);
377   Stream->Emit(0x0, 4);
378   Stream->Emit(0xC, 4);
379   Stream->Emit(0xE, 4);
380   Stream->Emit(0xD, 4);
381 }
382 
383 dxil::BitcodeWriter::~BitcodeWriter() { }
384 
385 /// Write the specified module to the specified output stream.
386 void dxil::WriteDXILToFile(const Module &M, raw_ostream &Out) {
387   SmallVector<char, 0> Buffer;
388   Buffer.reserve(256 * 1024);
389 
390   // If this is darwin or another generic macho target, reserve space for the
391   // header.
392   Triple TT(M.getTargetTriple());
393   if (TT.isOSDarwin() || TT.isOSBinFormatMachO())
394     Buffer.insert(Buffer.begin(), BWH_HeaderSize, 0);
395 
396   BitcodeWriter Writer(Buffer);
397   Writer.writeModule(M);
398 
399   // Write the generated bitstream to "Out".
400   if (!Buffer.empty())
401     Out.write((char *)&Buffer.front(), Buffer.size());
402 }
403 
404 void BitcodeWriter::writeBlob(unsigned Block, unsigned Record, StringRef Blob) {
405   Stream->EnterSubblock(Block, 3);
406 
407   auto Abbv = std::make_shared<BitCodeAbbrev>();
408   Abbv->Add(BitCodeAbbrevOp(Record));
409   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
410   auto AbbrevNo = Stream->EmitAbbrev(std::move(Abbv));
411 
412   Stream->EmitRecordWithBlob(AbbrevNo, ArrayRef<uint64_t>{Record}, Blob);
413 
414   Stream->ExitBlock();
415 }
416 
417 void BitcodeWriter::writeModule(const Module &M) {
418 
419   // The Mods vector is used by irsymtab::build, which requires non-const
420   // Modules in case it needs to materialize metadata. But the bitcode writer
421   // requires that the module is materialized, so we can cast to non-const here,
422   // after checking that it is in fact materialized.
423   assert(M.isMaterialized());
424   Mods.push_back(const_cast<Module *>(&M));
425 
426   DXILBitcodeWriter ModuleWriter(M, Buffer, StrtabBuilder, *Stream);
427   ModuleWriter.write();
428 }
429 
430 ////////////////////////////////////////////////////////////////////////////////
431 /// Begin dxil::BitcodeWriterBase Implementation
432 ////////////////////////////////////////////////////////////////////////////////
433 
434 unsigned DXILBitcodeWriter::getEncodedCastOpcode(unsigned Opcode) {
435   switch (Opcode) {
436   default:
437     llvm_unreachable("Unknown cast instruction!");
438   case Instruction::Trunc:
439     return bitc::CAST_TRUNC;
440   case Instruction::ZExt:
441     return bitc::CAST_ZEXT;
442   case Instruction::SExt:
443     return bitc::CAST_SEXT;
444   case Instruction::FPToUI:
445     return bitc::CAST_FPTOUI;
446   case Instruction::FPToSI:
447     return bitc::CAST_FPTOSI;
448   case Instruction::UIToFP:
449     return bitc::CAST_UITOFP;
450   case Instruction::SIToFP:
451     return bitc::CAST_SITOFP;
452   case Instruction::FPTrunc:
453     return bitc::CAST_FPTRUNC;
454   case Instruction::FPExt:
455     return bitc::CAST_FPEXT;
456   case Instruction::PtrToInt:
457     return bitc::CAST_PTRTOINT;
458   case Instruction::IntToPtr:
459     return bitc::CAST_INTTOPTR;
460   case Instruction::BitCast:
461     return bitc::CAST_BITCAST;
462   case Instruction::AddrSpaceCast:
463     return bitc::CAST_ADDRSPACECAST;
464   }
465 }
466 
467 unsigned DXILBitcodeWriter::getEncodedUnaryOpcode(unsigned Opcode) {
468   switch (Opcode) {
469   default:
470     llvm_unreachable("Unknown binary instruction!");
471   case Instruction::FNeg:
472     return bitc::UNOP_FNEG;
473   }
474 }
475 
476 unsigned DXILBitcodeWriter::getEncodedBinaryOpcode(unsigned Opcode) {
477   switch (Opcode) {
478   default:
479     llvm_unreachable("Unknown binary instruction!");
480   case Instruction::Add:
481   case Instruction::FAdd:
482     return bitc::BINOP_ADD;
483   case Instruction::Sub:
484   case Instruction::FSub:
485     return bitc::BINOP_SUB;
486   case Instruction::Mul:
487   case Instruction::FMul:
488     return bitc::BINOP_MUL;
489   case Instruction::UDiv:
490     return bitc::BINOP_UDIV;
491   case Instruction::FDiv:
492   case Instruction::SDiv:
493     return bitc::BINOP_SDIV;
494   case Instruction::URem:
495     return bitc::BINOP_UREM;
496   case Instruction::FRem:
497   case Instruction::SRem:
498     return bitc::BINOP_SREM;
499   case Instruction::Shl:
500     return bitc::BINOP_SHL;
501   case Instruction::LShr:
502     return bitc::BINOP_LSHR;
503   case Instruction::AShr:
504     return bitc::BINOP_ASHR;
505   case Instruction::And:
506     return bitc::BINOP_AND;
507   case Instruction::Or:
508     return bitc::BINOP_OR;
509   case Instruction::Xor:
510     return bitc::BINOP_XOR;
511   }
512 }
513 
514 unsigned DXILBitcodeWriter::getTypeID(Type *T, const Value *V) {
515   if (!T->isPointerTy() &&
516       // For Constant, always check PointerMap to make sure OpaquePointer in
517       // things like constant struct/array works.
518       (!V || !isa<Constant>(V)))
519     return VE.getTypeID(T);
520   auto It = PointerMap.find(V);
521   if (It != PointerMap.end())
522     return VE.getTypeID(It->second);
523   // For Constant, return T when cannot find in PointerMap.
524   // FIXME: support ConstantPointerNull which could map to more than one
525   // TypedPointerType.
526   // See https://github.com/llvm/llvm-project/issues/57942.
527   if (V && isa<Constant>(V) && !isa<ConstantPointerNull>(V))
528     return VE.getTypeID(T);
529   return VE.getTypeID(I8PtrTy);
530 }
531 
532 unsigned DXILBitcodeWriter::getGlobalObjectValueTypeID(Type *T,
533                                                        const GlobalObject *G) {
534   auto It = PointerMap.find(G);
535   if (It != PointerMap.end()) {
536     TypedPointerType *PtrTy = cast<TypedPointerType>(It->second);
537     return VE.getTypeID(PtrTy->getElementType());
538   }
539   return VE.getTypeID(T);
540 }
541 
542 unsigned DXILBitcodeWriter::getEncodedRMWOperation(AtomicRMWInst::BinOp Op) {
543   switch (Op) {
544   default:
545     llvm_unreachable("Unknown RMW operation!");
546   case AtomicRMWInst::Xchg:
547     return bitc::RMW_XCHG;
548   case AtomicRMWInst::Add:
549     return bitc::RMW_ADD;
550   case AtomicRMWInst::Sub:
551     return bitc::RMW_SUB;
552   case AtomicRMWInst::And:
553     return bitc::RMW_AND;
554   case AtomicRMWInst::Nand:
555     return bitc::RMW_NAND;
556   case AtomicRMWInst::Or:
557     return bitc::RMW_OR;
558   case AtomicRMWInst::Xor:
559     return bitc::RMW_XOR;
560   case AtomicRMWInst::Max:
561     return bitc::RMW_MAX;
562   case AtomicRMWInst::Min:
563     return bitc::RMW_MIN;
564   case AtomicRMWInst::UMax:
565     return bitc::RMW_UMAX;
566   case AtomicRMWInst::UMin:
567     return bitc::RMW_UMIN;
568   case AtomicRMWInst::FAdd:
569     return bitc::RMW_FADD;
570   case AtomicRMWInst::FSub:
571     return bitc::RMW_FSUB;
572   case AtomicRMWInst::FMax:
573     return bitc::RMW_FMAX;
574   case AtomicRMWInst::FMin:
575     return bitc::RMW_FMIN;
576   }
577 }
578 
579 unsigned DXILBitcodeWriter::getEncodedOrdering(AtomicOrdering Ordering) {
580   switch (Ordering) {
581   case AtomicOrdering::NotAtomic:
582     return bitc::ORDERING_NOTATOMIC;
583   case AtomicOrdering::Unordered:
584     return bitc::ORDERING_UNORDERED;
585   case AtomicOrdering::Monotonic:
586     return bitc::ORDERING_MONOTONIC;
587   case AtomicOrdering::Acquire:
588     return bitc::ORDERING_ACQUIRE;
589   case AtomicOrdering::Release:
590     return bitc::ORDERING_RELEASE;
591   case AtomicOrdering::AcquireRelease:
592     return bitc::ORDERING_ACQREL;
593   case AtomicOrdering::SequentiallyConsistent:
594     return bitc::ORDERING_SEQCST;
595   }
596   llvm_unreachable("Invalid ordering");
597 }
598 
599 void DXILBitcodeWriter::writeStringRecord(BitstreamWriter &Stream,
600                                           unsigned Code, StringRef Str,
601                                           unsigned AbbrevToUse) {
602   SmallVector<unsigned, 64> Vals;
603 
604   // Code: [strchar x N]
605   for (char C : Str) {
606     if (AbbrevToUse && !BitCodeAbbrevOp::isChar6(C))
607       AbbrevToUse = 0;
608     Vals.push_back(C);
609   }
610 
611   // Emit the finished record.
612   Stream.EmitRecord(Code, Vals, AbbrevToUse);
613 }
614 
615 uint64_t DXILBitcodeWriter::getAttrKindEncoding(Attribute::AttrKind Kind) {
616   switch (Kind) {
617   case Attribute::Alignment:
618     return bitc::ATTR_KIND_ALIGNMENT;
619   case Attribute::AlwaysInline:
620     return bitc::ATTR_KIND_ALWAYS_INLINE;
621   case Attribute::Builtin:
622     return bitc::ATTR_KIND_BUILTIN;
623   case Attribute::ByVal:
624     return bitc::ATTR_KIND_BY_VAL;
625   case Attribute::Convergent:
626     return bitc::ATTR_KIND_CONVERGENT;
627   case Attribute::InAlloca:
628     return bitc::ATTR_KIND_IN_ALLOCA;
629   case Attribute::Cold:
630     return bitc::ATTR_KIND_COLD;
631   case Attribute::InlineHint:
632     return bitc::ATTR_KIND_INLINE_HINT;
633   case Attribute::InReg:
634     return bitc::ATTR_KIND_IN_REG;
635   case Attribute::JumpTable:
636     return bitc::ATTR_KIND_JUMP_TABLE;
637   case Attribute::MinSize:
638     return bitc::ATTR_KIND_MIN_SIZE;
639   case Attribute::Naked:
640     return bitc::ATTR_KIND_NAKED;
641   case Attribute::Nest:
642     return bitc::ATTR_KIND_NEST;
643   case Attribute::NoAlias:
644     return bitc::ATTR_KIND_NO_ALIAS;
645   case Attribute::NoBuiltin:
646     return bitc::ATTR_KIND_NO_BUILTIN;
647   case Attribute::NoCapture:
648     return bitc::ATTR_KIND_NO_CAPTURE;
649   case Attribute::NoDuplicate:
650     return bitc::ATTR_KIND_NO_DUPLICATE;
651   case Attribute::NoImplicitFloat:
652     return bitc::ATTR_KIND_NO_IMPLICIT_FLOAT;
653   case Attribute::NoInline:
654     return bitc::ATTR_KIND_NO_INLINE;
655   case Attribute::NonLazyBind:
656     return bitc::ATTR_KIND_NON_LAZY_BIND;
657   case Attribute::NonNull:
658     return bitc::ATTR_KIND_NON_NULL;
659   case Attribute::Dereferenceable:
660     return bitc::ATTR_KIND_DEREFERENCEABLE;
661   case Attribute::DereferenceableOrNull:
662     return bitc::ATTR_KIND_DEREFERENCEABLE_OR_NULL;
663   case Attribute::NoRedZone:
664     return bitc::ATTR_KIND_NO_RED_ZONE;
665   case Attribute::NoReturn:
666     return bitc::ATTR_KIND_NO_RETURN;
667   case Attribute::NoUnwind:
668     return bitc::ATTR_KIND_NO_UNWIND;
669   case Attribute::OptimizeForSize:
670     return bitc::ATTR_KIND_OPTIMIZE_FOR_SIZE;
671   case Attribute::OptimizeNone:
672     return bitc::ATTR_KIND_OPTIMIZE_NONE;
673   case Attribute::ReadNone:
674     return bitc::ATTR_KIND_READ_NONE;
675   case Attribute::ReadOnly:
676     return bitc::ATTR_KIND_READ_ONLY;
677   case Attribute::Returned:
678     return bitc::ATTR_KIND_RETURNED;
679   case Attribute::ReturnsTwice:
680     return bitc::ATTR_KIND_RETURNS_TWICE;
681   case Attribute::SExt:
682     return bitc::ATTR_KIND_S_EXT;
683   case Attribute::StackAlignment:
684     return bitc::ATTR_KIND_STACK_ALIGNMENT;
685   case Attribute::StackProtect:
686     return bitc::ATTR_KIND_STACK_PROTECT;
687   case Attribute::StackProtectReq:
688     return bitc::ATTR_KIND_STACK_PROTECT_REQ;
689   case Attribute::StackProtectStrong:
690     return bitc::ATTR_KIND_STACK_PROTECT_STRONG;
691   case Attribute::SafeStack:
692     return bitc::ATTR_KIND_SAFESTACK;
693   case Attribute::StructRet:
694     return bitc::ATTR_KIND_STRUCT_RET;
695   case Attribute::SanitizeAddress:
696     return bitc::ATTR_KIND_SANITIZE_ADDRESS;
697   case Attribute::SanitizeThread:
698     return bitc::ATTR_KIND_SANITIZE_THREAD;
699   case Attribute::SanitizeMemory:
700     return bitc::ATTR_KIND_SANITIZE_MEMORY;
701   case Attribute::UWTable:
702     return bitc::ATTR_KIND_UW_TABLE;
703   case Attribute::ZExt:
704     return bitc::ATTR_KIND_Z_EXT;
705   case Attribute::EndAttrKinds:
706     llvm_unreachable("Can not encode end-attribute kinds marker.");
707   case Attribute::None:
708     llvm_unreachable("Can not encode none-attribute.");
709   case Attribute::EmptyKey:
710   case Attribute::TombstoneKey:
711     llvm_unreachable("Trying to encode EmptyKey/TombstoneKey");
712   default:
713     llvm_unreachable("Trying to encode attribute not supported by DXIL. These "
714                      "should be stripped in DXILPrepare");
715   }
716 
717   llvm_unreachable("Trying to encode unknown attribute");
718 }
719 
720 void DXILBitcodeWriter::emitSignedInt64(SmallVectorImpl<uint64_t> &Vals,
721                                         uint64_t V) {
722   if ((int64_t)V >= 0)
723     Vals.push_back(V << 1);
724   else
725     Vals.push_back((-V << 1) | 1);
726 }
727 
728 void DXILBitcodeWriter::emitWideAPInt(SmallVectorImpl<uint64_t> &Vals,
729                                       const APInt &A) {
730   // We have an arbitrary precision integer value to write whose
731   // bit width is > 64. However, in canonical unsigned integer
732   // format it is likely that the high bits are going to be zero.
733   // So, we only write the number of active words.
734   unsigned NumWords = A.getActiveWords();
735   const uint64_t *RawData = A.getRawData();
736   for (unsigned i = 0; i < NumWords; i++)
737     emitSignedInt64(Vals, RawData[i]);
738 }
739 
740 uint64_t DXILBitcodeWriter::getOptimizationFlags(const Value *V) {
741   uint64_t Flags = 0;
742 
743   if (const auto *OBO = dyn_cast<OverflowingBinaryOperator>(V)) {
744     if (OBO->hasNoSignedWrap())
745       Flags |= 1 << bitc::OBO_NO_SIGNED_WRAP;
746     if (OBO->hasNoUnsignedWrap())
747       Flags |= 1 << bitc::OBO_NO_UNSIGNED_WRAP;
748   } else if (const auto *PEO = dyn_cast<PossiblyExactOperator>(V)) {
749     if (PEO->isExact())
750       Flags |= 1 << bitc::PEO_EXACT;
751   } else if (const auto *FPMO = dyn_cast<FPMathOperator>(V)) {
752     if (FPMO->hasAllowReassoc() || FPMO->hasAllowContract())
753       Flags |= bitc::UnsafeAlgebra;
754     if (FPMO->hasNoNaNs())
755       Flags |= bitc::NoNaNs;
756     if (FPMO->hasNoInfs())
757       Flags |= bitc::NoInfs;
758     if (FPMO->hasNoSignedZeros())
759       Flags |= bitc::NoSignedZeros;
760     if (FPMO->hasAllowReciprocal())
761       Flags |= bitc::AllowReciprocal;
762   }
763 
764   return Flags;
765 }
766 
767 unsigned
768 DXILBitcodeWriter::getEncodedLinkage(const GlobalValue::LinkageTypes Linkage) {
769   switch (Linkage) {
770   case GlobalValue::ExternalLinkage:
771     return 0;
772   case GlobalValue::WeakAnyLinkage:
773     return 16;
774   case GlobalValue::AppendingLinkage:
775     return 2;
776   case GlobalValue::InternalLinkage:
777     return 3;
778   case GlobalValue::LinkOnceAnyLinkage:
779     return 18;
780   case GlobalValue::ExternalWeakLinkage:
781     return 7;
782   case GlobalValue::CommonLinkage:
783     return 8;
784   case GlobalValue::PrivateLinkage:
785     return 9;
786   case GlobalValue::WeakODRLinkage:
787     return 17;
788   case GlobalValue::LinkOnceODRLinkage:
789     return 19;
790   case GlobalValue::AvailableExternallyLinkage:
791     return 12;
792   }
793   llvm_unreachable("Invalid linkage");
794 }
795 
796 unsigned DXILBitcodeWriter::getEncodedLinkage(const GlobalValue &GV) {
797   return getEncodedLinkage(GV.getLinkage());
798 }
799 
800 unsigned DXILBitcodeWriter::getEncodedVisibility(const GlobalValue &GV) {
801   switch (GV.getVisibility()) {
802   case GlobalValue::DefaultVisibility:
803     return 0;
804   case GlobalValue::HiddenVisibility:
805     return 1;
806   case GlobalValue::ProtectedVisibility:
807     return 2;
808   }
809   llvm_unreachable("Invalid visibility");
810 }
811 
812 unsigned DXILBitcodeWriter::getEncodedDLLStorageClass(const GlobalValue &GV) {
813   switch (GV.getDLLStorageClass()) {
814   case GlobalValue::DefaultStorageClass:
815     return 0;
816   case GlobalValue::DLLImportStorageClass:
817     return 1;
818   case GlobalValue::DLLExportStorageClass:
819     return 2;
820   }
821   llvm_unreachable("Invalid DLL storage class");
822 }
823 
824 unsigned DXILBitcodeWriter::getEncodedThreadLocalMode(const GlobalValue &GV) {
825   switch (GV.getThreadLocalMode()) {
826   case GlobalVariable::NotThreadLocal:
827     return 0;
828   case GlobalVariable::GeneralDynamicTLSModel:
829     return 1;
830   case GlobalVariable::LocalDynamicTLSModel:
831     return 2;
832   case GlobalVariable::InitialExecTLSModel:
833     return 3;
834   case GlobalVariable::LocalExecTLSModel:
835     return 4;
836   }
837   llvm_unreachable("Invalid TLS model");
838 }
839 
840 unsigned DXILBitcodeWriter::getEncodedComdatSelectionKind(const Comdat &C) {
841   switch (C.getSelectionKind()) {
842   case Comdat::Any:
843     return bitc::COMDAT_SELECTION_KIND_ANY;
844   case Comdat::ExactMatch:
845     return bitc::COMDAT_SELECTION_KIND_EXACT_MATCH;
846   case Comdat::Largest:
847     return bitc::COMDAT_SELECTION_KIND_LARGEST;
848   case Comdat::NoDeduplicate:
849     return bitc::COMDAT_SELECTION_KIND_NO_DUPLICATES;
850   case Comdat::SameSize:
851     return bitc::COMDAT_SELECTION_KIND_SAME_SIZE;
852   }
853   llvm_unreachable("Invalid selection kind");
854 }
855 
856 ////////////////////////////////////////////////////////////////////////////////
857 /// Begin DXILBitcodeWriter Implementation
858 ////////////////////////////////////////////////////////////////////////////////
859 
860 void DXILBitcodeWriter::writeAttributeGroupTable() {
861   const std::vector<ValueEnumerator::IndexAndAttrSet> &AttrGrps =
862       VE.getAttributeGroups();
863   if (AttrGrps.empty())
864     return;
865 
866   Stream.EnterSubblock(bitc::PARAMATTR_GROUP_BLOCK_ID, 3);
867 
868   SmallVector<uint64_t, 64> Record;
869   for (ValueEnumerator::IndexAndAttrSet Pair : AttrGrps) {
870     unsigned AttrListIndex = Pair.first;
871     AttributeSet AS = Pair.second;
872     Record.push_back(VE.getAttributeGroupID(Pair));
873     Record.push_back(AttrListIndex);
874 
875     for (Attribute Attr : AS) {
876       if (Attr.isEnumAttribute()) {
877         uint64_t Val = getAttrKindEncoding(Attr.getKindAsEnum());
878         assert(Val <= bitc::ATTR_KIND_ARGMEMONLY &&
879                "DXIL does not support attributes above ATTR_KIND_ARGMEMONLY");
880         Record.push_back(0);
881         Record.push_back(Val);
882       } else if (Attr.isIntAttribute()) {
883         if (Attr.getKindAsEnum() == Attribute::AttrKind::Memory) {
884           MemoryEffects ME = Attr.getMemoryEffects();
885           if (ME.doesNotAccessMemory()) {
886             Record.push_back(0);
887             Record.push_back(bitc::ATTR_KIND_READ_NONE);
888           } else {
889             if (ME.onlyReadsMemory()) {
890               Record.push_back(0);
891               Record.push_back(bitc::ATTR_KIND_READ_ONLY);
892             }
893             if (ME.onlyAccessesArgPointees()) {
894               Record.push_back(0);
895               Record.push_back(bitc::ATTR_KIND_ARGMEMONLY);
896             }
897           }
898         } else {
899           uint64_t Val = getAttrKindEncoding(Attr.getKindAsEnum());
900           assert(Val <= bitc::ATTR_KIND_ARGMEMONLY &&
901                  "DXIL does not support attributes above ATTR_KIND_ARGMEMONLY");
902           Record.push_back(1);
903           Record.push_back(Val);
904           Record.push_back(Attr.getValueAsInt());
905         }
906       } else {
907         StringRef Kind = Attr.getKindAsString();
908         StringRef Val = Attr.getValueAsString();
909 
910         Record.push_back(Val.empty() ? 3 : 4);
911         Record.append(Kind.begin(), Kind.end());
912         Record.push_back(0);
913         if (!Val.empty()) {
914           Record.append(Val.begin(), Val.end());
915           Record.push_back(0);
916         }
917       }
918     }
919 
920     Stream.EmitRecord(bitc::PARAMATTR_GRP_CODE_ENTRY, Record);
921     Record.clear();
922   }
923 
924   Stream.ExitBlock();
925 }
926 
927 void DXILBitcodeWriter::writeAttributeTable() {
928   const std::vector<AttributeList> &Attrs = VE.getAttributeLists();
929   if (Attrs.empty())
930     return;
931 
932   Stream.EnterSubblock(bitc::PARAMATTR_BLOCK_ID, 3);
933 
934   SmallVector<uint64_t, 64> Record;
935   for (AttributeList AL : Attrs) {
936     for (unsigned i : AL.indexes()) {
937       AttributeSet AS = AL.getAttributes(i);
938       if (AS.hasAttributes())
939         Record.push_back(VE.getAttributeGroupID({i, AS}));
940     }
941 
942     Stream.EmitRecord(bitc::PARAMATTR_CODE_ENTRY, Record);
943     Record.clear();
944   }
945 
946   Stream.ExitBlock();
947 }
948 
949 /// WriteTypeTable - Write out the type table for a module.
950 void DXILBitcodeWriter::writeTypeTable() {
951   const ValueEnumerator::TypeList &TypeList = VE.getTypes();
952 
953   Stream.EnterSubblock(bitc::TYPE_BLOCK_ID_NEW, 4 /*count from # abbrevs */);
954   SmallVector<uint64_t, 64> TypeVals;
955 
956   uint64_t NumBits = VE.computeBitsRequiredForTypeIndices();
957 
958   // Abbrev for TYPE_CODE_POINTER.
959   auto Abbv = std::make_shared<BitCodeAbbrev>();
960   Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_POINTER));
961   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
962   Abbv->Add(BitCodeAbbrevOp(0)); // Addrspace = 0
963   unsigned PtrAbbrev = Stream.EmitAbbrev(std::move(Abbv));
964 
965   // Abbrev for TYPE_CODE_FUNCTION.
966   Abbv = std::make_shared<BitCodeAbbrev>();
967   Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_FUNCTION));
968   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // isvararg
969   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
970   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
971   unsigned FunctionAbbrev = Stream.EmitAbbrev(std::move(Abbv));
972 
973   // Abbrev for TYPE_CODE_STRUCT_ANON.
974   Abbv = std::make_shared<BitCodeAbbrev>();
975   Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_STRUCT_ANON));
976   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // ispacked
977   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
978   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
979   unsigned StructAnonAbbrev = Stream.EmitAbbrev(std::move(Abbv));
980 
981   // Abbrev for TYPE_CODE_STRUCT_NAME.
982   Abbv = std::make_shared<BitCodeAbbrev>();
983   Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_STRUCT_NAME));
984   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
985   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
986   unsigned StructNameAbbrev = Stream.EmitAbbrev(std::move(Abbv));
987 
988   // Abbrev for TYPE_CODE_STRUCT_NAMED.
989   Abbv = std::make_shared<BitCodeAbbrev>();
990   Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_STRUCT_NAMED));
991   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // ispacked
992   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
993   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
994   unsigned StructNamedAbbrev = Stream.EmitAbbrev(std::move(Abbv));
995 
996   // Abbrev for TYPE_CODE_ARRAY.
997   Abbv = std::make_shared<BitCodeAbbrev>();
998   Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_ARRAY));
999   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // size
1000   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
1001   unsigned ArrayAbbrev = Stream.EmitAbbrev(std::move(Abbv));
1002 
1003   // Emit an entry count so the reader can reserve space.
1004   TypeVals.push_back(TypeList.size());
1005   Stream.EmitRecord(bitc::TYPE_CODE_NUMENTRY, TypeVals);
1006   TypeVals.clear();
1007 
1008   // Loop over all of the types, emitting each in turn.
1009   for (Type *T : TypeList) {
1010     int AbbrevToUse = 0;
1011     unsigned Code = 0;
1012 
1013     switch (T->getTypeID()) {
1014     case Type::BFloatTyID:
1015     case Type::X86_AMXTyID:
1016     case Type::TokenTyID:
1017     case Type::TargetExtTyID:
1018       llvm_unreachable("These should never be used!!!");
1019       break;
1020     case Type::VoidTyID:
1021       Code = bitc::TYPE_CODE_VOID;
1022       break;
1023     case Type::HalfTyID:
1024       Code = bitc::TYPE_CODE_HALF;
1025       break;
1026     case Type::FloatTyID:
1027       Code = bitc::TYPE_CODE_FLOAT;
1028       break;
1029     case Type::DoubleTyID:
1030       Code = bitc::TYPE_CODE_DOUBLE;
1031       break;
1032     case Type::X86_FP80TyID:
1033       Code = bitc::TYPE_CODE_X86_FP80;
1034       break;
1035     case Type::FP128TyID:
1036       Code = bitc::TYPE_CODE_FP128;
1037       break;
1038     case Type::PPC_FP128TyID:
1039       Code = bitc::TYPE_CODE_PPC_FP128;
1040       break;
1041     case Type::LabelTyID:
1042       Code = bitc::TYPE_CODE_LABEL;
1043       break;
1044     case Type::MetadataTyID:
1045       Code = bitc::TYPE_CODE_METADATA;
1046       break;
1047     case Type::IntegerTyID:
1048       // INTEGER: [width]
1049       Code = bitc::TYPE_CODE_INTEGER;
1050       TypeVals.push_back(cast<IntegerType>(T)->getBitWidth());
1051       break;
1052     case Type::TypedPointerTyID: {
1053       TypedPointerType *PTy = cast<TypedPointerType>(T);
1054       // POINTER: [pointee type, address space]
1055       Code = bitc::TYPE_CODE_POINTER;
1056       TypeVals.push_back(getTypeID(PTy->getElementType()));
1057       unsigned AddressSpace = PTy->getAddressSpace();
1058       TypeVals.push_back(AddressSpace);
1059       if (AddressSpace == 0)
1060         AbbrevToUse = PtrAbbrev;
1061       break;
1062     }
1063     case Type::PointerTyID: {
1064       // POINTER: [pointee type, address space]
1065       // Emitting an empty struct type for the pointer's type allows this to be
1066       // order-independent. Non-struct types must be emitted in bitcode before
1067       // they can be referenced.
1068       TypeVals.push_back(false);
1069       Code = bitc::TYPE_CODE_OPAQUE;
1070       writeStringRecord(Stream, bitc::TYPE_CODE_STRUCT_NAME,
1071                         "dxilOpaquePtrReservedName", StructNameAbbrev);
1072       break;
1073     }
1074     case Type::FunctionTyID: {
1075       FunctionType *FT = cast<FunctionType>(T);
1076       // FUNCTION: [isvararg, retty, paramty x N]
1077       Code = bitc::TYPE_CODE_FUNCTION;
1078       TypeVals.push_back(FT->isVarArg());
1079       TypeVals.push_back(getTypeID(FT->getReturnType()));
1080       for (Type *PTy : FT->params())
1081         TypeVals.push_back(getTypeID(PTy));
1082       AbbrevToUse = FunctionAbbrev;
1083       break;
1084     }
1085     case Type::StructTyID: {
1086       StructType *ST = cast<StructType>(T);
1087       // STRUCT: [ispacked, eltty x N]
1088       TypeVals.push_back(ST->isPacked());
1089       // Output all of the element types.
1090       for (Type *ElTy : ST->elements())
1091         TypeVals.push_back(getTypeID(ElTy));
1092 
1093       if (ST->isLiteral()) {
1094         Code = bitc::TYPE_CODE_STRUCT_ANON;
1095         AbbrevToUse = StructAnonAbbrev;
1096       } else {
1097         if (ST->isOpaque()) {
1098           Code = bitc::TYPE_CODE_OPAQUE;
1099         } else {
1100           Code = bitc::TYPE_CODE_STRUCT_NAMED;
1101           AbbrevToUse = StructNamedAbbrev;
1102         }
1103 
1104         // Emit the name if it is present.
1105         if (!ST->getName().empty())
1106           writeStringRecord(Stream, bitc::TYPE_CODE_STRUCT_NAME, ST->getName(),
1107                             StructNameAbbrev);
1108       }
1109       break;
1110     }
1111     case Type::ArrayTyID: {
1112       ArrayType *AT = cast<ArrayType>(T);
1113       // ARRAY: [numelts, eltty]
1114       Code = bitc::TYPE_CODE_ARRAY;
1115       TypeVals.push_back(AT->getNumElements());
1116       TypeVals.push_back(getTypeID(AT->getElementType()));
1117       AbbrevToUse = ArrayAbbrev;
1118       break;
1119     }
1120     case Type::FixedVectorTyID:
1121     case Type::ScalableVectorTyID: {
1122       VectorType *VT = cast<VectorType>(T);
1123       // VECTOR [numelts, eltty]
1124       Code = bitc::TYPE_CODE_VECTOR;
1125       TypeVals.push_back(VT->getElementCount().getKnownMinValue());
1126       TypeVals.push_back(getTypeID(VT->getElementType()));
1127       break;
1128     }
1129     }
1130 
1131     // Emit the finished record.
1132     Stream.EmitRecord(Code, TypeVals, AbbrevToUse);
1133     TypeVals.clear();
1134   }
1135 
1136   Stream.ExitBlock();
1137 }
1138 
1139 void DXILBitcodeWriter::writeComdats() {
1140   SmallVector<uint16_t, 64> Vals;
1141   for (const Comdat *C : VE.getComdats()) {
1142     // COMDAT: [selection_kind, name]
1143     Vals.push_back(getEncodedComdatSelectionKind(*C));
1144     size_t Size = C->getName().size();
1145     assert(isUInt<16>(Size));
1146     Vals.push_back(Size);
1147     for (char Chr : C->getName())
1148       Vals.push_back((unsigned char)Chr);
1149     Stream.EmitRecord(bitc::MODULE_CODE_COMDAT, Vals, /*AbbrevToUse=*/0);
1150     Vals.clear();
1151   }
1152 }
1153 
1154 void DXILBitcodeWriter::writeValueSymbolTableForwardDecl() {}
1155 
1156 /// Emit top-level description of module, including target triple, inline asm,
1157 /// descriptors for global variables, and function prototype info.
1158 /// Returns the bit offset to backpatch with the location of the real VST.
1159 void DXILBitcodeWriter::writeModuleInfo() {
1160   // Emit various pieces of data attached to a module.
1161   if (!M.getTargetTriple().empty())
1162     writeStringRecord(Stream, bitc::MODULE_CODE_TRIPLE, M.getTargetTriple(),
1163                       0 /*TODO*/);
1164   const std::string &DL = M.getDataLayoutStr();
1165   if (!DL.empty())
1166     writeStringRecord(Stream, bitc::MODULE_CODE_DATALAYOUT, DL, 0 /*TODO*/);
1167   if (!M.getModuleInlineAsm().empty())
1168     writeStringRecord(Stream, bitc::MODULE_CODE_ASM, M.getModuleInlineAsm(),
1169                       0 /*TODO*/);
1170 
1171   // Emit information about sections and GC, computing how many there are. Also
1172   // compute the maximum alignment value.
1173   std::map<std::string, unsigned> SectionMap;
1174   std::map<std::string, unsigned> GCMap;
1175   MaybeAlign MaxAlignment;
1176   unsigned MaxGlobalType = 0;
1177   const auto UpdateMaxAlignment = [&MaxAlignment](const MaybeAlign A) {
1178     if (A)
1179       MaxAlignment = !MaxAlignment ? *A : std::max(*MaxAlignment, *A);
1180   };
1181   for (const GlobalVariable &GV : M.globals()) {
1182     UpdateMaxAlignment(GV.getAlign());
1183     // Use getGlobalObjectValueTypeID to look up the enumerated type ID for
1184     // Global Variable types.
1185     MaxGlobalType = std::max(
1186         MaxGlobalType, getGlobalObjectValueTypeID(GV.getValueType(), &GV));
1187     if (GV.hasSection()) {
1188       // Give section names unique ID's.
1189       unsigned &Entry = SectionMap[std::string(GV.getSection())];
1190       if (!Entry) {
1191         writeStringRecord(Stream, bitc::MODULE_CODE_SECTIONNAME,
1192                           GV.getSection(), 0 /*TODO*/);
1193         Entry = SectionMap.size();
1194       }
1195     }
1196   }
1197   for (const Function &F : M) {
1198     UpdateMaxAlignment(F.getAlign());
1199     if (F.hasSection()) {
1200       // Give section names unique ID's.
1201       unsigned &Entry = SectionMap[std::string(F.getSection())];
1202       if (!Entry) {
1203         writeStringRecord(Stream, bitc::MODULE_CODE_SECTIONNAME, F.getSection(),
1204                           0 /*TODO*/);
1205         Entry = SectionMap.size();
1206       }
1207     }
1208     if (F.hasGC()) {
1209       // Same for GC names.
1210       unsigned &Entry = GCMap[F.getGC()];
1211       if (!Entry) {
1212         writeStringRecord(Stream, bitc::MODULE_CODE_GCNAME, F.getGC(),
1213                           0 /*TODO*/);
1214         Entry = GCMap.size();
1215       }
1216     }
1217   }
1218 
1219   // Emit abbrev for globals, now that we know # sections and max alignment.
1220   unsigned SimpleGVarAbbrev = 0;
1221   if (!M.global_empty()) {
1222     // Add an abbrev for common globals with no visibility or thread
1223     // localness.
1224     auto Abbv = std::make_shared<BitCodeAbbrev>();
1225     Abbv->Add(BitCodeAbbrevOp(bitc::MODULE_CODE_GLOBALVAR));
1226     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
1227                               Log2_32_Ceil(MaxGlobalType + 1)));
1228     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));   // AddrSpace << 2
1229                                                            //| explicitType << 1
1230                                                            //| constant
1231     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));   // Initializer.
1232     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 5)); // Linkage.
1233     if (!MaxAlignment)                                     // Alignment.
1234       Abbv->Add(BitCodeAbbrevOp(0));
1235     else {
1236       unsigned MaxEncAlignment = getEncodedAlign(MaxAlignment);
1237       Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
1238                                 Log2_32_Ceil(MaxEncAlignment + 1)));
1239     }
1240     if (SectionMap.empty()) // Section.
1241       Abbv->Add(BitCodeAbbrevOp(0));
1242     else
1243       Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
1244                                 Log2_32_Ceil(SectionMap.size() + 1)));
1245     // Don't bother emitting vis + thread local.
1246     SimpleGVarAbbrev = Stream.EmitAbbrev(std::move(Abbv));
1247   }
1248 
1249   // Emit the global variable information.
1250   SmallVector<unsigned, 64> Vals;
1251   for (const GlobalVariable &GV : M.globals()) {
1252     unsigned AbbrevToUse = 0;
1253 
1254     // GLOBALVAR: [type, isconst, initid,
1255     //             linkage, alignment, section, visibility, threadlocal,
1256     //             unnamed_addr, externally_initialized, dllstorageclass,
1257     //             comdat]
1258     Vals.push_back(getGlobalObjectValueTypeID(GV.getValueType(), &GV));
1259     Vals.push_back(
1260         GV.getType()->getAddressSpace() << 2 | 2 |
1261         (GV.isConstant() ? 1 : 0)); // HLSL Change - bitwise | was used with
1262                                     // unsigned int and bool
1263     Vals.push_back(
1264         GV.isDeclaration() ? 0 : (VE.getValueID(GV.getInitializer()) + 1));
1265     Vals.push_back(getEncodedLinkage(GV));
1266     Vals.push_back(getEncodedAlign(GV.getAlign()));
1267     Vals.push_back(GV.hasSection() ? SectionMap[std::string(GV.getSection())]
1268                                    : 0);
1269     if (GV.isThreadLocal() ||
1270         GV.getVisibility() != GlobalValue::DefaultVisibility ||
1271         GV.getUnnamedAddr() != GlobalValue::UnnamedAddr::None ||
1272         GV.isExternallyInitialized() ||
1273         GV.getDLLStorageClass() != GlobalValue::DefaultStorageClass ||
1274         GV.hasComdat()) {
1275       Vals.push_back(getEncodedVisibility(GV));
1276       Vals.push_back(getEncodedThreadLocalMode(GV));
1277       Vals.push_back(GV.getUnnamedAddr() != GlobalValue::UnnamedAddr::None);
1278       Vals.push_back(GV.isExternallyInitialized());
1279       Vals.push_back(getEncodedDLLStorageClass(GV));
1280       Vals.push_back(GV.hasComdat() ? VE.getComdatID(GV.getComdat()) : 0);
1281     } else {
1282       AbbrevToUse = SimpleGVarAbbrev;
1283     }
1284 
1285     Stream.EmitRecord(bitc::MODULE_CODE_GLOBALVAR, Vals, AbbrevToUse);
1286     Vals.clear();
1287   }
1288 
1289   // Emit the function proto information.
1290   for (const Function &F : M) {
1291     // FUNCTION:  [type, callingconv, isproto, linkage, paramattrs, alignment,
1292     //             section, visibility, gc, unnamed_addr, prologuedata,
1293     //             dllstorageclass, comdat, prefixdata, personalityfn]
1294     Vals.push_back(getGlobalObjectValueTypeID(F.getFunctionType(), &F));
1295     Vals.push_back(F.getCallingConv());
1296     Vals.push_back(F.isDeclaration());
1297     Vals.push_back(getEncodedLinkage(F));
1298     Vals.push_back(VE.getAttributeListID(F.getAttributes()));
1299     Vals.push_back(getEncodedAlign(F.getAlign()));
1300     Vals.push_back(F.hasSection() ? SectionMap[std::string(F.getSection())]
1301                                   : 0);
1302     Vals.push_back(getEncodedVisibility(F));
1303     Vals.push_back(F.hasGC() ? GCMap[F.getGC()] : 0);
1304     Vals.push_back(F.getUnnamedAddr() != GlobalValue::UnnamedAddr::None);
1305     Vals.push_back(
1306         F.hasPrologueData() ? (VE.getValueID(F.getPrologueData()) + 1) : 0);
1307     Vals.push_back(getEncodedDLLStorageClass(F));
1308     Vals.push_back(F.hasComdat() ? VE.getComdatID(F.getComdat()) : 0);
1309     Vals.push_back(F.hasPrefixData() ? (VE.getValueID(F.getPrefixData()) + 1)
1310                                      : 0);
1311     Vals.push_back(
1312         F.hasPersonalityFn() ? (VE.getValueID(F.getPersonalityFn()) + 1) : 0);
1313 
1314     unsigned AbbrevToUse = 0;
1315     Stream.EmitRecord(bitc::MODULE_CODE_FUNCTION, Vals, AbbrevToUse);
1316     Vals.clear();
1317   }
1318 
1319   // Emit the alias information.
1320   for (const GlobalAlias &A : M.aliases()) {
1321     // ALIAS: [alias type, aliasee val#, linkage, visibility]
1322     Vals.push_back(getTypeID(A.getValueType(), &A));
1323     Vals.push_back(VE.getValueID(A.getAliasee()));
1324     Vals.push_back(getEncodedLinkage(A));
1325     Vals.push_back(getEncodedVisibility(A));
1326     Vals.push_back(getEncodedDLLStorageClass(A));
1327     Vals.push_back(getEncodedThreadLocalMode(A));
1328     Vals.push_back(A.getUnnamedAddr() != GlobalValue::UnnamedAddr::None);
1329     unsigned AbbrevToUse = 0;
1330     Stream.EmitRecord(bitc::MODULE_CODE_ALIAS_OLD, Vals, AbbrevToUse);
1331     Vals.clear();
1332   }
1333 }
1334 
1335 void DXILBitcodeWriter::writeValueAsMetadata(
1336     const ValueAsMetadata *MD, SmallVectorImpl<uint64_t> &Record) {
1337   // Mimic an MDNode with a value as one operand.
1338   Value *V = MD->getValue();
1339   Type *Ty = V->getType();
1340   if (Function *F = dyn_cast<Function>(V))
1341     Ty = TypedPointerType::get(F->getFunctionType(), F->getAddressSpace());
1342   else if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V))
1343     Ty = TypedPointerType::get(GV->getValueType(), GV->getAddressSpace());
1344   Record.push_back(getTypeID(Ty, V));
1345   Record.push_back(VE.getValueID(V));
1346   Stream.EmitRecord(bitc::METADATA_VALUE, Record, 0);
1347   Record.clear();
1348 }
1349 
1350 void DXILBitcodeWriter::writeMDTuple(const MDTuple *N,
1351                                      SmallVectorImpl<uint64_t> &Record,
1352                                      unsigned Abbrev) {
1353   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
1354     Metadata *MD = N->getOperand(i);
1355     assert(!(MD && isa<LocalAsMetadata>(MD)) &&
1356            "Unexpected function-local metadata");
1357     Record.push_back(VE.getMetadataOrNullID(MD));
1358   }
1359   Stream.EmitRecord(N->isDistinct() ? bitc::METADATA_DISTINCT_NODE
1360                                     : bitc::METADATA_NODE,
1361                     Record, Abbrev);
1362   Record.clear();
1363 }
1364 
1365 void DXILBitcodeWriter::writeDILocation(const DILocation *N,
1366                                         SmallVectorImpl<uint64_t> &Record,
1367                                         unsigned &Abbrev) {
1368   if (!Abbrev)
1369     Abbrev = createDILocationAbbrev();
1370   Record.push_back(N->isDistinct());
1371   Record.push_back(N->getLine());
1372   Record.push_back(N->getColumn());
1373   Record.push_back(VE.getMetadataID(N->getScope()));
1374   Record.push_back(VE.getMetadataOrNullID(N->getInlinedAt()));
1375 
1376   Stream.EmitRecord(bitc::METADATA_LOCATION, Record, Abbrev);
1377   Record.clear();
1378 }
1379 
1380 static uint64_t rotateSign(APInt Val) {
1381   int64_t I = Val.getSExtValue();
1382   uint64_t U = I;
1383   return I < 0 ? ~(U << 1) : U << 1;
1384 }
1385 
1386 void DXILBitcodeWriter::writeDISubrange(const DISubrange *N,
1387                                         SmallVectorImpl<uint64_t> &Record,
1388                                         unsigned Abbrev) {
1389   Record.push_back(N->isDistinct());
1390 
1391   // TODO: Do we need to handle DIExpression here? What about cases where Count
1392   // isn't specified but UpperBound and such are?
1393   ConstantInt *Count = N->getCount().dyn_cast<ConstantInt *>();
1394   assert(Count && "Count is missing or not ConstantInt");
1395   Record.push_back(Count->getValue().getSExtValue());
1396 
1397   // TODO: Similarly, DIExpression is allowed here now
1398   DISubrange::BoundType LowerBound = N->getLowerBound();
1399   assert((LowerBound.isNull() || LowerBound.is<ConstantInt *>()) &&
1400          "Lower bound provided but not ConstantInt");
1401   Record.push_back(
1402       LowerBound ? rotateSign(LowerBound.get<ConstantInt *>()->getValue()) : 0);
1403 
1404   Stream.EmitRecord(bitc::METADATA_SUBRANGE, Record, Abbrev);
1405   Record.clear();
1406 }
1407 
1408 void DXILBitcodeWriter::writeDIEnumerator(const DIEnumerator *N,
1409                                           SmallVectorImpl<uint64_t> &Record,
1410                                           unsigned Abbrev) {
1411   Record.push_back(N->isDistinct());
1412   Record.push_back(rotateSign(N->getValue()));
1413   Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1414 
1415   Stream.EmitRecord(bitc::METADATA_ENUMERATOR, Record, Abbrev);
1416   Record.clear();
1417 }
1418 
1419 void DXILBitcodeWriter::writeDIBasicType(const DIBasicType *N,
1420                                          SmallVectorImpl<uint64_t> &Record,
1421                                          unsigned Abbrev) {
1422   Record.push_back(N->isDistinct());
1423   Record.push_back(N->getTag());
1424   Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1425   Record.push_back(N->getSizeInBits());
1426   Record.push_back(N->getAlignInBits());
1427   Record.push_back(N->getEncoding());
1428 
1429   Stream.EmitRecord(bitc::METADATA_BASIC_TYPE, Record, Abbrev);
1430   Record.clear();
1431 }
1432 
1433 void DXILBitcodeWriter::writeDIDerivedType(const DIDerivedType *N,
1434                                            SmallVectorImpl<uint64_t> &Record,
1435                                            unsigned Abbrev) {
1436   Record.push_back(N->isDistinct());
1437   Record.push_back(N->getTag());
1438   Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1439   Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1440   Record.push_back(N->getLine());
1441   Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1442   Record.push_back(VE.getMetadataOrNullID(N->getBaseType()));
1443   Record.push_back(N->getSizeInBits());
1444   Record.push_back(N->getAlignInBits());
1445   Record.push_back(N->getOffsetInBits());
1446   Record.push_back(N->getFlags());
1447   Record.push_back(VE.getMetadataOrNullID(N->getExtraData()));
1448 
1449   Stream.EmitRecord(bitc::METADATA_DERIVED_TYPE, Record, Abbrev);
1450   Record.clear();
1451 }
1452 
1453 void DXILBitcodeWriter::writeDICompositeType(const DICompositeType *N,
1454                                              SmallVectorImpl<uint64_t> &Record,
1455                                              unsigned Abbrev) {
1456   Record.push_back(N->isDistinct());
1457   Record.push_back(N->getTag());
1458   Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1459   Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1460   Record.push_back(N->getLine());
1461   Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1462   Record.push_back(VE.getMetadataOrNullID(N->getBaseType()));
1463   Record.push_back(N->getSizeInBits());
1464   Record.push_back(N->getAlignInBits());
1465   Record.push_back(N->getOffsetInBits());
1466   Record.push_back(N->getFlags());
1467   Record.push_back(VE.getMetadataOrNullID(N->getElements().get()));
1468   Record.push_back(N->getRuntimeLang());
1469   Record.push_back(VE.getMetadataOrNullID(N->getVTableHolder()));
1470   Record.push_back(VE.getMetadataOrNullID(N->getTemplateParams().get()));
1471   Record.push_back(VE.getMetadataOrNullID(N->getRawIdentifier()));
1472 
1473   Stream.EmitRecord(bitc::METADATA_COMPOSITE_TYPE, Record, Abbrev);
1474   Record.clear();
1475 }
1476 
1477 void DXILBitcodeWriter::writeDISubroutineType(const DISubroutineType *N,
1478                                               SmallVectorImpl<uint64_t> &Record,
1479                                               unsigned Abbrev) {
1480   Record.push_back(N->isDistinct());
1481   Record.push_back(N->getFlags());
1482   Record.push_back(VE.getMetadataOrNullID(N->getTypeArray().get()));
1483 
1484   Stream.EmitRecord(bitc::METADATA_SUBROUTINE_TYPE, Record, Abbrev);
1485   Record.clear();
1486 }
1487 
1488 void DXILBitcodeWriter::writeDIFile(const DIFile *N,
1489                                     SmallVectorImpl<uint64_t> &Record,
1490                                     unsigned Abbrev) {
1491   Record.push_back(N->isDistinct());
1492   Record.push_back(VE.getMetadataOrNullID(N->getRawFilename()));
1493   Record.push_back(VE.getMetadataOrNullID(N->getRawDirectory()));
1494 
1495   Stream.EmitRecord(bitc::METADATA_FILE, Record, Abbrev);
1496   Record.clear();
1497 }
1498 
1499 void DXILBitcodeWriter::writeDICompileUnit(const DICompileUnit *N,
1500                                            SmallVectorImpl<uint64_t> &Record,
1501                                            unsigned Abbrev) {
1502   Record.push_back(N->isDistinct());
1503   Record.push_back(N->getSourceLanguage());
1504   Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1505   Record.push_back(VE.getMetadataOrNullID(N->getRawProducer()));
1506   Record.push_back(N->isOptimized());
1507   Record.push_back(VE.getMetadataOrNullID(N->getRawFlags()));
1508   Record.push_back(N->getRuntimeVersion());
1509   Record.push_back(VE.getMetadataOrNullID(N->getRawSplitDebugFilename()));
1510   Record.push_back(N->getEmissionKind());
1511   Record.push_back(VE.getMetadataOrNullID(N->getEnumTypes().get()));
1512   Record.push_back(VE.getMetadataOrNullID(N->getRetainedTypes().get()));
1513   Record.push_back(/* subprograms */ 0);
1514   Record.push_back(VE.getMetadataOrNullID(N->getGlobalVariables().get()));
1515   Record.push_back(VE.getMetadataOrNullID(N->getImportedEntities().get()));
1516   Record.push_back(N->getDWOId());
1517 
1518   Stream.EmitRecord(bitc::METADATA_COMPILE_UNIT, Record, Abbrev);
1519   Record.clear();
1520 }
1521 
1522 void DXILBitcodeWriter::writeDISubprogram(const DISubprogram *N,
1523                                           SmallVectorImpl<uint64_t> &Record,
1524                                           unsigned Abbrev) {
1525   Record.push_back(N->isDistinct());
1526   Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1527   Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1528   Record.push_back(VE.getMetadataOrNullID(N->getRawLinkageName()));
1529   Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1530   Record.push_back(N->getLine());
1531   Record.push_back(VE.getMetadataOrNullID(N->getType()));
1532   Record.push_back(N->isLocalToUnit());
1533   Record.push_back(N->isDefinition());
1534   Record.push_back(N->getScopeLine());
1535   Record.push_back(VE.getMetadataOrNullID(N->getContainingType()));
1536   Record.push_back(N->getVirtuality());
1537   Record.push_back(N->getVirtualIndex());
1538   Record.push_back(N->getFlags());
1539   Record.push_back(N->isOptimized());
1540   Record.push_back(VE.getMetadataOrNullID(N->getRawUnit()));
1541   Record.push_back(VE.getMetadataOrNullID(N->getTemplateParams().get()));
1542   Record.push_back(VE.getMetadataOrNullID(N->getDeclaration()));
1543   Record.push_back(VE.getMetadataOrNullID(N->getRetainedNodes().get()));
1544 
1545   Stream.EmitRecord(bitc::METADATA_SUBPROGRAM, Record, Abbrev);
1546   Record.clear();
1547 }
1548 
1549 void DXILBitcodeWriter::writeDILexicalBlock(const DILexicalBlock *N,
1550                                             SmallVectorImpl<uint64_t> &Record,
1551                                             unsigned Abbrev) {
1552   Record.push_back(N->isDistinct());
1553   Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1554   Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1555   Record.push_back(N->getLine());
1556   Record.push_back(N->getColumn());
1557 
1558   Stream.EmitRecord(bitc::METADATA_LEXICAL_BLOCK, Record, Abbrev);
1559   Record.clear();
1560 }
1561 
1562 void DXILBitcodeWriter::writeDILexicalBlockFile(
1563     const DILexicalBlockFile *N, SmallVectorImpl<uint64_t> &Record,
1564     unsigned Abbrev) {
1565   Record.push_back(N->isDistinct());
1566   Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1567   Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1568   Record.push_back(N->getDiscriminator());
1569 
1570   Stream.EmitRecord(bitc::METADATA_LEXICAL_BLOCK_FILE, Record, Abbrev);
1571   Record.clear();
1572 }
1573 
1574 void DXILBitcodeWriter::writeDINamespace(const DINamespace *N,
1575                                          SmallVectorImpl<uint64_t> &Record,
1576                                          unsigned Abbrev) {
1577   Record.push_back(N->isDistinct());
1578   Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1579   Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1580   Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1581   Record.push_back(/* line number */ 0);
1582 
1583   Stream.EmitRecord(bitc::METADATA_NAMESPACE, Record, Abbrev);
1584   Record.clear();
1585 }
1586 
1587 void DXILBitcodeWriter::writeDIModule(const DIModule *N,
1588                                       SmallVectorImpl<uint64_t> &Record,
1589                                       unsigned Abbrev) {
1590   Record.push_back(N->isDistinct());
1591   for (auto &I : N->operands())
1592     Record.push_back(VE.getMetadataOrNullID(I));
1593 
1594   Stream.EmitRecord(bitc::METADATA_MODULE, Record, Abbrev);
1595   Record.clear();
1596 }
1597 
1598 void DXILBitcodeWriter::writeDITemplateTypeParameter(
1599     const DITemplateTypeParameter *N, SmallVectorImpl<uint64_t> &Record,
1600     unsigned Abbrev) {
1601   Record.push_back(N->isDistinct());
1602   Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1603   Record.push_back(VE.getMetadataOrNullID(N->getType()));
1604 
1605   Stream.EmitRecord(bitc::METADATA_TEMPLATE_TYPE, Record, Abbrev);
1606   Record.clear();
1607 }
1608 
1609 void DXILBitcodeWriter::writeDITemplateValueParameter(
1610     const DITemplateValueParameter *N, SmallVectorImpl<uint64_t> &Record,
1611     unsigned Abbrev) {
1612   Record.push_back(N->isDistinct());
1613   Record.push_back(N->getTag());
1614   Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1615   Record.push_back(VE.getMetadataOrNullID(N->getType()));
1616   Record.push_back(VE.getMetadataOrNullID(N->getValue()));
1617 
1618   Stream.EmitRecord(bitc::METADATA_TEMPLATE_VALUE, Record, Abbrev);
1619   Record.clear();
1620 }
1621 
1622 void DXILBitcodeWriter::writeDIGlobalVariable(const DIGlobalVariable *N,
1623                                               SmallVectorImpl<uint64_t> &Record,
1624                                               unsigned Abbrev) {
1625   Record.push_back(N->isDistinct());
1626   Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1627   Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1628   Record.push_back(VE.getMetadataOrNullID(N->getRawLinkageName()));
1629   Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1630   Record.push_back(N->getLine());
1631   Record.push_back(VE.getMetadataOrNullID(N->getType()));
1632   Record.push_back(N->isLocalToUnit());
1633   Record.push_back(N->isDefinition());
1634   Record.push_back(/* N->getRawVariable() */ 0);
1635   Record.push_back(VE.getMetadataOrNullID(N->getStaticDataMemberDeclaration()));
1636 
1637   Stream.EmitRecord(bitc::METADATA_GLOBAL_VAR, Record, Abbrev);
1638   Record.clear();
1639 }
1640 
1641 void DXILBitcodeWriter::writeDILocalVariable(const DILocalVariable *N,
1642                                              SmallVectorImpl<uint64_t> &Record,
1643                                              unsigned Abbrev) {
1644   Record.push_back(N->isDistinct());
1645   Record.push_back(N->getTag());
1646   Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1647   Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1648   Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1649   Record.push_back(N->getLine());
1650   Record.push_back(VE.getMetadataOrNullID(N->getType()));
1651   Record.push_back(N->getArg());
1652   Record.push_back(N->getFlags());
1653 
1654   Stream.EmitRecord(bitc::METADATA_LOCAL_VAR, Record, Abbrev);
1655   Record.clear();
1656 }
1657 
1658 void DXILBitcodeWriter::writeDIExpression(const DIExpression *N,
1659                                           SmallVectorImpl<uint64_t> &Record,
1660                                           unsigned Abbrev) {
1661   Record.reserve(N->getElements().size() + 1);
1662 
1663   Record.push_back(N->isDistinct());
1664   Record.append(N->elements_begin(), N->elements_end());
1665 
1666   Stream.EmitRecord(bitc::METADATA_EXPRESSION, Record, Abbrev);
1667   Record.clear();
1668 }
1669 
1670 void DXILBitcodeWriter::writeDIObjCProperty(const DIObjCProperty *N,
1671                                             SmallVectorImpl<uint64_t> &Record,
1672                                             unsigned Abbrev) {
1673   llvm_unreachable("DXIL does not support objc!!!");
1674 }
1675 
1676 void DXILBitcodeWriter::writeDIImportedEntity(const DIImportedEntity *N,
1677                                               SmallVectorImpl<uint64_t> &Record,
1678                                               unsigned Abbrev) {
1679   Record.push_back(N->isDistinct());
1680   Record.push_back(N->getTag());
1681   Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1682   Record.push_back(VE.getMetadataOrNullID(N->getEntity()));
1683   Record.push_back(N->getLine());
1684   Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1685 
1686   Stream.EmitRecord(bitc::METADATA_IMPORTED_ENTITY, Record, Abbrev);
1687   Record.clear();
1688 }
1689 
1690 unsigned DXILBitcodeWriter::createDILocationAbbrev() {
1691   // Abbrev for METADATA_LOCATION.
1692   //
1693   // Assume the column is usually under 128, and always output the inlined-at
1694   // location (it's never more expensive than building an array size 1).
1695   std::shared_ptr<BitCodeAbbrev> Abbv = std::make_shared<BitCodeAbbrev>();
1696   Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_LOCATION));
1697   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));
1698   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
1699   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
1700   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
1701   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
1702   return Stream.EmitAbbrev(std::move(Abbv));
1703 }
1704 
1705 unsigned DXILBitcodeWriter::createGenericDINodeAbbrev() {
1706   // Abbrev for METADATA_GENERIC_DEBUG.
1707   //
1708   // Assume the column is usually under 128, and always output the inlined-at
1709   // location (it's never more expensive than building an array size 1).
1710   std::shared_ptr<BitCodeAbbrev> Abbv = std::make_shared<BitCodeAbbrev>();
1711   Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_GENERIC_DEBUG));
1712   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));
1713   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
1714   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));
1715   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
1716   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1717   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
1718   return Stream.EmitAbbrev(std::move(Abbv));
1719 }
1720 
1721 void DXILBitcodeWriter::writeMetadataRecords(ArrayRef<const Metadata *> MDs,
1722                                              SmallVectorImpl<uint64_t> &Record,
1723                                              std::vector<unsigned> *MDAbbrevs,
1724                                              std::vector<uint64_t> *IndexPos) {
1725   if (MDs.empty())
1726     return;
1727 
1728     // Initialize MDNode abbreviations.
1729 #define HANDLE_MDNODE_LEAF(CLASS) unsigned CLASS##Abbrev = 0;
1730 #include "llvm/IR/Metadata.def"
1731 
1732   for (const Metadata *MD : MDs) {
1733     if (IndexPos)
1734       IndexPos->push_back(Stream.GetCurrentBitNo());
1735     if (const MDNode *N = dyn_cast<MDNode>(MD)) {
1736       assert(N->isResolved() && "Expected forward references to be resolved");
1737 
1738       switch (N->getMetadataID()) {
1739       default:
1740         llvm_unreachable("Invalid MDNode subclass");
1741 #define HANDLE_MDNODE_LEAF(CLASS)                                              \
1742   case Metadata::CLASS##Kind:                                                  \
1743     if (MDAbbrevs)                                                             \
1744       write##CLASS(cast<CLASS>(N), Record,                                     \
1745                    (*MDAbbrevs)[MetadataAbbrev::CLASS##AbbrevID]);             \
1746     else                                                                       \
1747       write##CLASS(cast<CLASS>(N), Record, CLASS##Abbrev);                     \
1748     continue;
1749 #include "llvm/IR/Metadata.def"
1750       }
1751     }
1752     writeValueAsMetadata(cast<ValueAsMetadata>(MD), Record);
1753   }
1754 }
1755 
1756 unsigned DXILBitcodeWriter::createMetadataStringsAbbrev() {
1757   auto Abbv = std::make_shared<BitCodeAbbrev>();
1758   Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_STRING_OLD));
1759   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1760   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
1761   return Stream.EmitAbbrev(std::move(Abbv));
1762 }
1763 
1764 void DXILBitcodeWriter::writeMetadataStrings(
1765     ArrayRef<const Metadata *> Strings, SmallVectorImpl<uint64_t> &Record) {
1766   if (Strings.empty())
1767     return;
1768 
1769   unsigned MDSAbbrev = createMetadataStringsAbbrev();
1770 
1771   for (const Metadata *MD : Strings) {
1772     const MDString *MDS = cast<MDString>(MD);
1773     // Code: [strchar x N]
1774     Record.append(MDS->bytes_begin(), MDS->bytes_end());
1775 
1776     // Emit the finished record.
1777     Stream.EmitRecord(bitc::METADATA_STRING_OLD, Record, MDSAbbrev);
1778     Record.clear();
1779   }
1780 }
1781 
1782 void DXILBitcodeWriter::writeModuleMetadata() {
1783   if (!VE.hasMDs() && M.named_metadata_empty())
1784     return;
1785 
1786   Stream.EnterSubblock(bitc::METADATA_BLOCK_ID, 5);
1787 
1788   // Emit all abbrevs upfront, so that the reader can jump in the middle of the
1789   // block and load any metadata.
1790   std::vector<unsigned> MDAbbrevs;
1791 
1792   MDAbbrevs.resize(MetadataAbbrev::LastPlusOne);
1793   MDAbbrevs[MetadataAbbrev::DILocationAbbrevID] = createDILocationAbbrev();
1794   MDAbbrevs[MetadataAbbrev::GenericDINodeAbbrevID] =
1795       createGenericDINodeAbbrev();
1796 
1797   unsigned NameAbbrev = 0;
1798   if (!M.named_metadata_empty()) {
1799     // Abbrev for METADATA_NAME.
1800     std::shared_ptr<BitCodeAbbrev> Abbv = std::make_shared<BitCodeAbbrev>();
1801     Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_NAME));
1802     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1803     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
1804     NameAbbrev = Stream.EmitAbbrev(std::move(Abbv));
1805   }
1806 
1807   SmallVector<uint64_t, 64> Record;
1808   writeMetadataStrings(VE.getMDStrings(), Record);
1809 
1810   std::vector<uint64_t> IndexPos;
1811   IndexPos.reserve(VE.getNonMDStrings().size());
1812   writeMetadataRecords(VE.getNonMDStrings(), Record, &MDAbbrevs, &IndexPos);
1813 
1814   // Write named metadata.
1815   for (const NamedMDNode &NMD : M.named_metadata()) {
1816     // Write name.
1817     StringRef Str = NMD.getName();
1818     Record.append(Str.bytes_begin(), Str.bytes_end());
1819     Stream.EmitRecord(bitc::METADATA_NAME, Record, NameAbbrev);
1820     Record.clear();
1821 
1822     // Write named metadata operands.
1823     for (const MDNode *N : NMD.operands())
1824       Record.push_back(VE.getMetadataID(N));
1825     Stream.EmitRecord(bitc::METADATA_NAMED_NODE, Record, 0);
1826     Record.clear();
1827   }
1828 
1829   Stream.ExitBlock();
1830 }
1831 
1832 void DXILBitcodeWriter::writeFunctionMetadata(const Function &F) {
1833   if (!VE.hasMDs())
1834     return;
1835 
1836   Stream.EnterSubblock(bitc::METADATA_BLOCK_ID, 4);
1837   SmallVector<uint64_t, 64> Record;
1838   writeMetadataStrings(VE.getMDStrings(), Record);
1839   writeMetadataRecords(VE.getNonMDStrings(), Record);
1840   Stream.ExitBlock();
1841 }
1842 
1843 void DXILBitcodeWriter::writeFunctionMetadataAttachment(const Function &F) {
1844   Stream.EnterSubblock(bitc::METADATA_ATTACHMENT_ID, 3);
1845 
1846   SmallVector<uint64_t, 64> Record;
1847 
1848   // Write metadata attachments
1849   // METADATA_ATTACHMENT - [m x [value, [n x [id, mdnode]]]
1850   SmallVector<std::pair<unsigned, MDNode *>, 4> MDs;
1851   F.getAllMetadata(MDs);
1852   if (!MDs.empty()) {
1853     for (const auto &I : MDs) {
1854       Record.push_back(I.first);
1855       Record.push_back(VE.getMetadataID(I.second));
1856     }
1857     Stream.EmitRecord(bitc::METADATA_ATTACHMENT, Record, 0);
1858     Record.clear();
1859   }
1860 
1861   for (const BasicBlock &BB : F)
1862     for (const Instruction &I : BB) {
1863       MDs.clear();
1864       I.getAllMetadataOtherThanDebugLoc(MDs);
1865 
1866       // If no metadata, ignore instruction.
1867       if (MDs.empty())
1868         continue;
1869 
1870       Record.push_back(VE.getInstructionID(&I));
1871 
1872       for (unsigned i = 0, e = MDs.size(); i != e; ++i) {
1873         Record.push_back(MDs[i].first);
1874         Record.push_back(VE.getMetadataID(MDs[i].second));
1875       }
1876       Stream.EmitRecord(bitc::METADATA_ATTACHMENT, Record, 0);
1877       Record.clear();
1878     }
1879 
1880   Stream.ExitBlock();
1881 }
1882 
1883 void DXILBitcodeWriter::writeModuleMetadataKinds() {
1884   SmallVector<uint64_t, 64> Record;
1885 
1886   // Write metadata kinds
1887   // METADATA_KIND - [n x [id, name]]
1888   SmallVector<StringRef, 8> Names;
1889   M.getMDKindNames(Names);
1890 
1891   if (Names.empty())
1892     return;
1893 
1894   Stream.EnterSubblock(bitc::METADATA_BLOCK_ID, 3);
1895 
1896   for (unsigned MDKindID = 0, e = Names.size(); MDKindID != e; ++MDKindID) {
1897     Record.push_back(MDKindID);
1898     StringRef KName = Names[MDKindID];
1899     Record.append(KName.begin(), KName.end());
1900 
1901     Stream.EmitRecord(bitc::METADATA_KIND, Record, 0);
1902     Record.clear();
1903   }
1904 
1905   Stream.ExitBlock();
1906 }
1907 
1908 void DXILBitcodeWriter::writeConstants(unsigned FirstVal, unsigned LastVal,
1909                                        bool isGlobal) {
1910   if (FirstVal == LastVal)
1911     return;
1912 
1913   Stream.EnterSubblock(bitc::CONSTANTS_BLOCK_ID, 4);
1914 
1915   unsigned AggregateAbbrev = 0;
1916   unsigned String8Abbrev = 0;
1917   unsigned CString7Abbrev = 0;
1918   unsigned CString6Abbrev = 0;
1919   // If this is a constant pool for the module, emit module-specific abbrevs.
1920   if (isGlobal) {
1921     // Abbrev for CST_CODE_AGGREGATE.
1922     auto Abbv = std::make_shared<BitCodeAbbrev>();
1923     Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_AGGREGATE));
1924     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1925     Abbv->Add(
1926         BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, Log2_32_Ceil(LastVal + 1)));
1927     AggregateAbbrev = Stream.EmitAbbrev(std::move(Abbv));
1928 
1929     // Abbrev for CST_CODE_STRING.
1930     Abbv = std::make_shared<BitCodeAbbrev>();
1931     Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_STRING));
1932     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1933     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
1934     String8Abbrev = Stream.EmitAbbrev(std::move(Abbv));
1935     // Abbrev for CST_CODE_CSTRING.
1936     Abbv = std::make_shared<BitCodeAbbrev>();
1937     Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_CSTRING));
1938     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1939     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7));
1940     CString7Abbrev = Stream.EmitAbbrev(std::move(Abbv));
1941     // Abbrev for CST_CODE_CSTRING.
1942     Abbv = std::make_shared<BitCodeAbbrev>();
1943     Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_CSTRING));
1944     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1945     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
1946     CString6Abbrev = Stream.EmitAbbrev(std::move(Abbv));
1947   }
1948 
1949   SmallVector<uint64_t, 64> Record;
1950 
1951   const ValueEnumerator::ValueList &Vals = VE.getValues();
1952   Type *LastTy = nullptr;
1953   for (unsigned i = FirstVal; i != LastVal; ++i) {
1954     const Value *V = Vals[i].first;
1955     // If we need to switch types, do so now.
1956     if (V->getType() != LastTy) {
1957       LastTy = V->getType();
1958       Record.push_back(getTypeID(LastTy, V));
1959       Stream.EmitRecord(bitc::CST_CODE_SETTYPE, Record,
1960                         CONSTANTS_SETTYPE_ABBREV);
1961       Record.clear();
1962     }
1963 
1964     if (const InlineAsm *IA = dyn_cast<InlineAsm>(V)) {
1965       Record.push_back(unsigned(IA->hasSideEffects()) |
1966                        unsigned(IA->isAlignStack()) << 1 |
1967                        unsigned(IA->getDialect() & 1) << 2);
1968 
1969       // Add the asm string.
1970       const std::string &AsmStr = IA->getAsmString();
1971       Record.push_back(AsmStr.size());
1972       Record.append(AsmStr.begin(), AsmStr.end());
1973 
1974       // Add the constraint string.
1975       const std::string &ConstraintStr = IA->getConstraintString();
1976       Record.push_back(ConstraintStr.size());
1977       Record.append(ConstraintStr.begin(), ConstraintStr.end());
1978       Stream.EmitRecord(bitc::CST_CODE_INLINEASM, Record);
1979       Record.clear();
1980       continue;
1981     }
1982     const Constant *C = cast<Constant>(V);
1983     unsigned Code = -1U;
1984     unsigned AbbrevToUse = 0;
1985     if (C->isNullValue()) {
1986       Code = bitc::CST_CODE_NULL;
1987     } else if (isa<UndefValue>(C)) {
1988       Code = bitc::CST_CODE_UNDEF;
1989     } else if (const ConstantInt *IV = dyn_cast<ConstantInt>(C)) {
1990       if (IV->getBitWidth() <= 64) {
1991         uint64_t V = IV->getSExtValue();
1992         emitSignedInt64(Record, V);
1993         Code = bitc::CST_CODE_INTEGER;
1994         AbbrevToUse = CONSTANTS_INTEGER_ABBREV;
1995       } else { // Wide integers, > 64 bits in size.
1996         // We have an arbitrary precision integer value to write whose
1997         // bit width is > 64. However, in canonical unsigned integer
1998         // format it is likely that the high bits are going to be zero.
1999         // So, we only write the number of active words.
2000         unsigned NWords = IV->getValue().getActiveWords();
2001         const uint64_t *RawWords = IV->getValue().getRawData();
2002         for (unsigned i = 0; i != NWords; ++i) {
2003           emitSignedInt64(Record, RawWords[i]);
2004         }
2005         Code = bitc::CST_CODE_WIDE_INTEGER;
2006       }
2007     } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
2008       Code = bitc::CST_CODE_FLOAT;
2009       Type *Ty = CFP->getType();
2010       if (Ty->isHalfTy() || Ty->isFloatTy() || Ty->isDoubleTy()) {
2011         Record.push_back(CFP->getValueAPF().bitcastToAPInt().getZExtValue());
2012       } else if (Ty->isX86_FP80Ty()) {
2013         // api needed to prevent premature destruction
2014         // bits are not in the same order as a normal i80 APInt, compensate.
2015         APInt api = CFP->getValueAPF().bitcastToAPInt();
2016         const uint64_t *p = api.getRawData();
2017         Record.push_back((p[1] << 48) | (p[0] >> 16));
2018         Record.push_back(p[0] & 0xffffLL);
2019       } else if (Ty->isFP128Ty() || Ty->isPPC_FP128Ty()) {
2020         APInt api = CFP->getValueAPF().bitcastToAPInt();
2021         const uint64_t *p = api.getRawData();
2022         Record.push_back(p[0]);
2023         Record.push_back(p[1]);
2024       } else {
2025         assert(0 && "Unknown FP type!");
2026       }
2027     } else if (isa<ConstantDataSequential>(C) &&
2028                cast<ConstantDataSequential>(C)->isString()) {
2029       const ConstantDataSequential *Str = cast<ConstantDataSequential>(C);
2030       // Emit constant strings specially.
2031       unsigned NumElts = Str->getNumElements();
2032       // If this is a null-terminated string, use the denser CSTRING encoding.
2033       if (Str->isCString()) {
2034         Code = bitc::CST_CODE_CSTRING;
2035         --NumElts; // Don't encode the null, which isn't allowed by char6.
2036       } else {
2037         Code = bitc::CST_CODE_STRING;
2038         AbbrevToUse = String8Abbrev;
2039       }
2040       bool isCStr7 = Code == bitc::CST_CODE_CSTRING;
2041       bool isCStrChar6 = Code == bitc::CST_CODE_CSTRING;
2042       for (unsigned i = 0; i != NumElts; ++i) {
2043         unsigned char V = Str->getElementAsInteger(i);
2044         Record.push_back(V);
2045         isCStr7 &= (V & 128) == 0;
2046         if (isCStrChar6)
2047           isCStrChar6 = BitCodeAbbrevOp::isChar6(V);
2048       }
2049 
2050       if (isCStrChar6)
2051         AbbrevToUse = CString6Abbrev;
2052       else if (isCStr7)
2053         AbbrevToUse = CString7Abbrev;
2054     } else if (const ConstantDataSequential *CDS =
2055                    dyn_cast<ConstantDataSequential>(C)) {
2056       Code = bitc::CST_CODE_DATA;
2057       Type *EltTy = CDS->getElementType();
2058       if (isa<IntegerType>(EltTy)) {
2059         for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i)
2060           Record.push_back(CDS->getElementAsInteger(i));
2061       } else if (EltTy->isFloatTy()) {
2062         for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
2063           union {
2064             float F;
2065             uint32_t I;
2066           };
2067           F = CDS->getElementAsFloat(i);
2068           Record.push_back(I);
2069         }
2070       } else {
2071         assert(EltTy->isDoubleTy() && "Unknown ConstantData element type");
2072         for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
2073           union {
2074             double F;
2075             uint64_t I;
2076           };
2077           F = CDS->getElementAsDouble(i);
2078           Record.push_back(I);
2079         }
2080       }
2081     } else if (isa<ConstantArray>(C) || isa<ConstantStruct>(C) ||
2082                isa<ConstantVector>(C)) {
2083       Code = bitc::CST_CODE_AGGREGATE;
2084       for (const Value *Op : C->operands())
2085         Record.push_back(VE.getValueID(Op));
2086       AbbrevToUse = AggregateAbbrev;
2087     } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
2088       switch (CE->getOpcode()) {
2089       default:
2090         if (Instruction::isCast(CE->getOpcode())) {
2091           Code = bitc::CST_CODE_CE_CAST;
2092           Record.push_back(getEncodedCastOpcode(CE->getOpcode()));
2093           Record.push_back(
2094               getTypeID(C->getOperand(0)->getType(), C->getOperand(0)));
2095           Record.push_back(VE.getValueID(C->getOperand(0)));
2096           AbbrevToUse = CONSTANTS_CE_CAST_Abbrev;
2097         } else {
2098           assert(CE->getNumOperands() == 2 && "Unknown constant expr!");
2099           Code = bitc::CST_CODE_CE_BINOP;
2100           Record.push_back(getEncodedBinaryOpcode(CE->getOpcode()));
2101           Record.push_back(VE.getValueID(C->getOperand(0)));
2102           Record.push_back(VE.getValueID(C->getOperand(1)));
2103           uint64_t Flags = getOptimizationFlags(CE);
2104           if (Flags != 0)
2105             Record.push_back(Flags);
2106         }
2107         break;
2108       case Instruction::GetElementPtr: {
2109         Code = bitc::CST_CODE_CE_GEP;
2110         const auto *GO = cast<GEPOperator>(C);
2111         if (GO->isInBounds())
2112           Code = bitc::CST_CODE_CE_INBOUNDS_GEP;
2113         Record.push_back(getTypeID(GO->getSourceElementType()));
2114         for (unsigned i = 0, e = CE->getNumOperands(); i != e; ++i) {
2115           Record.push_back(
2116               getTypeID(C->getOperand(i)->getType(), C->getOperand(i)));
2117           Record.push_back(VE.getValueID(C->getOperand(i)));
2118         }
2119         break;
2120       }
2121       case Instruction::Select:
2122         Code = bitc::CST_CODE_CE_SELECT;
2123         Record.push_back(VE.getValueID(C->getOperand(0)));
2124         Record.push_back(VE.getValueID(C->getOperand(1)));
2125         Record.push_back(VE.getValueID(C->getOperand(2)));
2126         break;
2127       case Instruction::ExtractElement:
2128         Code = bitc::CST_CODE_CE_EXTRACTELT;
2129         Record.push_back(getTypeID(C->getOperand(0)->getType()));
2130         Record.push_back(VE.getValueID(C->getOperand(0)));
2131         Record.push_back(getTypeID(C->getOperand(1)->getType()));
2132         Record.push_back(VE.getValueID(C->getOperand(1)));
2133         break;
2134       case Instruction::InsertElement:
2135         Code = bitc::CST_CODE_CE_INSERTELT;
2136         Record.push_back(VE.getValueID(C->getOperand(0)));
2137         Record.push_back(VE.getValueID(C->getOperand(1)));
2138         Record.push_back(getTypeID(C->getOperand(2)->getType()));
2139         Record.push_back(VE.getValueID(C->getOperand(2)));
2140         break;
2141       case Instruction::ShuffleVector:
2142         // If the return type and argument types are the same, this is a
2143         // standard shufflevector instruction.  If the types are different,
2144         // then the shuffle is widening or truncating the input vectors, and
2145         // the argument type must also be encoded.
2146         if (C->getType() == C->getOperand(0)->getType()) {
2147           Code = bitc::CST_CODE_CE_SHUFFLEVEC;
2148         } else {
2149           Code = bitc::CST_CODE_CE_SHUFVEC_EX;
2150           Record.push_back(getTypeID(C->getOperand(0)->getType()));
2151         }
2152         Record.push_back(VE.getValueID(C->getOperand(0)));
2153         Record.push_back(VE.getValueID(C->getOperand(1)));
2154         Record.push_back(VE.getValueID(C->getOperand(2)));
2155         break;
2156       }
2157     } else if (const BlockAddress *BA = dyn_cast<BlockAddress>(C)) {
2158       Code = bitc::CST_CODE_BLOCKADDRESS;
2159       Record.push_back(getTypeID(BA->getFunction()->getType()));
2160       Record.push_back(VE.getValueID(BA->getFunction()));
2161       Record.push_back(VE.getGlobalBasicBlockID(BA->getBasicBlock()));
2162     } else {
2163 #ifndef NDEBUG
2164       C->dump();
2165 #endif
2166       llvm_unreachable("Unknown constant!");
2167     }
2168     Stream.EmitRecord(Code, Record, AbbrevToUse);
2169     Record.clear();
2170   }
2171 
2172   Stream.ExitBlock();
2173 }
2174 
2175 void DXILBitcodeWriter::writeModuleConstants() {
2176   const ValueEnumerator::ValueList &Vals = VE.getValues();
2177 
2178   // Find the first constant to emit, which is the first non-globalvalue value.
2179   // We know globalvalues have been emitted by WriteModuleInfo.
2180   for (unsigned i = 0, e = Vals.size(); i != e; ++i) {
2181     if (!isa<GlobalValue>(Vals[i].first)) {
2182       writeConstants(i, Vals.size(), true);
2183       return;
2184     }
2185   }
2186 }
2187 
2188 /// pushValueAndType - The file has to encode both the value and type id for
2189 /// many values, because we need to know what type to create for forward
2190 /// references.  However, most operands are not forward references, so this type
2191 /// field is not needed.
2192 ///
2193 /// This function adds V's value ID to Vals.  If the value ID is higher than the
2194 /// instruction ID, then it is a forward reference, and it also includes the
2195 /// type ID.  The value ID that is written is encoded relative to the InstID.
2196 bool DXILBitcodeWriter::pushValueAndType(const Value *V, unsigned InstID,
2197                                          SmallVectorImpl<unsigned> &Vals) {
2198   unsigned ValID = VE.getValueID(V);
2199   // Make encoding relative to the InstID.
2200   Vals.push_back(InstID - ValID);
2201   if (ValID >= InstID) {
2202     Vals.push_back(getTypeID(V->getType(), V));
2203     return true;
2204   }
2205   return false;
2206 }
2207 
2208 /// pushValue - Like pushValueAndType, but where the type of the value is
2209 /// omitted (perhaps it was already encoded in an earlier operand).
2210 void DXILBitcodeWriter::pushValue(const Value *V, unsigned InstID,
2211                                   SmallVectorImpl<unsigned> &Vals) {
2212   unsigned ValID = VE.getValueID(V);
2213   Vals.push_back(InstID - ValID);
2214 }
2215 
2216 void DXILBitcodeWriter::pushValueSigned(const Value *V, unsigned InstID,
2217                                         SmallVectorImpl<uint64_t> &Vals) {
2218   unsigned ValID = VE.getValueID(V);
2219   int64_t diff = ((int32_t)InstID - (int32_t)ValID);
2220   emitSignedInt64(Vals, diff);
2221 }
2222 
2223 /// WriteInstruction - Emit an instruction
2224 void DXILBitcodeWriter::writeInstruction(const Instruction &I, unsigned InstID,
2225                                          SmallVectorImpl<unsigned> &Vals) {
2226   unsigned Code = 0;
2227   unsigned AbbrevToUse = 0;
2228   VE.setInstructionID(&I);
2229   switch (I.getOpcode()) {
2230   default:
2231     if (Instruction::isCast(I.getOpcode())) {
2232       Code = bitc::FUNC_CODE_INST_CAST;
2233       if (!pushValueAndType(I.getOperand(0), InstID, Vals))
2234         AbbrevToUse = (unsigned)FUNCTION_INST_CAST_ABBREV;
2235       Vals.push_back(getTypeID(I.getType(), &I));
2236       Vals.push_back(getEncodedCastOpcode(I.getOpcode()));
2237     } else {
2238       assert(isa<BinaryOperator>(I) && "Unknown instruction!");
2239       Code = bitc::FUNC_CODE_INST_BINOP;
2240       if (!pushValueAndType(I.getOperand(0), InstID, Vals))
2241         AbbrevToUse = (unsigned)FUNCTION_INST_BINOP_ABBREV;
2242       pushValue(I.getOperand(1), InstID, Vals);
2243       Vals.push_back(getEncodedBinaryOpcode(I.getOpcode()));
2244       uint64_t Flags = getOptimizationFlags(&I);
2245       if (Flags != 0) {
2246         if (AbbrevToUse == (unsigned)FUNCTION_INST_BINOP_ABBREV)
2247           AbbrevToUse = (unsigned)FUNCTION_INST_BINOP_FLAGS_ABBREV;
2248         Vals.push_back(Flags);
2249       }
2250     }
2251     break;
2252 
2253   case Instruction::GetElementPtr: {
2254     Code = bitc::FUNC_CODE_INST_GEP;
2255     AbbrevToUse = (unsigned)FUNCTION_INST_GEP_ABBREV;
2256     auto &GEPInst = cast<GetElementPtrInst>(I);
2257     Vals.push_back(GEPInst.isInBounds());
2258     Vals.push_back(getTypeID(GEPInst.getSourceElementType()));
2259     for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
2260       pushValueAndType(I.getOperand(i), InstID, Vals);
2261     break;
2262   }
2263   case Instruction::ExtractValue: {
2264     Code = bitc::FUNC_CODE_INST_EXTRACTVAL;
2265     pushValueAndType(I.getOperand(0), InstID, Vals);
2266     const ExtractValueInst *EVI = cast<ExtractValueInst>(&I);
2267     Vals.append(EVI->idx_begin(), EVI->idx_end());
2268     break;
2269   }
2270   case Instruction::InsertValue: {
2271     Code = bitc::FUNC_CODE_INST_INSERTVAL;
2272     pushValueAndType(I.getOperand(0), InstID, Vals);
2273     pushValueAndType(I.getOperand(1), InstID, Vals);
2274     const InsertValueInst *IVI = cast<InsertValueInst>(&I);
2275     Vals.append(IVI->idx_begin(), IVI->idx_end());
2276     break;
2277   }
2278   case Instruction::Select:
2279     Code = bitc::FUNC_CODE_INST_VSELECT;
2280     pushValueAndType(I.getOperand(1), InstID, Vals);
2281     pushValue(I.getOperand(2), InstID, Vals);
2282     pushValueAndType(I.getOperand(0), InstID, Vals);
2283     break;
2284   case Instruction::ExtractElement:
2285     Code = bitc::FUNC_CODE_INST_EXTRACTELT;
2286     pushValueAndType(I.getOperand(0), InstID, Vals);
2287     pushValueAndType(I.getOperand(1), InstID, Vals);
2288     break;
2289   case Instruction::InsertElement:
2290     Code = bitc::FUNC_CODE_INST_INSERTELT;
2291     pushValueAndType(I.getOperand(0), InstID, Vals);
2292     pushValue(I.getOperand(1), InstID, Vals);
2293     pushValueAndType(I.getOperand(2), InstID, Vals);
2294     break;
2295   case Instruction::ShuffleVector:
2296     Code = bitc::FUNC_CODE_INST_SHUFFLEVEC;
2297     pushValueAndType(I.getOperand(0), InstID, Vals);
2298     pushValue(I.getOperand(1), InstID, Vals);
2299     pushValue(cast<ShuffleVectorInst>(&I)->getShuffleMaskForBitcode(), InstID,
2300               Vals);
2301     break;
2302   case Instruction::ICmp:
2303   case Instruction::FCmp: {
2304     // compare returning Int1Ty or vector of Int1Ty
2305     Code = bitc::FUNC_CODE_INST_CMP2;
2306     pushValueAndType(I.getOperand(0), InstID, Vals);
2307     pushValue(I.getOperand(1), InstID, Vals);
2308     Vals.push_back(cast<CmpInst>(I).getPredicate());
2309     uint64_t Flags = getOptimizationFlags(&I);
2310     if (Flags != 0)
2311       Vals.push_back(Flags);
2312     break;
2313   }
2314 
2315   case Instruction::Ret: {
2316     Code = bitc::FUNC_CODE_INST_RET;
2317     unsigned NumOperands = I.getNumOperands();
2318     if (NumOperands == 0)
2319       AbbrevToUse = (unsigned)FUNCTION_INST_RET_VOID_ABBREV;
2320     else if (NumOperands == 1) {
2321       if (!pushValueAndType(I.getOperand(0), InstID, Vals))
2322         AbbrevToUse = (unsigned)FUNCTION_INST_RET_VAL_ABBREV;
2323     } else {
2324       for (unsigned i = 0, e = NumOperands; i != e; ++i)
2325         pushValueAndType(I.getOperand(i), InstID, Vals);
2326     }
2327   } break;
2328   case Instruction::Br: {
2329     Code = bitc::FUNC_CODE_INST_BR;
2330     const BranchInst &II = cast<BranchInst>(I);
2331     Vals.push_back(VE.getValueID(II.getSuccessor(0)));
2332     if (II.isConditional()) {
2333       Vals.push_back(VE.getValueID(II.getSuccessor(1)));
2334       pushValue(II.getCondition(), InstID, Vals);
2335     }
2336   } break;
2337   case Instruction::Switch: {
2338     Code = bitc::FUNC_CODE_INST_SWITCH;
2339     const SwitchInst &SI = cast<SwitchInst>(I);
2340     Vals.push_back(getTypeID(SI.getCondition()->getType()));
2341     pushValue(SI.getCondition(), InstID, Vals);
2342     Vals.push_back(VE.getValueID(SI.getDefaultDest()));
2343     for (auto Case : SI.cases()) {
2344       Vals.push_back(VE.getValueID(Case.getCaseValue()));
2345       Vals.push_back(VE.getValueID(Case.getCaseSuccessor()));
2346     }
2347   } break;
2348   case Instruction::IndirectBr:
2349     Code = bitc::FUNC_CODE_INST_INDIRECTBR;
2350     Vals.push_back(getTypeID(I.getOperand(0)->getType()));
2351     // Encode the address operand as relative, but not the basic blocks.
2352     pushValue(I.getOperand(0), InstID, Vals);
2353     for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i)
2354       Vals.push_back(VE.getValueID(I.getOperand(i)));
2355     break;
2356 
2357   case Instruction::Invoke: {
2358     const InvokeInst *II = cast<InvokeInst>(&I);
2359     const Value *Callee = II->getCalledOperand();
2360     FunctionType *FTy = II->getFunctionType();
2361     Code = bitc::FUNC_CODE_INST_INVOKE;
2362 
2363     Vals.push_back(VE.getAttributeListID(II->getAttributes()));
2364     Vals.push_back(II->getCallingConv() | 1 << 13);
2365     Vals.push_back(VE.getValueID(II->getNormalDest()));
2366     Vals.push_back(VE.getValueID(II->getUnwindDest()));
2367     Vals.push_back(getTypeID(FTy));
2368     pushValueAndType(Callee, InstID, Vals);
2369 
2370     // Emit value #'s for the fixed parameters.
2371     for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
2372       pushValue(I.getOperand(i), InstID, Vals); // fixed param.
2373 
2374     // Emit type/value pairs for varargs params.
2375     if (FTy->isVarArg()) {
2376       for (unsigned i = FTy->getNumParams(), e = I.getNumOperands() - 3; i != e;
2377            ++i)
2378         pushValueAndType(I.getOperand(i), InstID, Vals); // vararg
2379     }
2380     break;
2381   }
2382   case Instruction::Resume:
2383     Code = bitc::FUNC_CODE_INST_RESUME;
2384     pushValueAndType(I.getOperand(0), InstID, Vals);
2385     break;
2386   case Instruction::Unreachable:
2387     Code = bitc::FUNC_CODE_INST_UNREACHABLE;
2388     AbbrevToUse = (unsigned)FUNCTION_INST_UNREACHABLE_ABBREV;
2389     break;
2390 
2391   case Instruction::PHI: {
2392     const PHINode &PN = cast<PHINode>(I);
2393     Code = bitc::FUNC_CODE_INST_PHI;
2394     // With the newer instruction encoding, forward references could give
2395     // negative valued IDs.  This is most common for PHIs, so we use
2396     // signed VBRs.
2397     SmallVector<uint64_t, 128> Vals64;
2398     Vals64.push_back(getTypeID(PN.getType()));
2399     for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
2400       pushValueSigned(PN.getIncomingValue(i), InstID, Vals64);
2401       Vals64.push_back(VE.getValueID(PN.getIncomingBlock(i)));
2402     }
2403     // Emit a Vals64 vector and exit.
2404     Stream.EmitRecord(Code, Vals64, AbbrevToUse);
2405     Vals64.clear();
2406     return;
2407   }
2408 
2409   case Instruction::LandingPad: {
2410     const LandingPadInst &LP = cast<LandingPadInst>(I);
2411     Code = bitc::FUNC_CODE_INST_LANDINGPAD;
2412     Vals.push_back(getTypeID(LP.getType()));
2413     Vals.push_back(LP.isCleanup());
2414     Vals.push_back(LP.getNumClauses());
2415     for (unsigned I = 0, E = LP.getNumClauses(); I != E; ++I) {
2416       if (LP.isCatch(I))
2417         Vals.push_back(LandingPadInst::Catch);
2418       else
2419         Vals.push_back(LandingPadInst::Filter);
2420       pushValueAndType(LP.getClause(I), InstID, Vals);
2421     }
2422     break;
2423   }
2424 
2425   case Instruction::Alloca: {
2426     Code = bitc::FUNC_CODE_INST_ALLOCA;
2427     const AllocaInst &AI = cast<AllocaInst>(I);
2428     Vals.push_back(getTypeID(AI.getAllocatedType()));
2429     Vals.push_back(getTypeID(I.getOperand(0)->getType()));
2430     Vals.push_back(VE.getValueID(I.getOperand(0))); // size.
2431     unsigned AlignRecord = Log2_32(AI.getAlign().value()) + 1;
2432     assert(AlignRecord < 1 << 5 && "alignment greater than 1 << 64");
2433     AlignRecord |= AI.isUsedWithInAlloca() << 5;
2434     AlignRecord |= 1 << 6;
2435     Vals.push_back(AlignRecord);
2436     break;
2437   }
2438 
2439   case Instruction::Load:
2440     if (cast<LoadInst>(I).isAtomic()) {
2441       Code = bitc::FUNC_CODE_INST_LOADATOMIC;
2442       pushValueAndType(I.getOperand(0), InstID, Vals);
2443     } else {
2444       Code = bitc::FUNC_CODE_INST_LOAD;
2445       if (!pushValueAndType(I.getOperand(0), InstID, Vals)) // ptr
2446         AbbrevToUse = (unsigned)FUNCTION_INST_LOAD_ABBREV;
2447     }
2448     Vals.push_back(getTypeID(I.getType()));
2449     Vals.push_back(Log2(cast<LoadInst>(I).getAlign()) + 1);
2450     Vals.push_back(cast<LoadInst>(I).isVolatile());
2451     if (cast<LoadInst>(I).isAtomic()) {
2452       Vals.push_back(getEncodedOrdering(cast<LoadInst>(I).getOrdering()));
2453       Vals.push_back(getEncodedSyncScopeID(cast<LoadInst>(I).getSyncScopeID()));
2454     }
2455     break;
2456   case Instruction::Store:
2457     if (cast<StoreInst>(I).isAtomic())
2458       Code = bitc::FUNC_CODE_INST_STOREATOMIC;
2459     else
2460       Code = bitc::FUNC_CODE_INST_STORE;
2461     pushValueAndType(I.getOperand(1), InstID, Vals); // ptrty + ptr
2462     pushValueAndType(I.getOperand(0), InstID, Vals); // valty + val
2463     Vals.push_back(Log2(cast<StoreInst>(I).getAlign()) + 1);
2464     Vals.push_back(cast<StoreInst>(I).isVolatile());
2465     if (cast<StoreInst>(I).isAtomic()) {
2466       Vals.push_back(getEncodedOrdering(cast<StoreInst>(I).getOrdering()));
2467       Vals.push_back(
2468           getEncodedSyncScopeID(cast<StoreInst>(I).getSyncScopeID()));
2469     }
2470     break;
2471   case Instruction::AtomicCmpXchg:
2472     Code = bitc::FUNC_CODE_INST_CMPXCHG;
2473     pushValueAndType(I.getOperand(0), InstID, Vals); // ptrty + ptr
2474     pushValueAndType(I.getOperand(1), InstID, Vals); // cmp.
2475     pushValue(I.getOperand(2), InstID, Vals);        // newval.
2476     Vals.push_back(cast<AtomicCmpXchgInst>(I).isVolatile());
2477     Vals.push_back(
2478         getEncodedOrdering(cast<AtomicCmpXchgInst>(I).getSuccessOrdering()));
2479     Vals.push_back(
2480         getEncodedSyncScopeID(cast<AtomicCmpXchgInst>(I).getSyncScopeID()));
2481     Vals.push_back(
2482         getEncodedOrdering(cast<AtomicCmpXchgInst>(I).getFailureOrdering()));
2483     Vals.push_back(cast<AtomicCmpXchgInst>(I).isWeak());
2484     break;
2485   case Instruction::AtomicRMW:
2486     Code = bitc::FUNC_CODE_INST_ATOMICRMW;
2487     pushValueAndType(I.getOperand(0), InstID, Vals); // ptrty + ptr
2488     pushValue(I.getOperand(1), InstID, Vals);        // val.
2489     Vals.push_back(
2490         getEncodedRMWOperation(cast<AtomicRMWInst>(I).getOperation()));
2491     Vals.push_back(cast<AtomicRMWInst>(I).isVolatile());
2492     Vals.push_back(getEncodedOrdering(cast<AtomicRMWInst>(I).getOrdering()));
2493     Vals.push_back(
2494         getEncodedSyncScopeID(cast<AtomicRMWInst>(I).getSyncScopeID()));
2495     break;
2496   case Instruction::Fence:
2497     Code = bitc::FUNC_CODE_INST_FENCE;
2498     Vals.push_back(getEncodedOrdering(cast<FenceInst>(I).getOrdering()));
2499     Vals.push_back(getEncodedSyncScopeID(cast<FenceInst>(I).getSyncScopeID()));
2500     break;
2501   case Instruction::Call: {
2502     const CallInst &CI = cast<CallInst>(I);
2503     FunctionType *FTy = CI.getFunctionType();
2504 
2505     Code = bitc::FUNC_CODE_INST_CALL;
2506 
2507     Vals.push_back(VE.getAttributeListID(CI.getAttributes()));
2508     Vals.push_back((CI.getCallingConv() << 1) | unsigned(CI.isTailCall()) |
2509                    unsigned(CI.isMustTailCall()) << 14 | 1 << 15);
2510     Vals.push_back(getGlobalObjectValueTypeID(FTy, CI.getCalledFunction()));
2511     pushValueAndType(CI.getCalledOperand(), InstID, Vals); // Callee
2512 
2513     // Emit value #'s for the fixed parameters.
2514     for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i) {
2515       // Check for labels (can happen with asm labels).
2516       if (FTy->getParamType(i)->isLabelTy())
2517         Vals.push_back(VE.getValueID(CI.getArgOperand(i)));
2518       else
2519         pushValue(CI.getArgOperand(i), InstID, Vals); // fixed param.
2520     }
2521 
2522     // Emit type/value pairs for varargs params.
2523     if (FTy->isVarArg()) {
2524       for (unsigned i = FTy->getNumParams(), e = CI.arg_size(); i != e; ++i)
2525         pushValueAndType(CI.getArgOperand(i), InstID, Vals); // varargs
2526     }
2527     break;
2528   }
2529   case Instruction::VAArg:
2530     Code = bitc::FUNC_CODE_INST_VAARG;
2531     Vals.push_back(getTypeID(I.getOperand(0)->getType())); // valistty
2532     pushValue(I.getOperand(0), InstID, Vals);              // valist.
2533     Vals.push_back(getTypeID(I.getType()));                // restype.
2534     break;
2535   }
2536 
2537   Stream.EmitRecord(Code, Vals, AbbrevToUse);
2538   Vals.clear();
2539 }
2540 
2541 // Emit names for globals/functions etc.
2542 void DXILBitcodeWriter::writeFunctionLevelValueSymbolTable(
2543     const ValueSymbolTable &VST) {
2544   if (VST.empty())
2545     return;
2546   Stream.EnterSubblock(bitc::VALUE_SYMTAB_BLOCK_ID, 4);
2547 
2548   SmallVector<unsigned, 64> NameVals;
2549 
2550   // HLSL Change
2551   // Read the named values from a sorted list instead of the original list
2552   // to ensure the binary is the same no matter what values ever existed.
2553   SmallVector<const ValueName *, 16> SortedTable;
2554 
2555   for (auto &VI : VST) {
2556     SortedTable.push_back(VI.second->getValueName());
2557   }
2558   // The keys are unique, so there shouldn't be stability issues.
2559   llvm::sort(SortedTable, [](const ValueName *A, const ValueName *B) {
2560     return A->first() < B->first();
2561   });
2562 
2563   for (const ValueName *SI : SortedTable) {
2564     auto &Name = *SI;
2565 
2566     // Figure out the encoding to use for the name.
2567     bool is7Bit = true;
2568     bool isChar6 = true;
2569     for (const char *C = Name.getKeyData(), *E = C + Name.getKeyLength();
2570          C != E; ++C) {
2571       if (isChar6)
2572         isChar6 = BitCodeAbbrevOp::isChar6(*C);
2573       if ((unsigned char)*C & 128) {
2574         is7Bit = false;
2575         break; // don't bother scanning the rest.
2576       }
2577     }
2578 
2579     unsigned AbbrevToUse = VST_ENTRY_8_ABBREV;
2580 
2581     // VST_ENTRY:   [valueid, namechar x N]
2582     // VST_BBENTRY: [bbid, namechar x N]
2583     unsigned Code;
2584     if (isa<BasicBlock>(SI->getValue())) {
2585       Code = bitc::VST_CODE_BBENTRY;
2586       if (isChar6)
2587         AbbrevToUse = VST_BBENTRY_6_ABBREV;
2588     } else {
2589       Code = bitc::VST_CODE_ENTRY;
2590       if (isChar6)
2591         AbbrevToUse = VST_ENTRY_6_ABBREV;
2592       else if (is7Bit)
2593         AbbrevToUse = VST_ENTRY_7_ABBREV;
2594     }
2595 
2596     NameVals.push_back(VE.getValueID(SI->getValue()));
2597     for (const char *P = Name.getKeyData(),
2598                     *E = Name.getKeyData() + Name.getKeyLength();
2599          P != E; ++P)
2600       NameVals.push_back((unsigned char)*P);
2601 
2602     // Emit the finished record.
2603     Stream.EmitRecord(Code, NameVals, AbbrevToUse);
2604     NameVals.clear();
2605   }
2606   Stream.ExitBlock();
2607 }
2608 
2609 /// Emit a function body to the module stream.
2610 void DXILBitcodeWriter::writeFunction(const Function &F) {
2611   Stream.EnterSubblock(bitc::FUNCTION_BLOCK_ID, 4);
2612   VE.incorporateFunction(F);
2613 
2614   SmallVector<unsigned, 64> Vals;
2615 
2616   // Emit the number of basic blocks, so the reader can create them ahead of
2617   // time.
2618   Vals.push_back(VE.getBasicBlocks().size());
2619   Stream.EmitRecord(bitc::FUNC_CODE_DECLAREBLOCKS, Vals);
2620   Vals.clear();
2621 
2622   // If there are function-local constants, emit them now.
2623   unsigned CstStart, CstEnd;
2624   VE.getFunctionConstantRange(CstStart, CstEnd);
2625   writeConstants(CstStart, CstEnd, false);
2626 
2627   // If there is function-local metadata, emit it now.
2628   writeFunctionMetadata(F);
2629 
2630   // Keep a running idea of what the instruction ID is.
2631   unsigned InstID = CstEnd;
2632 
2633   bool NeedsMetadataAttachment = F.hasMetadata();
2634 
2635   DILocation *LastDL = nullptr;
2636 
2637   // Finally, emit all the instructions, in order.
2638   for (Function::const_iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
2639     for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I != E;
2640          ++I) {
2641       writeInstruction(*I, InstID, Vals);
2642 
2643       if (!I->getType()->isVoidTy())
2644         ++InstID;
2645 
2646       // If the instruction has metadata, write a metadata attachment later.
2647       NeedsMetadataAttachment |= I->hasMetadataOtherThanDebugLoc();
2648 
2649       // If the instruction has a debug location, emit it.
2650       DILocation *DL = I->getDebugLoc();
2651       if (!DL)
2652         continue;
2653 
2654       if (DL == LastDL) {
2655         // Just repeat the same debug loc as last time.
2656         Stream.EmitRecord(bitc::FUNC_CODE_DEBUG_LOC_AGAIN, Vals);
2657         continue;
2658       }
2659 
2660       Vals.push_back(DL->getLine());
2661       Vals.push_back(DL->getColumn());
2662       Vals.push_back(VE.getMetadataOrNullID(DL->getScope()));
2663       Vals.push_back(VE.getMetadataOrNullID(DL->getInlinedAt()));
2664       Stream.EmitRecord(bitc::FUNC_CODE_DEBUG_LOC, Vals);
2665       Vals.clear();
2666 
2667       LastDL = DL;
2668     }
2669 
2670   // Emit names for all the instructions etc.
2671   if (auto *Symtab = F.getValueSymbolTable())
2672     writeFunctionLevelValueSymbolTable(*Symtab);
2673 
2674   if (NeedsMetadataAttachment)
2675     writeFunctionMetadataAttachment(F);
2676 
2677   VE.purgeFunction();
2678   Stream.ExitBlock();
2679 }
2680 
2681 // Emit blockinfo, which defines the standard abbreviations etc.
2682 void DXILBitcodeWriter::writeBlockInfo() {
2683   // We only want to emit block info records for blocks that have multiple
2684   // instances: CONSTANTS_BLOCK, FUNCTION_BLOCK and VALUE_SYMTAB_BLOCK.
2685   // Other blocks can define their abbrevs inline.
2686   Stream.EnterBlockInfoBlock();
2687 
2688   { // 8-bit fixed-width VST_ENTRY/VST_BBENTRY strings.
2689     auto Abbv = std::make_shared<BitCodeAbbrev>();
2690     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 3));
2691     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
2692     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
2693     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
2694     if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID,
2695                                    std::move(Abbv)) != VST_ENTRY_8_ABBREV)
2696       assert(false && "Unexpected abbrev ordering!");
2697   }
2698 
2699   { // 7-bit fixed width VST_ENTRY strings.
2700     auto Abbv = std::make_shared<BitCodeAbbrev>();
2701     Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_ENTRY));
2702     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
2703     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
2704     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7));
2705     if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID,
2706                                    std::move(Abbv)) != VST_ENTRY_7_ABBREV)
2707       assert(false && "Unexpected abbrev ordering!");
2708   }
2709   { // 6-bit char6 VST_ENTRY strings.
2710     auto Abbv = std::make_shared<BitCodeAbbrev>();
2711     Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_ENTRY));
2712     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
2713     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
2714     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
2715     if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID,
2716                                    std::move(Abbv)) != VST_ENTRY_6_ABBREV)
2717       assert(false && "Unexpected abbrev ordering!");
2718   }
2719   { // 6-bit char6 VST_BBENTRY strings.
2720     auto Abbv = std::make_shared<BitCodeAbbrev>();
2721     Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_BBENTRY));
2722     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
2723     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
2724     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
2725     if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID,
2726                                    std::move(Abbv)) != VST_BBENTRY_6_ABBREV)
2727       assert(false && "Unexpected abbrev ordering!");
2728   }
2729 
2730   { // SETTYPE abbrev for CONSTANTS_BLOCK.
2731     auto Abbv = std::make_shared<BitCodeAbbrev>();
2732     Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_SETTYPE));
2733     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
2734                               VE.computeBitsRequiredForTypeIndices()));
2735     if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID, std::move(Abbv)) !=
2736         CONSTANTS_SETTYPE_ABBREV)
2737       assert(false && "Unexpected abbrev ordering!");
2738   }
2739 
2740   { // INTEGER abbrev for CONSTANTS_BLOCK.
2741     auto Abbv = std::make_shared<BitCodeAbbrev>();
2742     Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_INTEGER));
2743     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
2744     if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID, std::move(Abbv)) !=
2745         CONSTANTS_INTEGER_ABBREV)
2746       assert(false && "Unexpected abbrev ordering!");
2747   }
2748 
2749   { // CE_CAST abbrev for CONSTANTS_BLOCK.
2750     auto Abbv = std::make_shared<BitCodeAbbrev>();
2751     Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_CE_CAST));
2752     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // cast opc
2753     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,      // typeid
2754                               VE.computeBitsRequiredForTypeIndices()));
2755     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // value id
2756 
2757     if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID, std::move(Abbv)) !=
2758         CONSTANTS_CE_CAST_Abbrev)
2759       assert(false && "Unexpected abbrev ordering!");
2760   }
2761   { // NULL abbrev for CONSTANTS_BLOCK.
2762     auto Abbv = std::make_shared<BitCodeAbbrev>();
2763     Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_NULL));
2764     if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID, std::move(Abbv)) !=
2765         CONSTANTS_NULL_Abbrev)
2766       assert(false && "Unexpected abbrev ordering!");
2767   }
2768 
2769   // FIXME: This should only use space for first class types!
2770 
2771   { // INST_LOAD abbrev for FUNCTION_BLOCK.
2772     auto Abbv = std::make_shared<BitCodeAbbrev>();
2773     Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_LOAD));
2774     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Ptr
2775     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,    // dest ty
2776                               VE.computeBitsRequiredForTypeIndices()));
2777     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4));   // Align
2778     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // volatile
2779     if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, std::move(Abbv)) !=
2780         (unsigned)FUNCTION_INST_LOAD_ABBREV)
2781       assert(false && "Unexpected abbrev ordering!");
2782   }
2783   { // INST_BINOP abbrev for FUNCTION_BLOCK.
2784     auto Abbv = std::make_shared<BitCodeAbbrev>();
2785     Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_BINOP));
2786     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));   // LHS
2787     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));   // RHS
2788     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
2789     if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, std::move(Abbv)) !=
2790         (unsigned)FUNCTION_INST_BINOP_ABBREV)
2791       assert(false && "Unexpected abbrev ordering!");
2792   }
2793   { // INST_BINOP_FLAGS abbrev for FUNCTION_BLOCK.
2794     auto Abbv = std::make_shared<BitCodeAbbrev>();
2795     Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_BINOP));
2796     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));   // LHS
2797     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));   // RHS
2798     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
2799     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7)); // flags
2800     if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, std::move(Abbv)) !=
2801         (unsigned)FUNCTION_INST_BINOP_FLAGS_ABBREV)
2802       assert(false && "Unexpected abbrev ordering!");
2803   }
2804   { // INST_CAST abbrev for FUNCTION_BLOCK.
2805     auto Abbv = std::make_shared<BitCodeAbbrev>();
2806     Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_CAST));
2807     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // OpVal
2808     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,    // dest ty
2809                               VE.computeBitsRequiredForTypeIndices()));
2810     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
2811     if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, std::move(Abbv)) !=
2812         (unsigned)FUNCTION_INST_CAST_ABBREV)
2813       assert(false && "Unexpected abbrev ordering!");
2814   }
2815 
2816   { // INST_RET abbrev for FUNCTION_BLOCK.
2817     auto Abbv = std::make_shared<BitCodeAbbrev>();
2818     Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_RET));
2819     if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, std::move(Abbv)) !=
2820         (unsigned)FUNCTION_INST_RET_VOID_ABBREV)
2821       assert(false && "Unexpected abbrev ordering!");
2822   }
2823   { // INST_RET abbrev for FUNCTION_BLOCK.
2824     auto Abbv = std::make_shared<BitCodeAbbrev>();
2825     Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_RET));
2826     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // ValID
2827     if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, std::move(Abbv)) !=
2828         (unsigned)FUNCTION_INST_RET_VAL_ABBREV)
2829       assert(false && "Unexpected abbrev ordering!");
2830   }
2831   { // INST_UNREACHABLE abbrev for FUNCTION_BLOCK.
2832     auto Abbv = std::make_shared<BitCodeAbbrev>();
2833     Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_UNREACHABLE));
2834     if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, std::move(Abbv)) !=
2835         (unsigned)FUNCTION_INST_UNREACHABLE_ABBREV)
2836       assert(false && "Unexpected abbrev ordering!");
2837   }
2838   {
2839     auto Abbv = std::make_shared<BitCodeAbbrev>();
2840     Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_GEP));
2841     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));
2842     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, // dest ty
2843                               Log2_32_Ceil(VE.getTypes().size() + 1)));
2844     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
2845     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
2846     if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, std::move(Abbv)) !=
2847         (unsigned)FUNCTION_INST_GEP_ABBREV)
2848       assert(false && "Unexpected abbrev ordering!");
2849   }
2850 
2851   Stream.ExitBlock();
2852 }
2853 
2854 void DXILBitcodeWriter::writeModuleVersion() {
2855   // VERSION: [version#]
2856   Stream.EmitRecord(bitc::MODULE_CODE_VERSION, ArrayRef<unsigned>{1});
2857 }
2858 
2859 /// WriteModule - Emit the specified module to the bitstream.
2860 void DXILBitcodeWriter::write() {
2861   // The identification block is new since llvm-3.7, but the old bitcode reader
2862   // will skip it.
2863   // writeIdentificationBlock(Stream);
2864 
2865   Stream.EnterSubblock(bitc::MODULE_BLOCK_ID, 3);
2866 
2867   // It is redundant to fully-specify this here, but nice to make it explicit
2868   // so that it is clear the DXIL module version is different.
2869   DXILBitcodeWriter::writeModuleVersion();
2870 
2871   // Emit blockinfo, which defines the standard abbreviations etc.
2872   writeBlockInfo();
2873 
2874   // Emit information about attribute groups.
2875   writeAttributeGroupTable();
2876 
2877   // Emit information about parameter attributes.
2878   writeAttributeTable();
2879 
2880   // Emit information describing all of the types in the module.
2881   writeTypeTable();
2882 
2883   writeComdats();
2884 
2885   // Emit top-level description of module, including target triple, inline asm,
2886   // descriptors for global variables, and function prototype info.
2887   writeModuleInfo();
2888 
2889   // Emit constants.
2890   writeModuleConstants();
2891 
2892   // Emit metadata.
2893   writeModuleMetadataKinds();
2894 
2895   // Emit metadata.
2896   writeModuleMetadata();
2897 
2898   // Emit names for globals/functions etc.
2899   // DXIL uses the same format for module-level value symbol table as for the
2900   // function level table.
2901   writeFunctionLevelValueSymbolTable(M.getValueSymbolTable());
2902 
2903   // Emit function bodies.
2904   for (const Function &F : M)
2905     if (!F.isDeclaration())
2906       writeFunction(F);
2907 
2908   Stream.ExitBlock();
2909 }
2910