xref: /src/contrib/llvm-project/llvm/lib/Target/DirectX/DXILWriter/DXILBitcodeWriter.cpp (revision 0fca6ea1d4eea4c934cfff25ac9ee8ad6fe95583)
1145449b1SDimitry Andric //===- Bitcode/Writer/DXILBitcodeWriter.cpp - DXIL Bitcode Writer ---------===//
2145449b1SDimitry Andric //
3145449b1SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4145449b1SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
5145449b1SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6145449b1SDimitry Andric //
7145449b1SDimitry Andric //===----------------------------------------------------------------------===//
8145449b1SDimitry Andric //
9145449b1SDimitry Andric // Bitcode writer implementation.
10145449b1SDimitry Andric //
11145449b1SDimitry Andric //===----------------------------------------------------------------------===//
12145449b1SDimitry Andric 
13145449b1SDimitry Andric #include "DXILBitcodeWriter.h"
14145449b1SDimitry Andric #include "DXILValueEnumerator.h"
15e3b55780SDimitry Andric #include "DirectXIRPasses/PointerTypeAnalysis.h"
164b4fe385SDimitry Andric #include "llvm/ADT/STLExtras.h"
17145449b1SDimitry Andric #include "llvm/Bitcode/BitcodeCommon.h"
18145449b1SDimitry Andric #include "llvm/Bitcode/BitcodeReader.h"
19145449b1SDimitry Andric #include "llvm/Bitcode/LLVMBitCodes.h"
20145449b1SDimitry Andric #include "llvm/Bitstream/BitCodes.h"
21145449b1SDimitry Andric #include "llvm/Bitstream/BitstreamWriter.h"
22145449b1SDimitry Andric #include "llvm/IR/Attributes.h"
23145449b1SDimitry Andric #include "llvm/IR/BasicBlock.h"
24145449b1SDimitry Andric #include "llvm/IR/Comdat.h"
25145449b1SDimitry Andric #include "llvm/IR/Constant.h"
26145449b1SDimitry Andric #include "llvm/IR/Constants.h"
27145449b1SDimitry Andric #include "llvm/IR/DebugInfoMetadata.h"
28145449b1SDimitry Andric #include "llvm/IR/DebugLoc.h"
29145449b1SDimitry Andric #include "llvm/IR/DerivedTypes.h"
30145449b1SDimitry Andric #include "llvm/IR/Function.h"
31145449b1SDimitry Andric #include "llvm/IR/GlobalAlias.h"
32145449b1SDimitry Andric #include "llvm/IR/GlobalIFunc.h"
33145449b1SDimitry Andric #include "llvm/IR/GlobalObject.h"
34145449b1SDimitry Andric #include "llvm/IR/GlobalValue.h"
35145449b1SDimitry Andric #include "llvm/IR/GlobalVariable.h"
36145449b1SDimitry Andric #include "llvm/IR/InlineAsm.h"
37145449b1SDimitry Andric #include "llvm/IR/InstrTypes.h"
38145449b1SDimitry Andric #include "llvm/IR/Instruction.h"
39145449b1SDimitry Andric #include "llvm/IR/Instructions.h"
40145449b1SDimitry Andric #include "llvm/IR/LLVMContext.h"
41145449b1SDimitry Andric #include "llvm/IR/Metadata.h"
42145449b1SDimitry Andric #include "llvm/IR/Module.h"
43145449b1SDimitry Andric #include "llvm/IR/ModuleSummaryIndex.h"
44145449b1SDimitry Andric #include "llvm/IR/Operator.h"
45145449b1SDimitry Andric #include "llvm/IR/Type.h"
46145449b1SDimitry Andric #include "llvm/IR/UseListOrder.h"
47145449b1SDimitry Andric #include "llvm/IR/Value.h"
48145449b1SDimitry Andric #include "llvm/IR/ValueSymbolTable.h"
49145449b1SDimitry Andric #include "llvm/Object/IRSymtab.h"
50145449b1SDimitry Andric #include "llvm/Support/ErrorHandling.h"
51e3b55780SDimitry Andric #include "llvm/Support/ModRef.h"
52145449b1SDimitry Andric #include "llvm/Support/SHA1.h"
537fa27ce4SDimitry Andric #include "llvm/TargetParser/Triple.h"
54145449b1SDimitry Andric 
55145449b1SDimitry Andric namespace llvm {
56145449b1SDimitry Andric namespace dxil {
57145449b1SDimitry Andric 
58145449b1SDimitry Andric // Generates an enum to use as an index in the Abbrev array of Metadata record.
59145449b1SDimitry Andric enum MetadataAbbrev : unsigned {
60145449b1SDimitry Andric #define HANDLE_MDNODE_LEAF(CLASS) CLASS##AbbrevID,
61145449b1SDimitry Andric #include "llvm/IR/Metadata.def"
62145449b1SDimitry Andric   LastPlusOne
63145449b1SDimitry Andric };
64145449b1SDimitry Andric 
65145449b1SDimitry Andric class DXILBitcodeWriter {
66145449b1SDimitry Andric 
67145449b1SDimitry Andric   /// These are manifest constants used by the bitcode writer. They do not need
68145449b1SDimitry Andric   /// to be kept in sync with the reader, but need to be consistent within this
69145449b1SDimitry Andric   /// file.
70145449b1SDimitry Andric   enum {
71145449b1SDimitry Andric     // VALUE_SYMTAB_BLOCK abbrev id's.
72145449b1SDimitry Andric     VST_ENTRY_8_ABBREV = bitc::FIRST_APPLICATION_ABBREV,
73145449b1SDimitry Andric     VST_ENTRY_7_ABBREV,
74145449b1SDimitry Andric     VST_ENTRY_6_ABBREV,
75145449b1SDimitry Andric     VST_BBENTRY_6_ABBREV,
76145449b1SDimitry Andric 
77145449b1SDimitry Andric     // CONSTANTS_BLOCK abbrev id's.
78145449b1SDimitry Andric     CONSTANTS_SETTYPE_ABBREV = bitc::FIRST_APPLICATION_ABBREV,
79145449b1SDimitry Andric     CONSTANTS_INTEGER_ABBREV,
80145449b1SDimitry Andric     CONSTANTS_CE_CAST_Abbrev,
81145449b1SDimitry Andric     CONSTANTS_NULL_Abbrev,
82145449b1SDimitry Andric 
83145449b1SDimitry Andric     // FUNCTION_BLOCK abbrev id's.
84145449b1SDimitry Andric     FUNCTION_INST_LOAD_ABBREV = bitc::FIRST_APPLICATION_ABBREV,
85145449b1SDimitry Andric     FUNCTION_INST_BINOP_ABBREV,
86145449b1SDimitry Andric     FUNCTION_INST_BINOP_FLAGS_ABBREV,
87145449b1SDimitry Andric     FUNCTION_INST_CAST_ABBREV,
88145449b1SDimitry Andric     FUNCTION_INST_RET_VOID_ABBREV,
89145449b1SDimitry Andric     FUNCTION_INST_RET_VAL_ABBREV,
90145449b1SDimitry Andric     FUNCTION_INST_UNREACHABLE_ABBREV,
91145449b1SDimitry Andric     FUNCTION_INST_GEP_ABBREV,
92145449b1SDimitry Andric   };
93145449b1SDimitry Andric 
94145449b1SDimitry Andric   // Cache some types
95145449b1SDimitry Andric   Type *I8Ty;
96145449b1SDimitry Andric   Type *I8PtrTy;
97145449b1SDimitry Andric 
98145449b1SDimitry Andric   /// The stream created and owned by the client.
99145449b1SDimitry Andric   BitstreamWriter &Stream;
100145449b1SDimitry Andric 
101145449b1SDimitry Andric   StringTableBuilder &StrtabBuilder;
102145449b1SDimitry Andric 
103145449b1SDimitry Andric   /// The Module to write to bitcode.
104145449b1SDimitry Andric   const Module &M;
105145449b1SDimitry Andric 
106145449b1SDimitry Andric   /// Enumerates ids for all values in the module.
107145449b1SDimitry Andric   ValueEnumerator VE;
108145449b1SDimitry Andric 
109145449b1SDimitry Andric   /// Map that holds the correspondence between GUIDs in the summary index,
110145449b1SDimitry Andric   /// that came from indirect call profiles, and a value id generated by this
111145449b1SDimitry Andric   /// class to use in the VST and summary block records.
112145449b1SDimitry Andric   std::map<GlobalValue::GUID, unsigned> GUIDToValueIdMap;
113145449b1SDimitry Andric 
114145449b1SDimitry Andric   /// Tracks the last value id recorded in the GUIDToValueMap.
115145449b1SDimitry Andric   unsigned GlobalValueId;
116145449b1SDimitry Andric 
117145449b1SDimitry Andric   /// Saves the offset of the VSTOffset record that must eventually be
118145449b1SDimitry Andric   /// backpatched with the offset of the actual VST.
119145449b1SDimitry Andric   uint64_t VSTOffsetPlaceholder = 0;
120145449b1SDimitry Andric 
121145449b1SDimitry Andric   /// Pointer to the buffer allocated by caller for bitcode writing.
122145449b1SDimitry Andric   const SmallVectorImpl<char> &Buffer;
123145449b1SDimitry Andric 
124145449b1SDimitry Andric   /// The start bit of the identification block.
125145449b1SDimitry Andric   uint64_t BitcodeStartBit;
126145449b1SDimitry Andric 
127145449b1SDimitry Andric   /// This maps values to their typed pointers
128145449b1SDimitry Andric   PointerTypeMap PointerMap;
129145449b1SDimitry Andric 
130145449b1SDimitry Andric public:
131145449b1SDimitry Andric   /// Constructs a ModuleBitcodeWriter object for the given Module,
132145449b1SDimitry Andric   /// writing to the provided \p Buffer.
DXILBitcodeWriter(const Module & M,SmallVectorImpl<char> & Buffer,StringTableBuilder & StrtabBuilder,BitstreamWriter & Stream)133145449b1SDimitry Andric   DXILBitcodeWriter(const Module &M, SmallVectorImpl<char> &Buffer,
134145449b1SDimitry Andric                     StringTableBuilder &StrtabBuilder, BitstreamWriter &Stream)
135145449b1SDimitry Andric       : I8Ty(Type::getInt8Ty(M.getContext())),
136145449b1SDimitry Andric         I8PtrTy(TypedPointerType::get(I8Ty, 0)), Stream(Stream),
137145449b1SDimitry Andric         StrtabBuilder(StrtabBuilder), M(M), VE(M, I8PtrTy), Buffer(Buffer),
138145449b1SDimitry Andric         BitcodeStartBit(Stream.GetCurrentBitNo()),
139145449b1SDimitry Andric         PointerMap(PointerTypeAnalysis::run(M)) {
140145449b1SDimitry Andric     GlobalValueId = VE.getValues().size();
141145449b1SDimitry Andric     // Enumerate the typed pointers
142145449b1SDimitry Andric     for (auto El : PointerMap)
143145449b1SDimitry Andric       VE.EnumerateType(El.second);
144145449b1SDimitry Andric   }
145145449b1SDimitry Andric 
146145449b1SDimitry Andric   /// Emit the current module to the bitstream.
147145449b1SDimitry Andric   void write();
148145449b1SDimitry Andric 
149145449b1SDimitry Andric   static uint64_t getAttrKindEncoding(Attribute::AttrKind Kind);
150145449b1SDimitry Andric   static void writeStringRecord(BitstreamWriter &Stream, unsigned Code,
151145449b1SDimitry Andric                                 StringRef Str, unsigned AbbrevToUse);
152145449b1SDimitry Andric   static void writeIdentificationBlock(BitstreamWriter &Stream);
153145449b1SDimitry Andric   static void emitSignedInt64(SmallVectorImpl<uint64_t> &Vals, uint64_t V);
154145449b1SDimitry Andric   static void emitWideAPInt(SmallVectorImpl<uint64_t> &Vals, const APInt &A);
155145449b1SDimitry Andric 
156145449b1SDimitry Andric   static unsigned getEncodedComdatSelectionKind(const Comdat &C);
157145449b1SDimitry Andric   static unsigned getEncodedLinkage(const GlobalValue::LinkageTypes Linkage);
158145449b1SDimitry Andric   static unsigned getEncodedLinkage(const GlobalValue &GV);
159145449b1SDimitry Andric   static unsigned getEncodedVisibility(const GlobalValue &GV);
160145449b1SDimitry Andric   static unsigned getEncodedThreadLocalMode(const GlobalValue &GV);
161145449b1SDimitry Andric   static unsigned getEncodedDLLStorageClass(const GlobalValue &GV);
162145449b1SDimitry Andric   static unsigned getEncodedCastOpcode(unsigned Opcode);
163145449b1SDimitry Andric   static unsigned getEncodedUnaryOpcode(unsigned Opcode);
164145449b1SDimitry Andric   static unsigned getEncodedBinaryOpcode(unsigned Opcode);
165145449b1SDimitry Andric   static unsigned getEncodedRMWOperation(AtomicRMWInst::BinOp Op);
166145449b1SDimitry Andric   static unsigned getEncodedOrdering(AtomicOrdering Ordering);
167145449b1SDimitry Andric   static uint64_t getOptimizationFlags(const Value *V);
168145449b1SDimitry Andric 
169145449b1SDimitry Andric private:
170145449b1SDimitry Andric   void writeModuleVersion();
171145449b1SDimitry Andric   void writePerModuleGlobalValueSummary();
172145449b1SDimitry Andric 
173145449b1SDimitry Andric   void writePerModuleFunctionSummaryRecord(SmallVector<uint64_t, 64> &NameVals,
174145449b1SDimitry Andric                                            GlobalValueSummary *Summary,
175145449b1SDimitry Andric                                            unsigned ValueID,
176145449b1SDimitry Andric                                            unsigned FSCallsAbbrev,
177145449b1SDimitry Andric                                            unsigned FSCallsProfileAbbrev,
178145449b1SDimitry Andric                                            const Function &F);
179145449b1SDimitry Andric   void writeModuleLevelReferences(const GlobalVariable &V,
180145449b1SDimitry Andric                                   SmallVector<uint64_t, 64> &NameVals,
181145449b1SDimitry Andric                                   unsigned FSModRefsAbbrev,
182145449b1SDimitry Andric                                   unsigned FSModVTableRefsAbbrev);
183145449b1SDimitry Andric 
assignValueId(GlobalValue::GUID ValGUID)184145449b1SDimitry Andric   void assignValueId(GlobalValue::GUID ValGUID) {
185145449b1SDimitry Andric     GUIDToValueIdMap[ValGUID] = ++GlobalValueId;
186145449b1SDimitry Andric   }
187145449b1SDimitry Andric 
getValueId(GlobalValue::GUID ValGUID)188145449b1SDimitry Andric   unsigned getValueId(GlobalValue::GUID ValGUID) {
189145449b1SDimitry Andric     const auto &VMI = GUIDToValueIdMap.find(ValGUID);
190145449b1SDimitry Andric     // Expect that any GUID value had a value Id assigned by an
191145449b1SDimitry Andric     // earlier call to assignValueId.
192145449b1SDimitry Andric     assert(VMI != GUIDToValueIdMap.end() &&
193145449b1SDimitry Andric            "GUID does not have assigned value Id");
194145449b1SDimitry Andric     return VMI->second;
195145449b1SDimitry Andric   }
196145449b1SDimitry Andric 
197145449b1SDimitry Andric   // Helper to get the valueId for the type of value recorded in VI.
getValueId(ValueInfo VI)198145449b1SDimitry Andric   unsigned getValueId(ValueInfo VI) {
199145449b1SDimitry Andric     if (!VI.haveGVs() || !VI.getValue())
200145449b1SDimitry Andric       return getValueId(VI.getGUID());
201145449b1SDimitry Andric     return VE.getValueID(VI.getValue());
202145449b1SDimitry Andric   }
203145449b1SDimitry Andric 
valueIds()204145449b1SDimitry Andric   std::map<GlobalValue::GUID, unsigned> &valueIds() { return GUIDToValueIdMap; }
205145449b1SDimitry Andric 
bitcodeStartBit()206145449b1SDimitry Andric   uint64_t bitcodeStartBit() { return BitcodeStartBit; }
207145449b1SDimitry Andric 
208145449b1SDimitry Andric   size_t addToStrtab(StringRef Str);
209145449b1SDimitry Andric 
210145449b1SDimitry Andric   unsigned createDILocationAbbrev();
211145449b1SDimitry Andric   unsigned createGenericDINodeAbbrev();
212145449b1SDimitry Andric 
213145449b1SDimitry Andric   void writeAttributeGroupTable();
214145449b1SDimitry Andric   void writeAttributeTable();
215145449b1SDimitry Andric   void writeTypeTable();
216145449b1SDimitry Andric   void writeComdats();
217145449b1SDimitry Andric   void writeValueSymbolTableForwardDecl();
218145449b1SDimitry Andric   void writeModuleInfo();
219145449b1SDimitry Andric   void writeValueAsMetadata(const ValueAsMetadata *MD,
220145449b1SDimitry Andric                             SmallVectorImpl<uint64_t> &Record);
221145449b1SDimitry Andric   void writeMDTuple(const MDTuple *N, SmallVectorImpl<uint64_t> &Record,
222145449b1SDimitry Andric                     unsigned Abbrev);
223145449b1SDimitry Andric   void writeDILocation(const DILocation *N, SmallVectorImpl<uint64_t> &Record,
224145449b1SDimitry Andric                        unsigned &Abbrev);
writeGenericDINode(const GenericDINode * N,SmallVectorImpl<uint64_t> & Record,unsigned & Abbrev)225145449b1SDimitry Andric   void writeGenericDINode(const GenericDINode *N,
226145449b1SDimitry Andric                           SmallVectorImpl<uint64_t> &Record, unsigned &Abbrev) {
227145449b1SDimitry Andric     llvm_unreachable("DXIL cannot contain GenericDI Nodes");
228145449b1SDimitry Andric   }
229145449b1SDimitry Andric   void writeDISubrange(const DISubrange *N, SmallVectorImpl<uint64_t> &Record,
230145449b1SDimitry Andric                        unsigned Abbrev);
writeDIGenericSubrange(const DIGenericSubrange * N,SmallVectorImpl<uint64_t> & Record,unsigned Abbrev)231145449b1SDimitry Andric   void writeDIGenericSubrange(const DIGenericSubrange *N,
232145449b1SDimitry Andric                               SmallVectorImpl<uint64_t> &Record,
233145449b1SDimitry Andric                               unsigned Abbrev) {
234145449b1SDimitry Andric     llvm_unreachable("DXIL cannot contain DIGenericSubrange Nodes");
235145449b1SDimitry Andric   }
236145449b1SDimitry Andric   void writeDIEnumerator(const DIEnumerator *N,
237145449b1SDimitry Andric                          SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
238145449b1SDimitry Andric   void writeDIBasicType(const DIBasicType *N, SmallVectorImpl<uint64_t> &Record,
239145449b1SDimitry Andric                         unsigned Abbrev);
writeDIStringType(const DIStringType * N,SmallVectorImpl<uint64_t> & Record,unsigned Abbrev)240145449b1SDimitry Andric   void writeDIStringType(const DIStringType *N,
241145449b1SDimitry Andric                          SmallVectorImpl<uint64_t> &Record, unsigned Abbrev) {
242145449b1SDimitry Andric     llvm_unreachable("DXIL cannot contain DIStringType Nodes");
243145449b1SDimitry Andric   }
244145449b1SDimitry Andric   void writeDIDerivedType(const DIDerivedType *N,
245145449b1SDimitry Andric                           SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
246145449b1SDimitry Andric   void writeDICompositeType(const DICompositeType *N,
247145449b1SDimitry Andric                             SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
248145449b1SDimitry Andric   void writeDISubroutineType(const DISubroutineType *N,
249145449b1SDimitry Andric                              SmallVectorImpl<uint64_t> &Record,
250145449b1SDimitry Andric                              unsigned Abbrev);
251145449b1SDimitry Andric   void writeDIFile(const DIFile *N, SmallVectorImpl<uint64_t> &Record,
252145449b1SDimitry Andric                    unsigned Abbrev);
253145449b1SDimitry Andric   void writeDICompileUnit(const DICompileUnit *N,
254145449b1SDimitry Andric                           SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
255145449b1SDimitry Andric   void writeDISubprogram(const DISubprogram *N,
256145449b1SDimitry Andric                          SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
257145449b1SDimitry Andric   void writeDILexicalBlock(const DILexicalBlock *N,
258145449b1SDimitry Andric                            SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
259145449b1SDimitry Andric   void writeDILexicalBlockFile(const DILexicalBlockFile *N,
260145449b1SDimitry Andric                                SmallVectorImpl<uint64_t> &Record,
261145449b1SDimitry Andric                                unsigned Abbrev);
writeDICommonBlock(const DICommonBlock * N,SmallVectorImpl<uint64_t> & Record,unsigned Abbrev)262145449b1SDimitry Andric   void writeDICommonBlock(const DICommonBlock *N,
263145449b1SDimitry Andric                           SmallVectorImpl<uint64_t> &Record, unsigned Abbrev) {
264145449b1SDimitry Andric     llvm_unreachable("DXIL cannot contain DICommonBlock Nodes");
265145449b1SDimitry Andric   }
266145449b1SDimitry Andric   void writeDINamespace(const DINamespace *N, SmallVectorImpl<uint64_t> &Record,
267145449b1SDimitry Andric                         unsigned Abbrev);
writeDIMacro(const DIMacro * N,SmallVectorImpl<uint64_t> & Record,unsigned Abbrev)268145449b1SDimitry Andric   void writeDIMacro(const DIMacro *N, SmallVectorImpl<uint64_t> &Record,
269145449b1SDimitry Andric                     unsigned Abbrev) {
270145449b1SDimitry Andric     llvm_unreachable("DXIL cannot contain DIMacro Nodes");
271145449b1SDimitry Andric   }
writeDIMacroFile(const DIMacroFile * N,SmallVectorImpl<uint64_t> & Record,unsigned Abbrev)272145449b1SDimitry Andric   void writeDIMacroFile(const DIMacroFile *N, SmallVectorImpl<uint64_t> &Record,
273145449b1SDimitry Andric                         unsigned Abbrev) {
274145449b1SDimitry Andric     llvm_unreachable("DXIL cannot contain DIMacroFile Nodes");
275145449b1SDimitry Andric   }
writeDIArgList(const DIArgList * N,SmallVectorImpl<uint64_t> & Record,unsigned Abbrev)276145449b1SDimitry Andric   void writeDIArgList(const DIArgList *N, SmallVectorImpl<uint64_t> &Record,
277145449b1SDimitry Andric                       unsigned Abbrev) {
278145449b1SDimitry Andric     llvm_unreachable("DXIL cannot contain DIArgList Nodes");
279145449b1SDimitry Andric   }
writeDIAssignID(const DIAssignID * N,SmallVectorImpl<uint64_t> & Record,unsigned Abbrev)280e3b55780SDimitry Andric   void writeDIAssignID(const DIAssignID *N, SmallVectorImpl<uint64_t> &Record,
281e3b55780SDimitry Andric                        unsigned Abbrev) {
282e3b55780SDimitry Andric     // DIAssignID is experimental feature to track variable location in IR..
283e3b55780SDimitry Andric     // FIXME: translate DIAssignID to debug info DXIL supports.
284e3b55780SDimitry Andric     //   See https://github.com/llvm/llvm-project/issues/58989
285e3b55780SDimitry Andric     llvm_unreachable("DXIL cannot contain DIAssignID Nodes");
286e3b55780SDimitry Andric   }
287145449b1SDimitry Andric   void writeDIModule(const DIModule *N, SmallVectorImpl<uint64_t> &Record,
288145449b1SDimitry Andric                      unsigned Abbrev);
289145449b1SDimitry Andric   void writeDITemplateTypeParameter(const DITemplateTypeParameter *N,
290145449b1SDimitry Andric                                     SmallVectorImpl<uint64_t> &Record,
291145449b1SDimitry Andric                                     unsigned Abbrev);
292145449b1SDimitry Andric   void writeDITemplateValueParameter(const DITemplateValueParameter *N,
293145449b1SDimitry Andric                                      SmallVectorImpl<uint64_t> &Record,
294145449b1SDimitry Andric                                      unsigned Abbrev);
295145449b1SDimitry Andric   void writeDIGlobalVariable(const DIGlobalVariable *N,
296145449b1SDimitry Andric                              SmallVectorImpl<uint64_t> &Record,
297145449b1SDimitry Andric                              unsigned Abbrev);
298145449b1SDimitry Andric   void writeDILocalVariable(const DILocalVariable *N,
299145449b1SDimitry Andric                             SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
writeDILabel(const DILabel * N,SmallVectorImpl<uint64_t> & Record,unsigned Abbrev)300145449b1SDimitry Andric   void writeDILabel(const DILabel *N, SmallVectorImpl<uint64_t> &Record,
301145449b1SDimitry Andric                     unsigned Abbrev) {
302145449b1SDimitry Andric     llvm_unreachable("DXIL cannot contain DILabel Nodes");
303145449b1SDimitry Andric   }
304145449b1SDimitry Andric   void writeDIExpression(const DIExpression *N,
305145449b1SDimitry Andric                          SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
writeDIGlobalVariableExpression(const DIGlobalVariableExpression * N,SmallVectorImpl<uint64_t> & Record,unsigned Abbrev)306145449b1SDimitry Andric   void writeDIGlobalVariableExpression(const DIGlobalVariableExpression *N,
307145449b1SDimitry Andric                                        SmallVectorImpl<uint64_t> &Record,
308145449b1SDimitry Andric                                        unsigned Abbrev) {
309145449b1SDimitry Andric     llvm_unreachable("DXIL cannot contain GlobalVariableExpression Nodes");
310145449b1SDimitry Andric   }
311145449b1SDimitry Andric   void writeDIObjCProperty(const DIObjCProperty *N,
312145449b1SDimitry Andric                            SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
313145449b1SDimitry Andric   void writeDIImportedEntity(const DIImportedEntity *N,
314145449b1SDimitry Andric                              SmallVectorImpl<uint64_t> &Record,
315145449b1SDimitry Andric                              unsigned Abbrev);
316145449b1SDimitry Andric   unsigned createNamedMetadataAbbrev();
317145449b1SDimitry Andric   void writeNamedMetadata(SmallVectorImpl<uint64_t> &Record);
318145449b1SDimitry Andric   unsigned createMetadataStringsAbbrev();
319145449b1SDimitry Andric   void writeMetadataStrings(ArrayRef<const Metadata *> Strings,
320145449b1SDimitry Andric                             SmallVectorImpl<uint64_t> &Record);
321145449b1SDimitry Andric   void writeMetadataRecords(ArrayRef<const Metadata *> MDs,
322145449b1SDimitry Andric                             SmallVectorImpl<uint64_t> &Record,
323145449b1SDimitry Andric                             std::vector<unsigned> *MDAbbrevs = nullptr,
324145449b1SDimitry Andric                             std::vector<uint64_t> *IndexPos = nullptr);
325145449b1SDimitry Andric   void writeModuleMetadata();
326145449b1SDimitry Andric   void writeFunctionMetadata(const Function &F);
327145449b1SDimitry Andric   void writeFunctionMetadataAttachment(const Function &F);
328145449b1SDimitry Andric   void pushGlobalMetadataAttachment(SmallVectorImpl<uint64_t> &Record,
329145449b1SDimitry Andric                                     const GlobalObject &GO);
330145449b1SDimitry Andric   void writeModuleMetadataKinds();
331145449b1SDimitry Andric   void writeOperandBundleTags();
332145449b1SDimitry Andric   void writeSyncScopeNames();
333145449b1SDimitry Andric   void writeConstants(unsigned FirstVal, unsigned LastVal, bool isGlobal);
334145449b1SDimitry Andric   void writeModuleConstants();
335145449b1SDimitry Andric   bool pushValueAndType(const Value *V, unsigned InstID,
336145449b1SDimitry Andric                         SmallVectorImpl<unsigned> &Vals);
337145449b1SDimitry Andric   void writeOperandBundles(const CallBase &CB, unsigned InstID);
338145449b1SDimitry Andric   void pushValue(const Value *V, unsigned InstID,
339145449b1SDimitry Andric                  SmallVectorImpl<unsigned> &Vals);
340145449b1SDimitry Andric   void pushValueSigned(const Value *V, unsigned InstID,
341145449b1SDimitry Andric                        SmallVectorImpl<uint64_t> &Vals);
342145449b1SDimitry Andric   void writeInstruction(const Instruction &I, unsigned InstID,
343145449b1SDimitry Andric                         SmallVectorImpl<unsigned> &Vals);
344145449b1SDimitry Andric   void writeFunctionLevelValueSymbolTable(const ValueSymbolTable &VST);
345145449b1SDimitry Andric   void writeGlobalValueSymbolTable(
346145449b1SDimitry Andric       DenseMap<const Function *, uint64_t> &FunctionToBitcodeIndex);
347145449b1SDimitry Andric   void writeFunction(const Function &F);
348145449b1SDimitry Andric   void writeBlockInfo();
349145449b1SDimitry Andric 
getEncodedSyncScopeID(SyncScope::ID SSID)350145449b1SDimitry Andric   unsigned getEncodedSyncScopeID(SyncScope::ID SSID) { return unsigned(SSID); }
351145449b1SDimitry Andric 
getEncodedAlign(MaybeAlign Alignment)352145449b1SDimitry Andric   unsigned getEncodedAlign(MaybeAlign Alignment) { return encode(Alignment); }
353145449b1SDimitry Andric 
354145449b1SDimitry Andric   unsigned getTypeID(Type *T, const Value *V = nullptr);
355e3b55780SDimitry Andric   /// getGlobalObjectValueTypeID - returns the element type for a GlobalObject
356e3b55780SDimitry Andric   ///
357e3b55780SDimitry Andric   /// GlobalObject types are saved by PointerTypeAnalysis as pointers to the
358e3b55780SDimitry Andric   /// GlobalObject, but in the bitcode writer we need the pointer element type.
359e3b55780SDimitry Andric   unsigned getGlobalObjectValueTypeID(Type *T, const GlobalObject *G);
360145449b1SDimitry Andric };
361145449b1SDimitry Andric 
362145449b1SDimitry Andric } // namespace dxil
363145449b1SDimitry Andric } // namespace llvm
364145449b1SDimitry Andric 
365145449b1SDimitry Andric using namespace llvm;
366145449b1SDimitry Andric using namespace llvm::dxil;
367145449b1SDimitry Andric 
368145449b1SDimitry Andric ////////////////////////////////////////////////////////////////////////////////
369145449b1SDimitry Andric /// Begin dxil::BitcodeWriter Implementation
370145449b1SDimitry Andric ////////////////////////////////////////////////////////////////////////////////
371145449b1SDimitry Andric 
BitcodeWriter(SmallVectorImpl<char> & Buffer)372ac9a064cSDimitry Andric dxil::BitcodeWriter::BitcodeWriter(SmallVectorImpl<char> &Buffer)
373ac9a064cSDimitry Andric     : Buffer(Buffer), Stream(new BitstreamWriter(Buffer)) {
374145449b1SDimitry Andric   // Emit the file header.
375145449b1SDimitry Andric   Stream->Emit((unsigned)'B', 8);
376145449b1SDimitry Andric   Stream->Emit((unsigned)'C', 8);
377145449b1SDimitry Andric   Stream->Emit(0x0, 4);
378145449b1SDimitry Andric   Stream->Emit(0xC, 4);
379145449b1SDimitry Andric   Stream->Emit(0xE, 4);
380145449b1SDimitry Andric   Stream->Emit(0xD, 4);
381145449b1SDimitry Andric }
382145449b1SDimitry Andric 
~BitcodeWriter()383e3b55780SDimitry Andric dxil::BitcodeWriter::~BitcodeWriter() { }
384145449b1SDimitry Andric 
385145449b1SDimitry Andric /// Write the specified module to the specified output stream.
WriteDXILToFile(const Module & M,raw_ostream & Out)386145449b1SDimitry Andric void dxil::WriteDXILToFile(const Module &M, raw_ostream &Out) {
387145449b1SDimitry Andric   SmallVector<char, 0> Buffer;
388145449b1SDimitry Andric   Buffer.reserve(256 * 1024);
389145449b1SDimitry Andric 
390145449b1SDimitry Andric   // If this is darwin or another generic macho target, reserve space for the
391145449b1SDimitry Andric   // header.
392145449b1SDimitry Andric   Triple TT(M.getTargetTriple());
393145449b1SDimitry Andric   if (TT.isOSDarwin() || TT.isOSBinFormatMachO())
394145449b1SDimitry Andric     Buffer.insert(Buffer.begin(), BWH_HeaderSize, 0);
395145449b1SDimitry Andric 
396ac9a064cSDimitry Andric   BitcodeWriter Writer(Buffer);
397145449b1SDimitry Andric   Writer.writeModule(M);
398145449b1SDimitry Andric 
399145449b1SDimitry Andric   // Write the generated bitstream to "Out".
400145449b1SDimitry Andric   if (!Buffer.empty())
401145449b1SDimitry Andric     Out.write((char *)&Buffer.front(), Buffer.size());
402145449b1SDimitry Andric }
403145449b1SDimitry Andric 
writeBlob(unsigned Block,unsigned Record,StringRef Blob)404145449b1SDimitry Andric void BitcodeWriter::writeBlob(unsigned Block, unsigned Record, StringRef Blob) {
405145449b1SDimitry Andric   Stream->EnterSubblock(Block, 3);
406145449b1SDimitry Andric 
407145449b1SDimitry Andric   auto Abbv = std::make_shared<BitCodeAbbrev>();
408145449b1SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(Record));
409145449b1SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
410145449b1SDimitry Andric   auto AbbrevNo = Stream->EmitAbbrev(std::move(Abbv));
411145449b1SDimitry Andric 
412145449b1SDimitry Andric   Stream->EmitRecordWithBlob(AbbrevNo, ArrayRef<uint64_t>{Record}, Blob);
413145449b1SDimitry Andric 
414145449b1SDimitry Andric   Stream->ExitBlock();
415145449b1SDimitry Andric }
416145449b1SDimitry Andric 
writeModule(const Module & M)417145449b1SDimitry Andric void BitcodeWriter::writeModule(const Module &M) {
418145449b1SDimitry Andric 
419145449b1SDimitry Andric   // The Mods vector is used by irsymtab::build, which requires non-const
420145449b1SDimitry Andric   // Modules in case it needs to materialize metadata. But the bitcode writer
421145449b1SDimitry Andric   // requires that the module is materialized, so we can cast to non-const here,
422145449b1SDimitry Andric   // after checking that it is in fact materialized.
423145449b1SDimitry Andric   assert(M.isMaterialized());
424145449b1SDimitry Andric   Mods.push_back(const_cast<Module *>(&M));
425145449b1SDimitry Andric 
426145449b1SDimitry Andric   DXILBitcodeWriter ModuleWriter(M, Buffer, StrtabBuilder, *Stream);
427145449b1SDimitry Andric   ModuleWriter.write();
428145449b1SDimitry Andric }
429145449b1SDimitry Andric 
430145449b1SDimitry Andric ////////////////////////////////////////////////////////////////////////////////
431145449b1SDimitry Andric /// Begin dxil::BitcodeWriterBase Implementation
432145449b1SDimitry Andric ////////////////////////////////////////////////////////////////////////////////
433145449b1SDimitry Andric 
getEncodedCastOpcode(unsigned Opcode)434145449b1SDimitry Andric unsigned DXILBitcodeWriter::getEncodedCastOpcode(unsigned Opcode) {
435145449b1SDimitry Andric   switch (Opcode) {
436145449b1SDimitry Andric   default:
437145449b1SDimitry Andric     llvm_unreachable("Unknown cast instruction!");
438145449b1SDimitry Andric   case Instruction::Trunc:
439145449b1SDimitry Andric     return bitc::CAST_TRUNC;
440145449b1SDimitry Andric   case Instruction::ZExt:
441145449b1SDimitry Andric     return bitc::CAST_ZEXT;
442145449b1SDimitry Andric   case Instruction::SExt:
443145449b1SDimitry Andric     return bitc::CAST_SEXT;
444145449b1SDimitry Andric   case Instruction::FPToUI:
445145449b1SDimitry Andric     return bitc::CAST_FPTOUI;
446145449b1SDimitry Andric   case Instruction::FPToSI:
447145449b1SDimitry Andric     return bitc::CAST_FPTOSI;
448145449b1SDimitry Andric   case Instruction::UIToFP:
449145449b1SDimitry Andric     return bitc::CAST_UITOFP;
450145449b1SDimitry Andric   case Instruction::SIToFP:
451145449b1SDimitry Andric     return bitc::CAST_SITOFP;
452145449b1SDimitry Andric   case Instruction::FPTrunc:
453145449b1SDimitry Andric     return bitc::CAST_FPTRUNC;
454145449b1SDimitry Andric   case Instruction::FPExt:
455145449b1SDimitry Andric     return bitc::CAST_FPEXT;
456145449b1SDimitry Andric   case Instruction::PtrToInt:
457145449b1SDimitry Andric     return bitc::CAST_PTRTOINT;
458145449b1SDimitry Andric   case Instruction::IntToPtr:
459145449b1SDimitry Andric     return bitc::CAST_INTTOPTR;
460145449b1SDimitry Andric   case Instruction::BitCast:
461145449b1SDimitry Andric     return bitc::CAST_BITCAST;
462145449b1SDimitry Andric   case Instruction::AddrSpaceCast:
463145449b1SDimitry Andric     return bitc::CAST_ADDRSPACECAST;
464145449b1SDimitry Andric   }
465145449b1SDimitry Andric }
466145449b1SDimitry Andric 
getEncodedUnaryOpcode(unsigned Opcode)467145449b1SDimitry Andric unsigned DXILBitcodeWriter::getEncodedUnaryOpcode(unsigned Opcode) {
468145449b1SDimitry Andric   switch (Opcode) {
469145449b1SDimitry Andric   default:
470145449b1SDimitry Andric     llvm_unreachable("Unknown binary instruction!");
471145449b1SDimitry Andric   case Instruction::FNeg:
472145449b1SDimitry Andric     return bitc::UNOP_FNEG;
473145449b1SDimitry Andric   }
474145449b1SDimitry Andric }
475145449b1SDimitry Andric 
getEncodedBinaryOpcode(unsigned Opcode)476145449b1SDimitry Andric unsigned DXILBitcodeWriter::getEncodedBinaryOpcode(unsigned Opcode) {
477145449b1SDimitry Andric   switch (Opcode) {
478145449b1SDimitry Andric   default:
479145449b1SDimitry Andric     llvm_unreachable("Unknown binary instruction!");
480145449b1SDimitry Andric   case Instruction::Add:
481145449b1SDimitry Andric   case Instruction::FAdd:
482145449b1SDimitry Andric     return bitc::BINOP_ADD;
483145449b1SDimitry Andric   case Instruction::Sub:
484145449b1SDimitry Andric   case Instruction::FSub:
485145449b1SDimitry Andric     return bitc::BINOP_SUB;
486145449b1SDimitry Andric   case Instruction::Mul:
487145449b1SDimitry Andric   case Instruction::FMul:
488145449b1SDimitry Andric     return bitc::BINOP_MUL;
489145449b1SDimitry Andric   case Instruction::UDiv:
490145449b1SDimitry Andric     return bitc::BINOP_UDIV;
491145449b1SDimitry Andric   case Instruction::FDiv:
492145449b1SDimitry Andric   case Instruction::SDiv:
493145449b1SDimitry Andric     return bitc::BINOP_SDIV;
494145449b1SDimitry Andric   case Instruction::URem:
495145449b1SDimitry Andric     return bitc::BINOP_UREM;
496145449b1SDimitry Andric   case Instruction::FRem:
497145449b1SDimitry Andric   case Instruction::SRem:
498145449b1SDimitry Andric     return bitc::BINOP_SREM;
499145449b1SDimitry Andric   case Instruction::Shl:
500145449b1SDimitry Andric     return bitc::BINOP_SHL;
501145449b1SDimitry Andric   case Instruction::LShr:
502145449b1SDimitry Andric     return bitc::BINOP_LSHR;
503145449b1SDimitry Andric   case Instruction::AShr:
504145449b1SDimitry Andric     return bitc::BINOP_ASHR;
505145449b1SDimitry Andric   case Instruction::And:
506145449b1SDimitry Andric     return bitc::BINOP_AND;
507145449b1SDimitry Andric   case Instruction::Or:
508145449b1SDimitry Andric     return bitc::BINOP_OR;
509145449b1SDimitry Andric   case Instruction::Xor:
510145449b1SDimitry Andric     return bitc::BINOP_XOR;
511145449b1SDimitry Andric   }
512145449b1SDimitry Andric }
513145449b1SDimitry Andric 
getTypeID(Type * T,const Value * V)514145449b1SDimitry Andric unsigned DXILBitcodeWriter::getTypeID(Type *T, const Value *V) {
5157fa27ce4SDimitry Andric   if (!T->isPointerTy() &&
516e3b55780SDimitry Andric       // For Constant, always check PointerMap to make sure OpaquePointer in
517e3b55780SDimitry Andric       // things like constant struct/array works.
518e3b55780SDimitry Andric       (!V || !isa<Constant>(V)))
519145449b1SDimitry Andric     return VE.getTypeID(T);
520145449b1SDimitry Andric   auto It = PointerMap.find(V);
521145449b1SDimitry Andric   if (It != PointerMap.end())
522145449b1SDimitry Andric     return VE.getTypeID(It->second);
523e3b55780SDimitry Andric   // For Constant, return T when cannot find in PointerMap.
524e3b55780SDimitry Andric   // FIXME: support ConstantPointerNull which could map to more than one
525e3b55780SDimitry Andric   // TypedPointerType.
526e3b55780SDimitry Andric   // See https://github.com/llvm/llvm-project/issues/57942.
527e3b55780SDimitry Andric   if (V && isa<Constant>(V) && !isa<ConstantPointerNull>(V))
528e3b55780SDimitry Andric     return VE.getTypeID(T);
529145449b1SDimitry Andric   return VE.getTypeID(I8PtrTy);
530145449b1SDimitry Andric }
531145449b1SDimitry Andric 
getGlobalObjectValueTypeID(Type * T,const GlobalObject * G)532e3b55780SDimitry Andric unsigned DXILBitcodeWriter::getGlobalObjectValueTypeID(Type *T,
533e3b55780SDimitry Andric                                                        const GlobalObject *G) {
534e3b55780SDimitry Andric   auto It = PointerMap.find(G);
535e3b55780SDimitry Andric   if (It != PointerMap.end()) {
536e3b55780SDimitry Andric     TypedPointerType *PtrTy = cast<TypedPointerType>(It->second);
537e3b55780SDimitry Andric     return VE.getTypeID(PtrTy->getElementType());
538e3b55780SDimitry Andric   }
539145449b1SDimitry Andric   return VE.getTypeID(T);
540145449b1SDimitry Andric }
541145449b1SDimitry Andric 
getEncodedRMWOperation(AtomicRMWInst::BinOp Op)542145449b1SDimitry Andric unsigned DXILBitcodeWriter::getEncodedRMWOperation(AtomicRMWInst::BinOp Op) {
543145449b1SDimitry Andric   switch (Op) {
544145449b1SDimitry Andric   default:
545145449b1SDimitry Andric     llvm_unreachable("Unknown RMW operation!");
546145449b1SDimitry Andric   case AtomicRMWInst::Xchg:
547145449b1SDimitry Andric     return bitc::RMW_XCHG;
548145449b1SDimitry Andric   case AtomicRMWInst::Add:
549145449b1SDimitry Andric     return bitc::RMW_ADD;
550145449b1SDimitry Andric   case AtomicRMWInst::Sub:
551145449b1SDimitry Andric     return bitc::RMW_SUB;
552145449b1SDimitry Andric   case AtomicRMWInst::And:
553145449b1SDimitry Andric     return bitc::RMW_AND;
554145449b1SDimitry Andric   case AtomicRMWInst::Nand:
555145449b1SDimitry Andric     return bitc::RMW_NAND;
556145449b1SDimitry Andric   case AtomicRMWInst::Or:
557145449b1SDimitry Andric     return bitc::RMW_OR;
558145449b1SDimitry Andric   case AtomicRMWInst::Xor:
559145449b1SDimitry Andric     return bitc::RMW_XOR;
560145449b1SDimitry Andric   case AtomicRMWInst::Max:
561145449b1SDimitry Andric     return bitc::RMW_MAX;
562145449b1SDimitry Andric   case AtomicRMWInst::Min:
563145449b1SDimitry Andric     return bitc::RMW_MIN;
564145449b1SDimitry Andric   case AtomicRMWInst::UMax:
565145449b1SDimitry Andric     return bitc::RMW_UMAX;
566145449b1SDimitry Andric   case AtomicRMWInst::UMin:
567145449b1SDimitry Andric     return bitc::RMW_UMIN;
568145449b1SDimitry Andric   case AtomicRMWInst::FAdd:
569145449b1SDimitry Andric     return bitc::RMW_FADD;
570145449b1SDimitry Andric   case AtomicRMWInst::FSub:
571145449b1SDimitry Andric     return bitc::RMW_FSUB;
5721f917f69SDimitry Andric   case AtomicRMWInst::FMax:
5731f917f69SDimitry Andric     return bitc::RMW_FMAX;
5741f917f69SDimitry Andric   case AtomicRMWInst::FMin:
5751f917f69SDimitry Andric     return bitc::RMW_FMIN;
576145449b1SDimitry Andric   }
577145449b1SDimitry Andric }
578145449b1SDimitry Andric 
getEncodedOrdering(AtomicOrdering Ordering)579145449b1SDimitry Andric unsigned DXILBitcodeWriter::getEncodedOrdering(AtomicOrdering Ordering) {
580145449b1SDimitry Andric   switch (Ordering) {
581145449b1SDimitry Andric   case AtomicOrdering::NotAtomic:
582145449b1SDimitry Andric     return bitc::ORDERING_NOTATOMIC;
583145449b1SDimitry Andric   case AtomicOrdering::Unordered:
584145449b1SDimitry Andric     return bitc::ORDERING_UNORDERED;
585145449b1SDimitry Andric   case AtomicOrdering::Monotonic:
586145449b1SDimitry Andric     return bitc::ORDERING_MONOTONIC;
587145449b1SDimitry Andric   case AtomicOrdering::Acquire:
588145449b1SDimitry Andric     return bitc::ORDERING_ACQUIRE;
589145449b1SDimitry Andric   case AtomicOrdering::Release:
590145449b1SDimitry Andric     return bitc::ORDERING_RELEASE;
591145449b1SDimitry Andric   case AtomicOrdering::AcquireRelease:
592145449b1SDimitry Andric     return bitc::ORDERING_ACQREL;
593145449b1SDimitry Andric   case AtomicOrdering::SequentiallyConsistent:
594145449b1SDimitry Andric     return bitc::ORDERING_SEQCST;
595145449b1SDimitry Andric   }
596145449b1SDimitry Andric   llvm_unreachable("Invalid ordering");
597145449b1SDimitry Andric }
598145449b1SDimitry Andric 
writeStringRecord(BitstreamWriter & Stream,unsigned Code,StringRef Str,unsigned AbbrevToUse)599145449b1SDimitry Andric void DXILBitcodeWriter::writeStringRecord(BitstreamWriter &Stream,
600145449b1SDimitry Andric                                           unsigned Code, StringRef Str,
601145449b1SDimitry Andric                                           unsigned AbbrevToUse) {
602145449b1SDimitry Andric   SmallVector<unsigned, 64> Vals;
603145449b1SDimitry Andric 
604145449b1SDimitry Andric   // Code: [strchar x N]
605145449b1SDimitry Andric   for (char C : Str) {
606145449b1SDimitry Andric     if (AbbrevToUse && !BitCodeAbbrevOp::isChar6(C))
607145449b1SDimitry Andric       AbbrevToUse = 0;
608145449b1SDimitry Andric     Vals.push_back(C);
609145449b1SDimitry Andric   }
610145449b1SDimitry Andric 
611145449b1SDimitry Andric   // Emit the finished record.
612145449b1SDimitry Andric   Stream.EmitRecord(Code, Vals, AbbrevToUse);
613145449b1SDimitry Andric }
614145449b1SDimitry Andric 
getAttrKindEncoding(Attribute::AttrKind Kind)615145449b1SDimitry Andric uint64_t DXILBitcodeWriter::getAttrKindEncoding(Attribute::AttrKind Kind) {
616145449b1SDimitry Andric   switch (Kind) {
617145449b1SDimitry Andric   case Attribute::Alignment:
618145449b1SDimitry Andric     return bitc::ATTR_KIND_ALIGNMENT;
619145449b1SDimitry Andric   case Attribute::AlwaysInline:
620145449b1SDimitry Andric     return bitc::ATTR_KIND_ALWAYS_INLINE;
621145449b1SDimitry Andric   case Attribute::Builtin:
622145449b1SDimitry Andric     return bitc::ATTR_KIND_BUILTIN;
623145449b1SDimitry Andric   case Attribute::ByVal:
624145449b1SDimitry Andric     return bitc::ATTR_KIND_BY_VAL;
625145449b1SDimitry Andric   case Attribute::Convergent:
626145449b1SDimitry Andric     return bitc::ATTR_KIND_CONVERGENT;
627145449b1SDimitry Andric   case Attribute::InAlloca:
628145449b1SDimitry Andric     return bitc::ATTR_KIND_IN_ALLOCA;
629145449b1SDimitry Andric   case Attribute::Cold:
630145449b1SDimitry Andric     return bitc::ATTR_KIND_COLD;
631145449b1SDimitry Andric   case Attribute::InlineHint:
632145449b1SDimitry Andric     return bitc::ATTR_KIND_INLINE_HINT;
633145449b1SDimitry Andric   case Attribute::InReg:
634145449b1SDimitry Andric     return bitc::ATTR_KIND_IN_REG;
635145449b1SDimitry Andric   case Attribute::JumpTable:
636145449b1SDimitry Andric     return bitc::ATTR_KIND_JUMP_TABLE;
637145449b1SDimitry Andric   case Attribute::MinSize:
638145449b1SDimitry Andric     return bitc::ATTR_KIND_MIN_SIZE;
639145449b1SDimitry Andric   case Attribute::Naked:
640145449b1SDimitry Andric     return bitc::ATTR_KIND_NAKED;
641145449b1SDimitry Andric   case Attribute::Nest:
642145449b1SDimitry Andric     return bitc::ATTR_KIND_NEST;
643145449b1SDimitry Andric   case Attribute::NoAlias:
644145449b1SDimitry Andric     return bitc::ATTR_KIND_NO_ALIAS;
645145449b1SDimitry Andric   case Attribute::NoBuiltin:
646145449b1SDimitry Andric     return bitc::ATTR_KIND_NO_BUILTIN;
647145449b1SDimitry Andric   case Attribute::NoCapture:
648145449b1SDimitry Andric     return bitc::ATTR_KIND_NO_CAPTURE;
649145449b1SDimitry Andric   case Attribute::NoDuplicate:
650145449b1SDimitry Andric     return bitc::ATTR_KIND_NO_DUPLICATE;
651145449b1SDimitry Andric   case Attribute::NoImplicitFloat:
652145449b1SDimitry Andric     return bitc::ATTR_KIND_NO_IMPLICIT_FLOAT;
653145449b1SDimitry Andric   case Attribute::NoInline:
654145449b1SDimitry Andric     return bitc::ATTR_KIND_NO_INLINE;
655145449b1SDimitry Andric   case Attribute::NonLazyBind:
656145449b1SDimitry Andric     return bitc::ATTR_KIND_NON_LAZY_BIND;
657145449b1SDimitry Andric   case Attribute::NonNull:
658145449b1SDimitry Andric     return bitc::ATTR_KIND_NON_NULL;
659145449b1SDimitry Andric   case Attribute::Dereferenceable:
660145449b1SDimitry Andric     return bitc::ATTR_KIND_DEREFERENCEABLE;
661145449b1SDimitry Andric   case Attribute::DereferenceableOrNull:
662145449b1SDimitry Andric     return bitc::ATTR_KIND_DEREFERENCEABLE_OR_NULL;
663145449b1SDimitry Andric   case Attribute::NoRedZone:
664145449b1SDimitry Andric     return bitc::ATTR_KIND_NO_RED_ZONE;
665145449b1SDimitry Andric   case Attribute::NoReturn:
666145449b1SDimitry Andric     return bitc::ATTR_KIND_NO_RETURN;
667145449b1SDimitry Andric   case Attribute::NoUnwind:
668145449b1SDimitry Andric     return bitc::ATTR_KIND_NO_UNWIND;
669145449b1SDimitry Andric   case Attribute::OptimizeForSize:
670145449b1SDimitry Andric     return bitc::ATTR_KIND_OPTIMIZE_FOR_SIZE;
671145449b1SDimitry Andric   case Attribute::OptimizeNone:
672145449b1SDimitry Andric     return bitc::ATTR_KIND_OPTIMIZE_NONE;
673145449b1SDimitry Andric   case Attribute::ReadNone:
674145449b1SDimitry Andric     return bitc::ATTR_KIND_READ_NONE;
675145449b1SDimitry Andric   case Attribute::ReadOnly:
676145449b1SDimitry Andric     return bitc::ATTR_KIND_READ_ONLY;
677145449b1SDimitry Andric   case Attribute::Returned:
678145449b1SDimitry Andric     return bitc::ATTR_KIND_RETURNED;
679145449b1SDimitry Andric   case Attribute::ReturnsTwice:
680145449b1SDimitry Andric     return bitc::ATTR_KIND_RETURNS_TWICE;
681145449b1SDimitry Andric   case Attribute::SExt:
682145449b1SDimitry Andric     return bitc::ATTR_KIND_S_EXT;
683145449b1SDimitry Andric   case Attribute::StackAlignment:
684145449b1SDimitry Andric     return bitc::ATTR_KIND_STACK_ALIGNMENT;
685145449b1SDimitry Andric   case Attribute::StackProtect:
686145449b1SDimitry Andric     return bitc::ATTR_KIND_STACK_PROTECT;
687145449b1SDimitry Andric   case Attribute::StackProtectReq:
688145449b1SDimitry Andric     return bitc::ATTR_KIND_STACK_PROTECT_REQ;
689145449b1SDimitry Andric   case Attribute::StackProtectStrong:
690145449b1SDimitry Andric     return bitc::ATTR_KIND_STACK_PROTECT_STRONG;
691145449b1SDimitry Andric   case Attribute::SafeStack:
692145449b1SDimitry Andric     return bitc::ATTR_KIND_SAFESTACK;
693145449b1SDimitry Andric   case Attribute::StructRet:
694145449b1SDimitry Andric     return bitc::ATTR_KIND_STRUCT_RET;
695145449b1SDimitry Andric   case Attribute::SanitizeAddress:
696145449b1SDimitry Andric     return bitc::ATTR_KIND_SANITIZE_ADDRESS;
697145449b1SDimitry Andric   case Attribute::SanitizeThread:
698145449b1SDimitry Andric     return bitc::ATTR_KIND_SANITIZE_THREAD;
699145449b1SDimitry Andric   case Attribute::SanitizeMemory:
700145449b1SDimitry Andric     return bitc::ATTR_KIND_SANITIZE_MEMORY;
701145449b1SDimitry Andric   case Attribute::UWTable:
702145449b1SDimitry Andric     return bitc::ATTR_KIND_UW_TABLE;
703145449b1SDimitry Andric   case Attribute::ZExt:
704145449b1SDimitry Andric     return bitc::ATTR_KIND_Z_EXT;
705145449b1SDimitry Andric   case Attribute::EndAttrKinds:
706145449b1SDimitry Andric     llvm_unreachable("Can not encode end-attribute kinds marker.");
707145449b1SDimitry Andric   case Attribute::None:
708145449b1SDimitry Andric     llvm_unreachable("Can not encode none-attribute.");
709145449b1SDimitry Andric   case Attribute::EmptyKey:
710145449b1SDimitry Andric   case Attribute::TombstoneKey:
711145449b1SDimitry Andric     llvm_unreachable("Trying to encode EmptyKey/TombstoneKey");
712145449b1SDimitry Andric   default:
713145449b1SDimitry Andric     llvm_unreachable("Trying to encode attribute not supported by DXIL. These "
714145449b1SDimitry Andric                      "should be stripped in DXILPrepare");
715145449b1SDimitry Andric   }
716145449b1SDimitry Andric 
717145449b1SDimitry Andric   llvm_unreachable("Trying to encode unknown attribute");
718145449b1SDimitry Andric }
719145449b1SDimitry Andric 
emitSignedInt64(SmallVectorImpl<uint64_t> & Vals,uint64_t V)720145449b1SDimitry Andric void DXILBitcodeWriter::emitSignedInt64(SmallVectorImpl<uint64_t> &Vals,
721145449b1SDimitry Andric                                         uint64_t V) {
722145449b1SDimitry Andric   if ((int64_t)V >= 0)
723145449b1SDimitry Andric     Vals.push_back(V << 1);
724145449b1SDimitry Andric   else
725145449b1SDimitry Andric     Vals.push_back((-V << 1) | 1);
726145449b1SDimitry Andric }
727145449b1SDimitry Andric 
emitWideAPInt(SmallVectorImpl<uint64_t> & Vals,const APInt & A)728145449b1SDimitry Andric void DXILBitcodeWriter::emitWideAPInt(SmallVectorImpl<uint64_t> &Vals,
729145449b1SDimitry Andric                                       const APInt &A) {
730145449b1SDimitry Andric   // We have an arbitrary precision integer value to write whose
731145449b1SDimitry Andric   // bit width is > 64. However, in canonical unsigned integer
732145449b1SDimitry Andric   // format it is likely that the high bits are going to be zero.
733145449b1SDimitry Andric   // So, we only write the number of active words.
734145449b1SDimitry Andric   unsigned NumWords = A.getActiveWords();
735145449b1SDimitry Andric   const uint64_t *RawData = A.getRawData();
736145449b1SDimitry Andric   for (unsigned i = 0; i < NumWords; i++)
737145449b1SDimitry Andric     emitSignedInt64(Vals, RawData[i]);
738145449b1SDimitry Andric }
739145449b1SDimitry Andric 
getOptimizationFlags(const Value * V)740145449b1SDimitry Andric uint64_t DXILBitcodeWriter::getOptimizationFlags(const Value *V) {
741145449b1SDimitry Andric   uint64_t Flags = 0;
742145449b1SDimitry Andric 
743145449b1SDimitry Andric   if (const auto *OBO = dyn_cast<OverflowingBinaryOperator>(V)) {
744145449b1SDimitry Andric     if (OBO->hasNoSignedWrap())
745145449b1SDimitry Andric       Flags |= 1 << bitc::OBO_NO_SIGNED_WRAP;
746145449b1SDimitry Andric     if (OBO->hasNoUnsignedWrap())
747145449b1SDimitry Andric       Flags |= 1 << bitc::OBO_NO_UNSIGNED_WRAP;
748145449b1SDimitry Andric   } else if (const auto *PEO = dyn_cast<PossiblyExactOperator>(V)) {
749145449b1SDimitry Andric     if (PEO->isExact())
750145449b1SDimitry Andric       Flags |= 1 << bitc::PEO_EXACT;
751145449b1SDimitry Andric   } else if (const auto *FPMO = dyn_cast<FPMathOperator>(V)) {
752145449b1SDimitry Andric     if (FPMO->hasAllowReassoc())
753145449b1SDimitry Andric       Flags |= bitc::AllowReassoc;
754145449b1SDimitry Andric     if (FPMO->hasNoNaNs())
755145449b1SDimitry Andric       Flags |= bitc::NoNaNs;
756145449b1SDimitry Andric     if (FPMO->hasNoInfs())
757145449b1SDimitry Andric       Flags |= bitc::NoInfs;
758145449b1SDimitry Andric     if (FPMO->hasNoSignedZeros())
759145449b1SDimitry Andric       Flags |= bitc::NoSignedZeros;
760145449b1SDimitry Andric     if (FPMO->hasAllowReciprocal())
761145449b1SDimitry Andric       Flags |= bitc::AllowReciprocal;
762145449b1SDimitry Andric     if (FPMO->hasAllowContract())
763145449b1SDimitry Andric       Flags |= bitc::AllowContract;
764145449b1SDimitry Andric     if (FPMO->hasApproxFunc())
765145449b1SDimitry Andric       Flags |= bitc::ApproxFunc;
766145449b1SDimitry Andric   }
767145449b1SDimitry Andric 
768145449b1SDimitry Andric   return Flags;
769145449b1SDimitry Andric }
770145449b1SDimitry Andric 
771145449b1SDimitry Andric unsigned
getEncodedLinkage(const GlobalValue::LinkageTypes Linkage)772145449b1SDimitry Andric DXILBitcodeWriter::getEncodedLinkage(const GlobalValue::LinkageTypes Linkage) {
773145449b1SDimitry Andric   switch (Linkage) {
774145449b1SDimitry Andric   case GlobalValue::ExternalLinkage:
775145449b1SDimitry Andric     return 0;
776145449b1SDimitry Andric   case GlobalValue::WeakAnyLinkage:
777145449b1SDimitry Andric     return 16;
778145449b1SDimitry Andric   case GlobalValue::AppendingLinkage:
779145449b1SDimitry Andric     return 2;
780145449b1SDimitry Andric   case GlobalValue::InternalLinkage:
781145449b1SDimitry Andric     return 3;
782145449b1SDimitry Andric   case GlobalValue::LinkOnceAnyLinkage:
783145449b1SDimitry Andric     return 18;
784145449b1SDimitry Andric   case GlobalValue::ExternalWeakLinkage:
785145449b1SDimitry Andric     return 7;
786145449b1SDimitry Andric   case GlobalValue::CommonLinkage:
787145449b1SDimitry Andric     return 8;
788145449b1SDimitry Andric   case GlobalValue::PrivateLinkage:
789145449b1SDimitry Andric     return 9;
790145449b1SDimitry Andric   case GlobalValue::WeakODRLinkage:
791145449b1SDimitry Andric     return 17;
792145449b1SDimitry Andric   case GlobalValue::LinkOnceODRLinkage:
793145449b1SDimitry Andric     return 19;
794145449b1SDimitry Andric   case GlobalValue::AvailableExternallyLinkage:
795145449b1SDimitry Andric     return 12;
796145449b1SDimitry Andric   }
797145449b1SDimitry Andric   llvm_unreachable("Invalid linkage");
798145449b1SDimitry Andric }
799145449b1SDimitry Andric 
getEncodedLinkage(const GlobalValue & GV)800145449b1SDimitry Andric unsigned DXILBitcodeWriter::getEncodedLinkage(const GlobalValue &GV) {
801145449b1SDimitry Andric   return getEncodedLinkage(GV.getLinkage());
802145449b1SDimitry Andric }
803145449b1SDimitry Andric 
getEncodedVisibility(const GlobalValue & GV)804145449b1SDimitry Andric unsigned DXILBitcodeWriter::getEncodedVisibility(const GlobalValue &GV) {
805145449b1SDimitry Andric   switch (GV.getVisibility()) {
806145449b1SDimitry Andric   case GlobalValue::DefaultVisibility:
807145449b1SDimitry Andric     return 0;
808145449b1SDimitry Andric   case GlobalValue::HiddenVisibility:
809145449b1SDimitry Andric     return 1;
810145449b1SDimitry Andric   case GlobalValue::ProtectedVisibility:
811145449b1SDimitry Andric     return 2;
812145449b1SDimitry Andric   }
813145449b1SDimitry Andric   llvm_unreachable("Invalid visibility");
814145449b1SDimitry Andric }
815145449b1SDimitry Andric 
getEncodedDLLStorageClass(const GlobalValue & GV)816145449b1SDimitry Andric unsigned DXILBitcodeWriter::getEncodedDLLStorageClass(const GlobalValue &GV) {
817145449b1SDimitry Andric   switch (GV.getDLLStorageClass()) {
818145449b1SDimitry Andric   case GlobalValue::DefaultStorageClass:
819145449b1SDimitry Andric     return 0;
820145449b1SDimitry Andric   case GlobalValue::DLLImportStorageClass:
821145449b1SDimitry Andric     return 1;
822145449b1SDimitry Andric   case GlobalValue::DLLExportStorageClass:
823145449b1SDimitry Andric     return 2;
824145449b1SDimitry Andric   }
825145449b1SDimitry Andric   llvm_unreachable("Invalid DLL storage class");
826145449b1SDimitry Andric }
827145449b1SDimitry Andric 
getEncodedThreadLocalMode(const GlobalValue & GV)828145449b1SDimitry Andric unsigned DXILBitcodeWriter::getEncodedThreadLocalMode(const GlobalValue &GV) {
829145449b1SDimitry Andric   switch (GV.getThreadLocalMode()) {
830145449b1SDimitry Andric   case GlobalVariable::NotThreadLocal:
831145449b1SDimitry Andric     return 0;
832145449b1SDimitry Andric   case GlobalVariable::GeneralDynamicTLSModel:
833145449b1SDimitry Andric     return 1;
834145449b1SDimitry Andric   case GlobalVariable::LocalDynamicTLSModel:
835145449b1SDimitry Andric     return 2;
836145449b1SDimitry Andric   case GlobalVariable::InitialExecTLSModel:
837145449b1SDimitry Andric     return 3;
838145449b1SDimitry Andric   case GlobalVariable::LocalExecTLSModel:
839145449b1SDimitry Andric     return 4;
840145449b1SDimitry Andric   }
841145449b1SDimitry Andric   llvm_unreachable("Invalid TLS model");
842145449b1SDimitry Andric }
843145449b1SDimitry Andric 
getEncodedComdatSelectionKind(const Comdat & C)844145449b1SDimitry Andric unsigned DXILBitcodeWriter::getEncodedComdatSelectionKind(const Comdat &C) {
845145449b1SDimitry Andric   switch (C.getSelectionKind()) {
846145449b1SDimitry Andric   case Comdat::Any:
847145449b1SDimitry Andric     return bitc::COMDAT_SELECTION_KIND_ANY;
848145449b1SDimitry Andric   case Comdat::ExactMatch:
849145449b1SDimitry Andric     return bitc::COMDAT_SELECTION_KIND_EXACT_MATCH;
850145449b1SDimitry Andric   case Comdat::Largest:
851145449b1SDimitry Andric     return bitc::COMDAT_SELECTION_KIND_LARGEST;
852145449b1SDimitry Andric   case Comdat::NoDeduplicate:
853145449b1SDimitry Andric     return bitc::COMDAT_SELECTION_KIND_NO_DUPLICATES;
854145449b1SDimitry Andric   case Comdat::SameSize:
855145449b1SDimitry Andric     return bitc::COMDAT_SELECTION_KIND_SAME_SIZE;
856145449b1SDimitry Andric   }
857145449b1SDimitry Andric   llvm_unreachable("Invalid selection kind");
858145449b1SDimitry Andric }
859145449b1SDimitry Andric 
860145449b1SDimitry Andric ////////////////////////////////////////////////////////////////////////////////
861145449b1SDimitry Andric /// Begin DXILBitcodeWriter Implementation
862145449b1SDimitry Andric ////////////////////////////////////////////////////////////////////////////////
863145449b1SDimitry Andric 
writeAttributeGroupTable()864145449b1SDimitry Andric void DXILBitcodeWriter::writeAttributeGroupTable() {
865145449b1SDimitry Andric   const std::vector<ValueEnumerator::IndexAndAttrSet> &AttrGrps =
866145449b1SDimitry Andric       VE.getAttributeGroups();
867145449b1SDimitry Andric   if (AttrGrps.empty())
868145449b1SDimitry Andric     return;
869145449b1SDimitry Andric 
870145449b1SDimitry Andric   Stream.EnterSubblock(bitc::PARAMATTR_GROUP_BLOCK_ID, 3);
871145449b1SDimitry Andric 
872145449b1SDimitry Andric   SmallVector<uint64_t, 64> Record;
873145449b1SDimitry Andric   for (ValueEnumerator::IndexAndAttrSet Pair : AttrGrps) {
874145449b1SDimitry Andric     unsigned AttrListIndex = Pair.first;
875145449b1SDimitry Andric     AttributeSet AS = Pair.second;
876145449b1SDimitry Andric     Record.push_back(VE.getAttributeGroupID(Pair));
877145449b1SDimitry Andric     Record.push_back(AttrListIndex);
878145449b1SDimitry Andric 
879145449b1SDimitry Andric     for (Attribute Attr : AS) {
880145449b1SDimitry Andric       if (Attr.isEnumAttribute()) {
881145449b1SDimitry Andric         uint64_t Val = getAttrKindEncoding(Attr.getKindAsEnum());
882145449b1SDimitry Andric         assert(Val <= bitc::ATTR_KIND_ARGMEMONLY &&
883145449b1SDimitry Andric                "DXIL does not support attributes above ATTR_KIND_ARGMEMONLY");
884145449b1SDimitry Andric         Record.push_back(0);
885145449b1SDimitry Andric         Record.push_back(Val);
886145449b1SDimitry Andric       } else if (Attr.isIntAttribute()) {
887e3b55780SDimitry Andric         if (Attr.getKindAsEnum() == Attribute::AttrKind::Memory) {
888e3b55780SDimitry Andric           MemoryEffects ME = Attr.getMemoryEffects();
889e3b55780SDimitry Andric           if (ME.doesNotAccessMemory()) {
890e3b55780SDimitry Andric             Record.push_back(0);
891e3b55780SDimitry Andric             Record.push_back(bitc::ATTR_KIND_READ_NONE);
892e3b55780SDimitry Andric           } else {
893e3b55780SDimitry Andric             if (ME.onlyReadsMemory()) {
894e3b55780SDimitry Andric               Record.push_back(0);
895e3b55780SDimitry Andric               Record.push_back(bitc::ATTR_KIND_READ_ONLY);
896e3b55780SDimitry Andric             }
897e3b55780SDimitry Andric             if (ME.onlyAccessesArgPointees()) {
898e3b55780SDimitry Andric               Record.push_back(0);
899e3b55780SDimitry Andric               Record.push_back(bitc::ATTR_KIND_ARGMEMONLY);
900e3b55780SDimitry Andric             }
901e3b55780SDimitry Andric           }
902e3b55780SDimitry Andric         } else {
903145449b1SDimitry Andric           uint64_t Val = getAttrKindEncoding(Attr.getKindAsEnum());
904145449b1SDimitry Andric           assert(Val <= bitc::ATTR_KIND_ARGMEMONLY &&
905145449b1SDimitry Andric                  "DXIL does not support attributes above ATTR_KIND_ARGMEMONLY");
906145449b1SDimitry Andric           Record.push_back(1);
907145449b1SDimitry Andric           Record.push_back(Val);
908145449b1SDimitry Andric           Record.push_back(Attr.getValueAsInt());
909e3b55780SDimitry Andric         }
910145449b1SDimitry Andric       } else {
911145449b1SDimitry Andric         StringRef Kind = Attr.getKindAsString();
912145449b1SDimitry Andric         StringRef Val = Attr.getValueAsString();
913145449b1SDimitry Andric 
914145449b1SDimitry Andric         Record.push_back(Val.empty() ? 3 : 4);
915145449b1SDimitry Andric         Record.append(Kind.begin(), Kind.end());
916145449b1SDimitry Andric         Record.push_back(0);
917145449b1SDimitry Andric         if (!Val.empty()) {
918145449b1SDimitry Andric           Record.append(Val.begin(), Val.end());
919145449b1SDimitry Andric           Record.push_back(0);
920145449b1SDimitry Andric         }
921145449b1SDimitry Andric       }
922145449b1SDimitry Andric     }
923145449b1SDimitry Andric 
924145449b1SDimitry Andric     Stream.EmitRecord(bitc::PARAMATTR_GRP_CODE_ENTRY, Record);
925145449b1SDimitry Andric     Record.clear();
926145449b1SDimitry Andric   }
927145449b1SDimitry Andric 
928145449b1SDimitry Andric   Stream.ExitBlock();
929145449b1SDimitry Andric }
930145449b1SDimitry Andric 
writeAttributeTable()931145449b1SDimitry Andric void DXILBitcodeWriter::writeAttributeTable() {
932145449b1SDimitry Andric   const std::vector<AttributeList> &Attrs = VE.getAttributeLists();
933145449b1SDimitry Andric   if (Attrs.empty())
934145449b1SDimitry Andric     return;
935145449b1SDimitry Andric 
936145449b1SDimitry Andric   Stream.EnterSubblock(bitc::PARAMATTR_BLOCK_ID, 3);
937145449b1SDimitry Andric 
938145449b1SDimitry Andric   SmallVector<uint64_t, 64> Record;
93999aabd70SDimitry Andric   for (AttributeList AL : Attrs) {
940145449b1SDimitry Andric     for (unsigned i : AL.indexes()) {
941145449b1SDimitry Andric       AttributeSet AS = AL.getAttributes(i);
942145449b1SDimitry Andric       if (AS.hasAttributes())
943145449b1SDimitry Andric         Record.push_back(VE.getAttributeGroupID({i, AS}));
944145449b1SDimitry Andric     }
945145449b1SDimitry Andric 
946145449b1SDimitry Andric     Stream.EmitRecord(bitc::PARAMATTR_CODE_ENTRY, Record);
947145449b1SDimitry Andric     Record.clear();
948145449b1SDimitry Andric   }
949145449b1SDimitry Andric 
950145449b1SDimitry Andric   Stream.ExitBlock();
951145449b1SDimitry Andric }
952145449b1SDimitry Andric 
953145449b1SDimitry Andric /// WriteTypeTable - Write out the type table for a module.
writeTypeTable()954145449b1SDimitry Andric void DXILBitcodeWriter::writeTypeTable() {
955145449b1SDimitry Andric   const ValueEnumerator::TypeList &TypeList = VE.getTypes();
956145449b1SDimitry Andric 
957145449b1SDimitry Andric   Stream.EnterSubblock(bitc::TYPE_BLOCK_ID_NEW, 4 /*count from # abbrevs */);
958145449b1SDimitry Andric   SmallVector<uint64_t, 64> TypeVals;
959145449b1SDimitry Andric 
960ac9a064cSDimitry Andric   uint64_t NumBits = VE.computeBitsRequiredForTypeIndices();
961145449b1SDimitry Andric 
962145449b1SDimitry Andric   // Abbrev for TYPE_CODE_POINTER.
963145449b1SDimitry Andric   auto Abbv = std::make_shared<BitCodeAbbrev>();
964145449b1SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_POINTER));
965145449b1SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
966145449b1SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(0)); // Addrspace = 0
967145449b1SDimitry Andric   unsigned PtrAbbrev = Stream.EmitAbbrev(std::move(Abbv));
968145449b1SDimitry Andric 
969145449b1SDimitry Andric   // Abbrev for TYPE_CODE_FUNCTION.
970145449b1SDimitry Andric   Abbv = std::make_shared<BitCodeAbbrev>();
971145449b1SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_FUNCTION));
972145449b1SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // isvararg
973145449b1SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
974145449b1SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
975145449b1SDimitry Andric   unsigned FunctionAbbrev = Stream.EmitAbbrev(std::move(Abbv));
976145449b1SDimitry Andric 
977145449b1SDimitry Andric   // Abbrev for TYPE_CODE_STRUCT_ANON.
978145449b1SDimitry Andric   Abbv = std::make_shared<BitCodeAbbrev>();
979145449b1SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_STRUCT_ANON));
980145449b1SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // ispacked
981145449b1SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
982145449b1SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
983145449b1SDimitry Andric   unsigned StructAnonAbbrev = Stream.EmitAbbrev(std::move(Abbv));
984145449b1SDimitry Andric 
985145449b1SDimitry Andric   // Abbrev for TYPE_CODE_STRUCT_NAME.
986145449b1SDimitry Andric   Abbv = std::make_shared<BitCodeAbbrev>();
987145449b1SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_STRUCT_NAME));
988145449b1SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
989145449b1SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
990145449b1SDimitry Andric   unsigned StructNameAbbrev = Stream.EmitAbbrev(std::move(Abbv));
991145449b1SDimitry Andric 
992145449b1SDimitry Andric   // Abbrev for TYPE_CODE_STRUCT_NAMED.
993145449b1SDimitry Andric   Abbv = std::make_shared<BitCodeAbbrev>();
994145449b1SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_STRUCT_NAMED));
995145449b1SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // ispacked
996145449b1SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
997145449b1SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
998145449b1SDimitry Andric   unsigned StructNamedAbbrev = Stream.EmitAbbrev(std::move(Abbv));
999145449b1SDimitry Andric 
1000145449b1SDimitry Andric   // Abbrev for TYPE_CODE_ARRAY.
1001145449b1SDimitry Andric   Abbv = std::make_shared<BitCodeAbbrev>();
1002145449b1SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_ARRAY));
1003145449b1SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // size
1004145449b1SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
1005145449b1SDimitry Andric   unsigned ArrayAbbrev = Stream.EmitAbbrev(std::move(Abbv));
1006145449b1SDimitry Andric 
1007145449b1SDimitry Andric   // Emit an entry count so the reader can reserve space.
1008145449b1SDimitry Andric   TypeVals.push_back(TypeList.size());
1009145449b1SDimitry Andric   Stream.EmitRecord(bitc::TYPE_CODE_NUMENTRY, TypeVals);
1010145449b1SDimitry Andric   TypeVals.clear();
1011145449b1SDimitry Andric 
1012145449b1SDimitry Andric   // Loop over all of the types, emitting each in turn.
1013145449b1SDimitry Andric   for (Type *T : TypeList) {
1014145449b1SDimitry Andric     int AbbrevToUse = 0;
1015145449b1SDimitry Andric     unsigned Code = 0;
1016145449b1SDimitry Andric 
1017145449b1SDimitry Andric     switch (T->getTypeID()) {
1018145449b1SDimitry Andric     case Type::BFloatTyID:
1019145449b1SDimitry Andric     case Type::X86_AMXTyID:
1020145449b1SDimitry Andric     case Type::TokenTyID:
1021e3b55780SDimitry Andric     case Type::TargetExtTyID:
1022145449b1SDimitry Andric       llvm_unreachable("These should never be used!!!");
1023145449b1SDimitry Andric       break;
1024145449b1SDimitry Andric     case Type::VoidTyID:
1025145449b1SDimitry Andric       Code = bitc::TYPE_CODE_VOID;
1026145449b1SDimitry Andric       break;
1027145449b1SDimitry Andric     case Type::HalfTyID:
1028145449b1SDimitry Andric       Code = bitc::TYPE_CODE_HALF;
1029145449b1SDimitry Andric       break;
1030145449b1SDimitry Andric     case Type::FloatTyID:
1031145449b1SDimitry Andric       Code = bitc::TYPE_CODE_FLOAT;
1032145449b1SDimitry Andric       break;
1033145449b1SDimitry Andric     case Type::DoubleTyID:
1034145449b1SDimitry Andric       Code = bitc::TYPE_CODE_DOUBLE;
1035145449b1SDimitry Andric       break;
1036145449b1SDimitry Andric     case Type::X86_FP80TyID:
1037145449b1SDimitry Andric       Code = bitc::TYPE_CODE_X86_FP80;
1038145449b1SDimitry Andric       break;
1039145449b1SDimitry Andric     case Type::FP128TyID:
1040145449b1SDimitry Andric       Code = bitc::TYPE_CODE_FP128;
1041145449b1SDimitry Andric       break;
1042145449b1SDimitry Andric     case Type::PPC_FP128TyID:
1043145449b1SDimitry Andric       Code = bitc::TYPE_CODE_PPC_FP128;
1044145449b1SDimitry Andric       break;
1045145449b1SDimitry Andric     case Type::LabelTyID:
1046145449b1SDimitry Andric       Code = bitc::TYPE_CODE_LABEL;
1047145449b1SDimitry Andric       break;
1048145449b1SDimitry Andric     case Type::MetadataTyID:
1049145449b1SDimitry Andric       Code = bitc::TYPE_CODE_METADATA;
1050145449b1SDimitry Andric       break;
1051145449b1SDimitry Andric     case Type::X86_MMXTyID:
1052145449b1SDimitry Andric       Code = bitc::TYPE_CODE_X86_MMX;
1053145449b1SDimitry Andric       break;
1054145449b1SDimitry Andric     case Type::IntegerTyID:
1055145449b1SDimitry Andric       // INTEGER: [width]
1056145449b1SDimitry Andric       Code = bitc::TYPE_CODE_INTEGER;
1057145449b1SDimitry Andric       TypeVals.push_back(cast<IntegerType>(T)->getBitWidth());
1058145449b1SDimitry Andric       break;
1059e3b55780SDimitry Andric     case Type::TypedPointerTyID: {
1060145449b1SDimitry Andric       TypedPointerType *PTy = cast<TypedPointerType>(T);
1061145449b1SDimitry Andric       // POINTER: [pointee type, address space]
1062145449b1SDimitry Andric       Code = bitc::TYPE_CODE_POINTER;
1063145449b1SDimitry Andric       TypeVals.push_back(getTypeID(PTy->getElementType()));
1064145449b1SDimitry Andric       unsigned AddressSpace = PTy->getAddressSpace();
1065145449b1SDimitry Andric       TypeVals.push_back(AddressSpace);
1066145449b1SDimitry Andric       if (AddressSpace == 0)
1067145449b1SDimitry Andric         AbbrevToUse = PtrAbbrev;
1068145449b1SDimitry Andric       break;
1069145449b1SDimitry Andric     }
1070145449b1SDimitry Andric     case Type::PointerTyID: {
1071145449b1SDimitry Andric       // POINTER: [pointee type, address space]
10727fa27ce4SDimitry Andric       // Emitting an empty struct type for the pointer's type allows this to be
10737fa27ce4SDimitry Andric       // order-independent. Non-struct types must be emitted in bitcode before
10747fa27ce4SDimitry Andric       // they can be referenced.
1075145449b1SDimitry Andric       TypeVals.push_back(false);
1076145449b1SDimitry Andric       Code = bitc::TYPE_CODE_OPAQUE;
1077145449b1SDimitry Andric       writeStringRecord(Stream, bitc::TYPE_CODE_STRUCT_NAME,
1078145449b1SDimitry Andric                         "dxilOpaquePtrReservedName", StructNameAbbrev);
1079145449b1SDimitry Andric       break;
1080145449b1SDimitry Andric     }
1081145449b1SDimitry Andric     case Type::FunctionTyID: {
1082145449b1SDimitry Andric       FunctionType *FT = cast<FunctionType>(T);
1083145449b1SDimitry Andric       // FUNCTION: [isvararg, retty, paramty x N]
1084145449b1SDimitry Andric       Code = bitc::TYPE_CODE_FUNCTION;
1085145449b1SDimitry Andric       TypeVals.push_back(FT->isVarArg());
1086145449b1SDimitry Andric       TypeVals.push_back(getTypeID(FT->getReturnType()));
1087145449b1SDimitry Andric       for (Type *PTy : FT->params())
1088145449b1SDimitry Andric         TypeVals.push_back(getTypeID(PTy));
1089145449b1SDimitry Andric       AbbrevToUse = FunctionAbbrev;
1090145449b1SDimitry Andric       break;
1091145449b1SDimitry Andric     }
1092145449b1SDimitry Andric     case Type::StructTyID: {
1093145449b1SDimitry Andric       StructType *ST = cast<StructType>(T);
1094145449b1SDimitry Andric       // STRUCT: [ispacked, eltty x N]
1095145449b1SDimitry Andric       TypeVals.push_back(ST->isPacked());
1096145449b1SDimitry Andric       // Output all of the element types.
1097145449b1SDimitry Andric       for (Type *ElTy : ST->elements())
1098145449b1SDimitry Andric         TypeVals.push_back(getTypeID(ElTy));
1099145449b1SDimitry Andric 
1100145449b1SDimitry Andric       if (ST->isLiteral()) {
1101145449b1SDimitry Andric         Code = bitc::TYPE_CODE_STRUCT_ANON;
1102145449b1SDimitry Andric         AbbrevToUse = StructAnonAbbrev;
1103145449b1SDimitry Andric       } else {
1104145449b1SDimitry Andric         if (ST->isOpaque()) {
1105145449b1SDimitry Andric           Code = bitc::TYPE_CODE_OPAQUE;
1106145449b1SDimitry Andric         } else {
1107145449b1SDimitry Andric           Code = bitc::TYPE_CODE_STRUCT_NAMED;
1108145449b1SDimitry Andric           AbbrevToUse = StructNamedAbbrev;
1109145449b1SDimitry Andric         }
1110145449b1SDimitry Andric 
1111145449b1SDimitry Andric         // Emit the name if it is present.
1112145449b1SDimitry Andric         if (!ST->getName().empty())
1113145449b1SDimitry Andric           writeStringRecord(Stream, bitc::TYPE_CODE_STRUCT_NAME, ST->getName(),
1114145449b1SDimitry Andric                             StructNameAbbrev);
1115145449b1SDimitry Andric       }
1116145449b1SDimitry Andric       break;
1117145449b1SDimitry Andric     }
1118145449b1SDimitry Andric     case Type::ArrayTyID: {
1119145449b1SDimitry Andric       ArrayType *AT = cast<ArrayType>(T);
1120145449b1SDimitry Andric       // ARRAY: [numelts, eltty]
1121145449b1SDimitry Andric       Code = bitc::TYPE_CODE_ARRAY;
1122145449b1SDimitry Andric       TypeVals.push_back(AT->getNumElements());
1123145449b1SDimitry Andric       TypeVals.push_back(getTypeID(AT->getElementType()));
1124145449b1SDimitry Andric       AbbrevToUse = ArrayAbbrev;
1125145449b1SDimitry Andric       break;
1126145449b1SDimitry Andric     }
1127145449b1SDimitry Andric     case Type::FixedVectorTyID:
1128145449b1SDimitry Andric     case Type::ScalableVectorTyID: {
1129145449b1SDimitry Andric       VectorType *VT = cast<VectorType>(T);
1130145449b1SDimitry Andric       // VECTOR [numelts, eltty]
1131145449b1SDimitry Andric       Code = bitc::TYPE_CODE_VECTOR;
1132145449b1SDimitry Andric       TypeVals.push_back(VT->getElementCount().getKnownMinValue());
1133145449b1SDimitry Andric       TypeVals.push_back(getTypeID(VT->getElementType()));
1134145449b1SDimitry Andric       break;
1135145449b1SDimitry Andric     }
1136145449b1SDimitry Andric     }
1137145449b1SDimitry Andric 
1138145449b1SDimitry Andric     // Emit the finished record.
1139145449b1SDimitry Andric     Stream.EmitRecord(Code, TypeVals, AbbrevToUse);
1140145449b1SDimitry Andric     TypeVals.clear();
1141145449b1SDimitry Andric   }
1142145449b1SDimitry Andric 
1143145449b1SDimitry Andric   Stream.ExitBlock();
1144145449b1SDimitry Andric }
1145145449b1SDimitry Andric 
writeComdats()1146145449b1SDimitry Andric void DXILBitcodeWriter::writeComdats() {
1147145449b1SDimitry Andric   SmallVector<uint16_t, 64> Vals;
1148145449b1SDimitry Andric   for (const Comdat *C : VE.getComdats()) {
1149145449b1SDimitry Andric     // COMDAT: [selection_kind, name]
1150145449b1SDimitry Andric     Vals.push_back(getEncodedComdatSelectionKind(*C));
1151145449b1SDimitry Andric     size_t Size = C->getName().size();
1152145449b1SDimitry Andric     assert(isUInt<16>(Size));
1153145449b1SDimitry Andric     Vals.push_back(Size);
1154145449b1SDimitry Andric     for (char Chr : C->getName())
1155145449b1SDimitry Andric       Vals.push_back((unsigned char)Chr);
1156145449b1SDimitry Andric     Stream.EmitRecord(bitc::MODULE_CODE_COMDAT, Vals, /*AbbrevToUse=*/0);
1157145449b1SDimitry Andric     Vals.clear();
1158145449b1SDimitry Andric   }
1159145449b1SDimitry Andric }
1160145449b1SDimitry Andric 
writeValueSymbolTableForwardDecl()1161145449b1SDimitry Andric void DXILBitcodeWriter::writeValueSymbolTableForwardDecl() {}
1162145449b1SDimitry Andric 
1163145449b1SDimitry Andric /// Emit top-level description of module, including target triple, inline asm,
1164145449b1SDimitry Andric /// descriptors for global variables, and function prototype info.
1165145449b1SDimitry Andric /// Returns the bit offset to backpatch with the location of the real VST.
writeModuleInfo()1166145449b1SDimitry Andric void DXILBitcodeWriter::writeModuleInfo() {
1167145449b1SDimitry Andric   // Emit various pieces of data attached to a module.
1168145449b1SDimitry Andric   if (!M.getTargetTriple().empty())
1169145449b1SDimitry Andric     writeStringRecord(Stream, bitc::MODULE_CODE_TRIPLE, M.getTargetTriple(),
1170145449b1SDimitry Andric                       0 /*TODO*/);
1171145449b1SDimitry Andric   const std::string &DL = M.getDataLayoutStr();
1172145449b1SDimitry Andric   if (!DL.empty())
1173145449b1SDimitry Andric     writeStringRecord(Stream, bitc::MODULE_CODE_DATALAYOUT, DL, 0 /*TODO*/);
1174145449b1SDimitry Andric   if (!M.getModuleInlineAsm().empty())
1175145449b1SDimitry Andric     writeStringRecord(Stream, bitc::MODULE_CODE_ASM, M.getModuleInlineAsm(),
1176145449b1SDimitry Andric                       0 /*TODO*/);
1177145449b1SDimitry Andric 
1178145449b1SDimitry Andric   // Emit information about sections and GC, computing how many there are. Also
1179145449b1SDimitry Andric   // compute the maximum alignment value.
1180145449b1SDimitry Andric   std::map<std::string, unsigned> SectionMap;
1181145449b1SDimitry Andric   std::map<std::string, unsigned> GCMap;
1182145449b1SDimitry Andric   MaybeAlign MaxAlignment;
1183145449b1SDimitry Andric   unsigned MaxGlobalType = 0;
1184145449b1SDimitry Andric   const auto UpdateMaxAlignment = [&MaxAlignment](const MaybeAlign A) {
1185145449b1SDimitry Andric     if (A)
1186145449b1SDimitry Andric       MaxAlignment = !MaxAlignment ? *A : std::max(*MaxAlignment, *A);
1187145449b1SDimitry Andric   };
1188145449b1SDimitry Andric   for (const GlobalVariable &GV : M.globals()) {
1189145449b1SDimitry Andric     UpdateMaxAlignment(GV.getAlign());
1190e3b55780SDimitry Andric     // Use getGlobalObjectValueTypeID to look up the enumerated type ID for
1191e3b55780SDimitry Andric     // Global Variable types.
1192e3b55780SDimitry Andric     MaxGlobalType = std::max(
1193e3b55780SDimitry Andric         MaxGlobalType, getGlobalObjectValueTypeID(GV.getValueType(), &GV));
1194145449b1SDimitry Andric     if (GV.hasSection()) {
1195145449b1SDimitry Andric       // Give section names unique ID's.
1196145449b1SDimitry Andric       unsigned &Entry = SectionMap[std::string(GV.getSection())];
1197145449b1SDimitry Andric       if (!Entry) {
1198145449b1SDimitry Andric         writeStringRecord(Stream, bitc::MODULE_CODE_SECTIONNAME,
1199145449b1SDimitry Andric                           GV.getSection(), 0 /*TODO*/);
1200145449b1SDimitry Andric         Entry = SectionMap.size();
1201145449b1SDimitry Andric       }
1202145449b1SDimitry Andric     }
1203145449b1SDimitry Andric   }
1204145449b1SDimitry Andric   for (const Function &F : M) {
1205145449b1SDimitry Andric     UpdateMaxAlignment(F.getAlign());
1206145449b1SDimitry Andric     if (F.hasSection()) {
1207145449b1SDimitry Andric       // Give section names unique ID's.
1208145449b1SDimitry Andric       unsigned &Entry = SectionMap[std::string(F.getSection())];
1209145449b1SDimitry Andric       if (!Entry) {
1210145449b1SDimitry Andric         writeStringRecord(Stream, bitc::MODULE_CODE_SECTIONNAME, F.getSection(),
1211145449b1SDimitry Andric                           0 /*TODO*/);
1212145449b1SDimitry Andric         Entry = SectionMap.size();
1213145449b1SDimitry Andric       }
1214145449b1SDimitry Andric     }
1215145449b1SDimitry Andric     if (F.hasGC()) {
1216145449b1SDimitry Andric       // Same for GC names.
1217145449b1SDimitry Andric       unsigned &Entry = GCMap[F.getGC()];
1218145449b1SDimitry Andric       if (!Entry) {
1219145449b1SDimitry Andric         writeStringRecord(Stream, bitc::MODULE_CODE_GCNAME, F.getGC(),
1220145449b1SDimitry Andric                           0 /*TODO*/);
1221145449b1SDimitry Andric         Entry = GCMap.size();
1222145449b1SDimitry Andric       }
1223145449b1SDimitry Andric     }
1224145449b1SDimitry Andric   }
1225145449b1SDimitry Andric 
1226145449b1SDimitry Andric   // Emit abbrev for globals, now that we know # sections and max alignment.
1227145449b1SDimitry Andric   unsigned SimpleGVarAbbrev = 0;
1228145449b1SDimitry Andric   if (!M.global_empty()) {
1229145449b1SDimitry Andric     // Add an abbrev for common globals with no visibility or thread
1230145449b1SDimitry Andric     // localness.
1231145449b1SDimitry Andric     auto Abbv = std::make_shared<BitCodeAbbrev>();
1232145449b1SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(bitc::MODULE_CODE_GLOBALVAR));
1233145449b1SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
1234145449b1SDimitry Andric                               Log2_32_Ceil(MaxGlobalType + 1)));
1235145449b1SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));   // AddrSpace << 2
1236145449b1SDimitry Andric                                                            //| explicitType << 1
1237145449b1SDimitry Andric                                                            //| constant
1238145449b1SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));   // Initializer.
1239145449b1SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 5)); // Linkage.
1240145449b1SDimitry Andric     if (!MaxAlignment)                                     // Alignment.
1241145449b1SDimitry Andric       Abbv->Add(BitCodeAbbrevOp(0));
1242145449b1SDimitry Andric     else {
1243145449b1SDimitry Andric       unsigned MaxEncAlignment = getEncodedAlign(MaxAlignment);
1244145449b1SDimitry Andric       Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
1245145449b1SDimitry Andric                                 Log2_32_Ceil(MaxEncAlignment + 1)));
1246145449b1SDimitry Andric     }
1247145449b1SDimitry Andric     if (SectionMap.empty()) // Section.
1248145449b1SDimitry Andric       Abbv->Add(BitCodeAbbrevOp(0));
1249145449b1SDimitry Andric     else
1250145449b1SDimitry Andric       Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
1251145449b1SDimitry Andric                                 Log2_32_Ceil(SectionMap.size() + 1)));
1252145449b1SDimitry Andric     // Don't bother emitting vis + thread local.
1253145449b1SDimitry Andric     SimpleGVarAbbrev = Stream.EmitAbbrev(std::move(Abbv));
1254145449b1SDimitry Andric   }
1255145449b1SDimitry Andric 
1256145449b1SDimitry Andric   // Emit the global variable information.
1257145449b1SDimitry Andric   SmallVector<unsigned, 64> Vals;
1258145449b1SDimitry Andric   for (const GlobalVariable &GV : M.globals()) {
1259145449b1SDimitry Andric     unsigned AbbrevToUse = 0;
1260145449b1SDimitry Andric 
1261145449b1SDimitry Andric     // GLOBALVAR: [type, isconst, initid,
1262145449b1SDimitry Andric     //             linkage, alignment, section, visibility, threadlocal,
1263145449b1SDimitry Andric     //             unnamed_addr, externally_initialized, dllstorageclass,
1264145449b1SDimitry Andric     //             comdat]
1265e3b55780SDimitry Andric     Vals.push_back(getGlobalObjectValueTypeID(GV.getValueType(), &GV));
1266145449b1SDimitry Andric     Vals.push_back(
1267145449b1SDimitry Andric         GV.getType()->getAddressSpace() << 2 | 2 |
1268145449b1SDimitry Andric         (GV.isConstant() ? 1 : 0)); // HLSL Change - bitwise | was used with
1269145449b1SDimitry Andric                                     // unsigned int and bool
1270145449b1SDimitry Andric     Vals.push_back(
1271145449b1SDimitry Andric         GV.isDeclaration() ? 0 : (VE.getValueID(GV.getInitializer()) + 1));
1272145449b1SDimitry Andric     Vals.push_back(getEncodedLinkage(GV));
1273145449b1SDimitry Andric     Vals.push_back(getEncodedAlign(GV.getAlign()));
1274145449b1SDimitry Andric     Vals.push_back(GV.hasSection() ? SectionMap[std::string(GV.getSection())]
1275145449b1SDimitry Andric                                    : 0);
1276145449b1SDimitry Andric     if (GV.isThreadLocal() ||
1277145449b1SDimitry Andric         GV.getVisibility() != GlobalValue::DefaultVisibility ||
1278145449b1SDimitry Andric         GV.getUnnamedAddr() != GlobalValue::UnnamedAddr::None ||
1279145449b1SDimitry Andric         GV.isExternallyInitialized() ||
1280145449b1SDimitry Andric         GV.getDLLStorageClass() != GlobalValue::DefaultStorageClass ||
1281145449b1SDimitry Andric         GV.hasComdat()) {
1282145449b1SDimitry Andric       Vals.push_back(getEncodedVisibility(GV));
1283145449b1SDimitry Andric       Vals.push_back(getEncodedThreadLocalMode(GV));
1284145449b1SDimitry Andric       Vals.push_back(GV.getUnnamedAddr() != GlobalValue::UnnamedAddr::None);
1285145449b1SDimitry Andric       Vals.push_back(GV.isExternallyInitialized());
1286145449b1SDimitry Andric       Vals.push_back(getEncodedDLLStorageClass(GV));
1287145449b1SDimitry Andric       Vals.push_back(GV.hasComdat() ? VE.getComdatID(GV.getComdat()) : 0);
1288145449b1SDimitry Andric     } else {
1289145449b1SDimitry Andric       AbbrevToUse = SimpleGVarAbbrev;
1290145449b1SDimitry Andric     }
1291145449b1SDimitry Andric 
1292145449b1SDimitry Andric     Stream.EmitRecord(bitc::MODULE_CODE_GLOBALVAR, Vals, AbbrevToUse);
1293145449b1SDimitry Andric     Vals.clear();
1294145449b1SDimitry Andric   }
1295145449b1SDimitry Andric 
1296145449b1SDimitry Andric   // Emit the function proto information.
1297145449b1SDimitry Andric   for (const Function &F : M) {
1298145449b1SDimitry Andric     // FUNCTION:  [type, callingconv, isproto, linkage, paramattrs, alignment,
1299145449b1SDimitry Andric     //             section, visibility, gc, unnamed_addr, prologuedata,
1300145449b1SDimitry Andric     //             dllstorageclass, comdat, prefixdata, personalityfn]
1301e3b55780SDimitry Andric     Vals.push_back(getGlobalObjectValueTypeID(F.getFunctionType(), &F));
1302145449b1SDimitry Andric     Vals.push_back(F.getCallingConv());
1303145449b1SDimitry Andric     Vals.push_back(F.isDeclaration());
1304145449b1SDimitry Andric     Vals.push_back(getEncodedLinkage(F));
1305145449b1SDimitry Andric     Vals.push_back(VE.getAttributeListID(F.getAttributes()));
1306145449b1SDimitry Andric     Vals.push_back(getEncodedAlign(F.getAlign()));
1307145449b1SDimitry Andric     Vals.push_back(F.hasSection() ? SectionMap[std::string(F.getSection())]
1308145449b1SDimitry Andric                                   : 0);
1309145449b1SDimitry Andric     Vals.push_back(getEncodedVisibility(F));
1310145449b1SDimitry Andric     Vals.push_back(F.hasGC() ? GCMap[F.getGC()] : 0);
1311145449b1SDimitry Andric     Vals.push_back(F.getUnnamedAddr() != GlobalValue::UnnamedAddr::None);
1312145449b1SDimitry Andric     Vals.push_back(
1313145449b1SDimitry Andric         F.hasPrologueData() ? (VE.getValueID(F.getPrologueData()) + 1) : 0);
1314145449b1SDimitry Andric     Vals.push_back(getEncodedDLLStorageClass(F));
1315145449b1SDimitry Andric     Vals.push_back(F.hasComdat() ? VE.getComdatID(F.getComdat()) : 0);
1316145449b1SDimitry Andric     Vals.push_back(F.hasPrefixData() ? (VE.getValueID(F.getPrefixData()) + 1)
1317145449b1SDimitry Andric                                      : 0);
1318145449b1SDimitry Andric     Vals.push_back(
1319145449b1SDimitry Andric         F.hasPersonalityFn() ? (VE.getValueID(F.getPersonalityFn()) + 1) : 0);
1320145449b1SDimitry Andric 
1321145449b1SDimitry Andric     unsigned AbbrevToUse = 0;
1322145449b1SDimitry Andric     Stream.EmitRecord(bitc::MODULE_CODE_FUNCTION, Vals, AbbrevToUse);
1323145449b1SDimitry Andric     Vals.clear();
1324145449b1SDimitry Andric   }
1325145449b1SDimitry Andric 
1326145449b1SDimitry Andric   // Emit the alias information.
1327145449b1SDimitry Andric   for (const GlobalAlias &A : M.aliases()) {
1328145449b1SDimitry Andric     // ALIAS: [alias type, aliasee val#, linkage, visibility]
1329145449b1SDimitry Andric     Vals.push_back(getTypeID(A.getValueType(), &A));
1330145449b1SDimitry Andric     Vals.push_back(VE.getValueID(A.getAliasee()));
1331145449b1SDimitry Andric     Vals.push_back(getEncodedLinkage(A));
1332145449b1SDimitry Andric     Vals.push_back(getEncodedVisibility(A));
1333145449b1SDimitry Andric     Vals.push_back(getEncodedDLLStorageClass(A));
1334145449b1SDimitry Andric     Vals.push_back(getEncodedThreadLocalMode(A));
1335145449b1SDimitry Andric     Vals.push_back(A.getUnnamedAddr() != GlobalValue::UnnamedAddr::None);
1336145449b1SDimitry Andric     unsigned AbbrevToUse = 0;
1337145449b1SDimitry Andric     Stream.EmitRecord(bitc::MODULE_CODE_ALIAS_OLD, Vals, AbbrevToUse);
1338145449b1SDimitry Andric     Vals.clear();
1339145449b1SDimitry Andric   }
1340145449b1SDimitry Andric }
1341145449b1SDimitry Andric 
writeValueAsMetadata(const ValueAsMetadata * MD,SmallVectorImpl<uint64_t> & Record)1342145449b1SDimitry Andric void DXILBitcodeWriter::writeValueAsMetadata(
1343145449b1SDimitry Andric     const ValueAsMetadata *MD, SmallVectorImpl<uint64_t> &Record) {
1344145449b1SDimitry Andric   // Mimic an MDNode with a value as one operand.
1345145449b1SDimitry Andric   Value *V = MD->getValue();
1346145449b1SDimitry Andric   Type *Ty = V->getType();
1347145449b1SDimitry Andric   if (Function *F = dyn_cast<Function>(V))
1348145449b1SDimitry Andric     Ty = TypedPointerType::get(F->getFunctionType(), F->getAddressSpace());
1349145449b1SDimitry Andric   else if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V))
1350145449b1SDimitry Andric     Ty = TypedPointerType::get(GV->getValueType(), GV->getAddressSpace());
1351145449b1SDimitry Andric   Record.push_back(getTypeID(Ty));
1352145449b1SDimitry Andric   Record.push_back(VE.getValueID(V));
1353145449b1SDimitry Andric   Stream.EmitRecord(bitc::METADATA_VALUE, Record, 0);
1354145449b1SDimitry Andric   Record.clear();
1355145449b1SDimitry Andric }
1356145449b1SDimitry Andric 
writeMDTuple(const MDTuple * N,SmallVectorImpl<uint64_t> & Record,unsigned Abbrev)1357145449b1SDimitry Andric void DXILBitcodeWriter::writeMDTuple(const MDTuple *N,
1358145449b1SDimitry Andric                                      SmallVectorImpl<uint64_t> &Record,
1359145449b1SDimitry Andric                                      unsigned Abbrev) {
1360145449b1SDimitry Andric   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
1361145449b1SDimitry Andric     Metadata *MD = N->getOperand(i);
1362145449b1SDimitry Andric     assert(!(MD && isa<LocalAsMetadata>(MD)) &&
1363145449b1SDimitry Andric            "Unexpected function-local metadata");
1364145449b1SDimitry Andric     Record.push_back(VE.getMetadataOrNullID(MD));
1365145449b1SDimitry Andric   }
1366145449b1SDimitry Andric   Stream.EmitRecord(N->isDistinct() ? bitc::METADATA_DISTINCT_NODE
1367145449b1SDimitry Andric                                     : bitc::METADATA_NODE,
1368145449b1SDimitry Andric                     Record, Abbrev);
1369145449b1SDimitry Andric   Record.clear();
1370145449b1SDimitry Andric }
1371145449b1SDimitry Andric 
writeDILocation(const DILocation * N,SmallVectorImpl<uint64_t> & Record,unsigned & Abbrev)1372145449b1SDimitry Andric void DXILBitcodeWriter::writeDILocation(const DILocation *N,
1373145449b1SDimitry Andric                                         SmallVectorImpl<uint64_t> &Record,
1374145449b1SDimitry Andric                                         unsigned &Abbrev) {
1375145449b1SDimitry Andric   if (!Abbrev)
1376145449b1SDimitry Andric     Abbrev = createDILocationAbbrev();
1377145449b1SDimitry Andric   Record.push_back(N->isDistinct());
1378145449b1SDimitry Andric   Record.push_back(N->getLine());
1379145449b1SDimitry Andric   Record.push_back(N->getColumn());
1380145449b1SDimitry Andric   Record.push_back(VE.getMetadataID(N->getScope()));
1381145449b1SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getInlinedAt()));
1382145449b1SDimitry Andric 
1383145449b1SDimitry Andric   Stream.EmitRecord(bitc::METADATA_LOCATION, Record, Abbrev);
1384145449b1SDimitry Andric   Record.clear();
1385145449b1SDimitry Andric }
1386145449b1SDimitry Andric 
rotateSign(APInt Val)1387145449b1SDimitry Andric static uint64_t rotateSign(APInt Val) {
1388145449b1SDimitry Andric   int64_t I = Val.getSExtValue();
1389145449b1SDimitry Andric   uint64_t U = I;
1390145449b1SDimitry Andric   return I < 0 ? ~(U << 1) : U << 1;
1391145449b1SDimitry Andric }
1392145449b1SDimitry Andric 
writeDISubrange(const DISubrange * N,SmallVectorImpl<uint64_t> & Record,unsigned Abbrev)1393145449b1SDimitry Andric void DXILBitcodeWriter::writeDISubrange(const DISubrange *N,
1394145449b1SDimitry Andric                                         SmallVectorImpl<uint64_t> &Record,
1395145449b1SDimitry Andric                                         unsigned Abbrev) {
1396145449b1SDimitry Andric   Record.push_back(N->isDistinct());
1397b1c73532SDimitry Andric 
1398b1c73532SDimitry Andric   // TODO: Do we need to handle DIExpression here? What about cases where Count
1399b1c73532SDimitry Andric   // isn't specified but UpperBound and such are?
1400b1c73532SDimitry Andric   ConstantInt *Count = N->getCount().dyn_cast<ConstantInt *>();
1401b1c73532SDimitry Andric   assert(Count && "Count is missing or not ConstantInt");
1402b1c73532SDimitry Andric   Record.push_back(Count->getValue().getSExtValue());
1403b1c73532SDimitry Andric 
1404b1c73532SDimitry Andric   // TODO: Similarly, DIExpression is allowed here now
1405b1c73532SDimitry Andric   DISubrange::BoundType LowerBound = N->getLowerBound();
1406b1c73532SDimitry Andric   assert((LowerBound.isNull() || LowerBound.is<ConstantInt *>()) &&
1407b1c73532SDimitry Andric          "Lower bound provided but not ConstantInt");
1408145449b1SDimitry Andric   Record.push_back(
1409b1c73532SDimitry Andric       LowerBound ? rotateSign(LowerBound.get<ConstantInt *>()->getValue()) : 0);
1410145449b1SDimitry Andric 
1411145449b1SDimitry Andric   Stream.EmitRecord(bitc::METADATA_SUBRANGE, Record, Abbrev);
1412145449b1SDimitry Andric   Record.clear();
1413145449b1SDimitry Andric }
1414145449b1SDimitry Andric 
writeDIEnumerator(const DIEnumerator * N,SmallVectorImpl<uint64_t> & Record,unsigned Abbrev)1415145449b1SDimitry Andric void DXILBitcodeWriter::writeDIEnumerator(const DIEnumerator *N,
1416145449b1SDimitry Andric                                           SmallVectorImpl<uint64_t> &Record,
1417145449b1SDimitry Andric                                           unsigned Abbrev) {
1418145449b1SDimitry Andric   Record.push_back(N->isDistinct());
1419145449b1SDimitry Andric   Record.push_back(rotateSign(N->getValue()));
1420145449b1SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1421145449b1SDimitry Andric 
1422145449b1SDimitry Andric   Stream.EmitRecord(bitc::METADATA_ENUMERATOR, Record, Abbrev);
1423145449b1SDimitry Andric   Record.clear();
1424145449b1SDimitry Andric }
1425145449b1SDimitry Andric 
writeDIBasicType(const DIBasicType * N,SmallVectorImpl<uint64_t> & Record,unsigned Abbrev)1426145449b1SDimitry Andric void DXILBitcodeWriter::writeDIBasicType(const DIBasicType *N,
1427145449b1SDimitry Andric                                          SmallVectorImpl<uint64_t> &Record,
1428145449b1SDimitry Andric                                          unsigned Abbrev) {
1429145449b1SDimitry Andric   Record.push_back(N->isDistinct());
1430145449b1SDimitry Andric   Record.push_back(N->getTag());
1431145449b1SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1432145449b1SDimitry Andric   Record.push_back(N->getSizeInBits());
1433145449b1SDimitry Andric   Record.push_back(N->getAlignInBits());
1434145449b1SDimitry Andric   Record.push_back(N->getEncoding());
1435145449b1SDimitry Andric 
1436145449b1SDimitry Andric   Stream.EmitRecord(bitc::METADATA_BASIC_TYPE, Record, Abbrev);
1437145449b1SDimitry Andric   Record.clear();
1438145449b1SDimitry Andric }
1439145449b1SDimitry Andric 
writeDIDerivedType(const DIDerivedType * N,SmallVectorImpl<uint64_t> & Record,unsigned Abbrev)1440145449b1SDimitry Andric void DXILBitcodeWriter::writeDIDerivedType(const DIDerivedType *N,
1441145449b1SDimitry Andric                                            SmallVectorImpl<uint64_t> &Record,
1442145449b1SDimitry Andric                                            unsigned Abbrev) {
1443145449b1SDimitry Andric   Record.push_back(N->isDistinct());
1444145449b1SDimitry Andric   Record.push_back(N->getTag());
1445145449b1SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1446145449b1SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1447145449b1SDimitry Andric   Record.push_back(N->getLine());
1448145449b1SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1449145449b1SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getBaseType()));
1450145449b1SDimitry Andric   Record.push_back(N->getSizeInBits());
1451145449b1SDimitry Andric   Record.push_back(N->getAlignInBits());
1452145449b1SDimitry Andric   Record.push_back(N->getOffsetInBits());
1453145449b1SDimitry Andric   Record.push_back(N->getFlags());
1454145449b1SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getExtraData()));
1455145449b1SDimitry Andric 
1456145449b1SDimitry Andric   Stream.EmitRecord(bitc::METADATA_DERIVED_TYPE, Record, Abbrev);
1457145449b1SDimitry Andric   Record.clear();
1458145449b1SDimitry Andric }
1459145449b1SDimitry Andric 
writeDICompositeType(const DICompositeType * N,SmallVectorImpl<uint64_t> & Record,unsigned Abbrev)1460145449b1SDimitry Andric void DXILBitcodeWriter::writeDICompositeType(const DICompositeType *N,
1461145449b1SDimitry Andric                                              SmallVectorImpl<uint64_t> &Record,
1462145449b1SDimitry Andric                                              unsigned Abbrev) {
1463145449b1SDimitry Andric   Record.push_back(N->isDistinct());
1464145449b1SDimitry Andric   Record.push_back(N->getTag());
1465145449b1SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1466145449b1SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1467145449b1SDimitry Andric   Record.push_back(N->getLine());
1468145449b1SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1469145449b1SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getBaseType()));
1470145449b1SDimitry Andric   Record.push_back(N->getSizeInBits());
1471145449b1SDimitry Andric   Record.push_back(N->getAlignInBits());
1472145449b1SDimitry Andric   Record.push_back(N->getOffsetInBits());
1473145449b1SDimitry Andric   Record.push_back(N->getFlags());
1474145449b1SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getElements().get()));
1475145449b1SDimitry Andric   Record.push_back(N->getRuntimeLang());
1476145449b1SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getVTableHolder()));
1477145449b1SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getTemplateParams().get()));
1478145449b1SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getRawIdentifier()));
1479145449b1SDimitry Andric 
1480145449b1SDimitry Andric   Stream.EmitRecord(bitc::METADATA_COMPOSITE_TYPE, Record, Abbrev);
1481145449b1SDimitry Andric   Record.clear();
1482145449b1SDimitry Andric }
1483145449b1SDimitry Andric 
writeDISubroutineType(const DISubroutineType * N,SmallVectorImpl<uint64_t> & Record,unsigned Abbrev)1484145449b1SDimitry Andric void DXILBitcodeWriter::writeDISubroutineType(const DISubroutineType *N,
1485145449b1SDimitry Andric                                               SmallVectorImpl<uint64_t> &Record,
1486145449b1SDimitry Andric                                               unsigned Abbrev) {
1487145449b1SDimitry Andric   Record.push_back(N->isDistinct());
1488145449b1SDimitry Andric   Record.push_back(N->getFlags());
1489145449b1SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getTypeArray().get()));
1490145449b1SDimitry Andric 
1491145449b1SDimitry Andric   Stream.EmitRecord(bitc::METADATA_SUBROUTINE_TYPE, Record, Abbrev);
1492145449b1SDimitry Andric   Record.clear();
1493145449b1SDimitry Andric }
1494145449b1SDimitry Andric 
writeDIFile(const DIFile * N,SmallVectorImpl<uint64_t> & Record,unsigned Abbrev)1495145449b1SDimitry Andric void DXILBitcodeWriter::writeDIFile(const DIFile *N,
1496145449b1SDimitry Andric                                     SmallVectorImpl<uint64_t> &Record,
1497145449b1SDimitry Andric                                     unsigned Abbrev) {
1498145449b1SDimitry Andric   Record.push_back(N->isDistinct());
1499145449b1SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getRawFilename()));
1500145449b1SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getRawDirectory()));
1501145449b1SDimitry Andric 
1502145449b1SDimitry Andric   Stream.EmitRecord(bitc::METADATA_FILE, Record, Abbrev);
1503145449b1SDimitry Andric   Record.clear();
1504145449b1SDimitry Andric }
1505145449b1SDimitry Andric 
writeDICompileUnit(const DICompileUnit * N,SmallVectorImpl<uint64_t> & Record,unsigned Abbrev)1506145449b1SDimitry Andric void DXILBitcodeWriter::writeDICompileUnit(const DICompileUnit *N,
1507145449b1SDimitry Andric                                            SmallVectorImpl<uint64_t> &Record,
1508145449b1SDimitry Andric                                            unsigned Abbrev) {
1509145449b1SDimitry Andric   Record.push_back(N->isDistinct());
1510145449b1SDimitry Andric   Record.push_back(N->getSourceLanguage());
1511145449b1SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1512145449b1SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getRawProducer()));
1513145449b1SDimitry Andric   Record.push_back(N->isOptimized());
1514145449b1SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getRawFlags()));
1515145449b1SDimitry Andric   Record.push_back(N->getRuntimeVersion());
1516145449b1SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getRawSplitDebugFilename()));
1517145449b1SDimitry Andric   Record.push_back(N->getEmissionKind());
1518145449b1SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getEnumTypes().get()));
1519145449b1SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getRetainedTypes().get()));
1520145449b1SDimitry Andric   Record.push_back(/* subprograms */ 0);
1521145449b1SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getGlobalVariables().get()));
1522145449b1SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getImportedEntities().get()));
1523145449b1SDimitry Andric   Record.push_back(N->getDWOId());
1524145449b1SDimitry Andric 
1525145449b1SDimitry Andric   Stream.EmitRecord(bitc::METADATA_COMPILE_UNIT, Record, Abbrev);
1526145449b1SDimitry Andric   Record.clear();
1527145449b1SDimitry Andric }
1528145449b1SDimitry Andric 
writeDISubprogram(const DISubprogram * N,SmallVectorImpl<uint64_t> & Record,unsigned Abbrev)1529145449b1SDimitry Andric void DXILBitcodeWriter::writeDISubprogram(const DISubprogram *N,
1530145449b1SDimitry Andric                                           SmallVectorImpl<uint64_t> &Record,
1531145449b1SDimitry Andric                                           unsigned Abbrev) {
1532145449b1SDimitry Andric   Record.push_back(N->isDistinct());
1533145449b1SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1534145449b1SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1535145449b1SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getRawLinkageName()));
1536145449b1SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1537145449b1SDimitry Andric   Record.push_back(N->getLine());
1538145449b1SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getType()));
1539145449b1SDimitry Andric   Record.push_back(N->isLocalToUnit());
1540145449b1SDimitry Andric   Record.push_back(N->isDefinition());
1541145449b1SDimitry Andric   Record.push_back(N->getScopeLine());
1542145449b1SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getContainingType()));
1543145449b1SDimitry Andric   Record.push_back(N->getVirtuality());
1544145449b1SDimitry Andric   Record.push_back(N->getVirtualIndex());
1545145449b1SDimitry Andric   Record.push_back(N->getFlags());
1546145449b1SDimitry Andric   Record.push_back(N->isOptimized());
1547145449b1SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getRawUnit()));
1548145449b1SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getTemplateParams().get()));
1549145449b1SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getDeclaration()));
1550145449b1SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getRetainedNodes().get()));
1551145449b1SDimitry Andric 
1552145449b1SDimitry Andric   Stream.EmitRecord(bitc::METADATA_SUBPROGRAM, Record, Abbrev);
1553145449b1SDimitry Andric   Record.clear();
1554145449b1SDimitry Andric }
1555145449b1SDimitry Andric 
writeDILexicalBlock(const DILexicalBlock * N,SmallVectorImpl<uint64_t> & Record,unsigned Abbrev)1556145449b1SDimitry Andric void DXILBitcodeWriter::writeDILexicalBlock(const DILexicalBlock *N,
1557145449b1SDimitry Andric                                             SmallVectorImpl<uint64_t> &Record,
1558145449b1SDimitry Andric                                             unsigned Abbrev) {
1559145449b1SDimitry Andric   Record.push_back(N->isDistinct());
1560145449b1SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1561145449b1SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1562145449b1SDimitry Andric   Record.push_back(N->getLine());
1563145449b1SDimitry Andric   Record.push_back(N->getColumn());
1564145449b1SDimitry Andric 
1565145449b1SDimitry Andric   Stream.EmitRecord(bitc::METADATA_LEXICAL_BLOCK, Record, Abbrev);
1566145449b1SDimitry Andric   Record.clear();
1567145449b1SDimitry Andric }
1568145449b1SDimitry Andric 
writeDILexicalBlockFile(const DILexicalBlockFile * N,SmallVectorImpl<uint64_t> & Record,unsigned Abbrev)1569145449b1SDimitry Andric void DXILBitcodeWriter::writeDILexicalBlockFile(
1570145449b1SDimitry Andric     const DILexicalBlockFile *N, SmallVectorImpl<uint64_t> &Record,
1571145449b1SDimitry Andric     unsigned Abbrev) {
1572145449b1SDimitry Andric   Record.push_back(N->isDistinct());
1573145449b1SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1574145449b1SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1575145449b1SDimitry Andric   Record.push_back(N->getDiscriminator());
1576145449b1SDimitry Andric 
1577145449b1SDimitry Andric   Stream.EmitRecord(bitc::METADATA_LEXICAL_BLOCK_FILE, Record, Abbrev);
1578145449b1SDimitry Andric   Record.clear();
1579145449b1SDimitry Andric }
1580145449b1SDimitry Andric 
writeDINamespace(const DINamespace * N,SmallVectorImpl<uint64_t> & Record,unsigned Abbrev)1581145449b1SDimitry Andric void DXILBitcodeWriter::writeDINamespace(const DINamespace *N,
1582145449b1SDimitry Andric                                          SmallVectorImpl<uint64_t> &Record,
1583145449b1SDimitry Andric                                          unsigned Abbrev) {
1584145449b1SDimitry Andric   Record.push_back(N->isDistinct());
1585145449b1SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1586145449b1SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1587145449b1SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1588145449b1SDimitry Andric   Record.push_back(/* line number */ 0);
1589145449b1SDimitry Andric 
1590145449b1SDimitry Andric   Stream.EmitRecord(bitc::METADATA_NAMESPACE, Record, Abbrev);
1591145449b1SDimitry Andric   Record.clear();
1592145449b1SDimitry Andric }
1593145449b1SDimitry Andric 
writeDIModule(const DIModule * N,SmallVectorImpl<uint64_t> & Record,unsigned Abbrev)1594145449b1SDimitry Andric void DXILBitcodeWriter::writeDIModule(const DIModule *N,
1595145449b1SDimitry Andric                                       SmallVectorImpl<uint64_t> &Record,
1596145449b1SDimitry Andric                                       unsigned Abbrev) {
1597145449b1SDimitry Andric   Record.push_back(N->isDistinct());
1598145449b1SDimitry Andric   for (auto &I : N->operands())
1599145449b1SDimitry Andric     Record.push_back(VE.getMetadataOrNullID(I));
1600145449b1SDimitry Andric 
1601145449b1SDimitry Andric   Stream.EmitRecord(bitc::METADATA_MODULE, Record, Abbrev);
1602145449b1SDimitry Andric   Record.clear();
1603145449b1SDimitry Andric }
1604145449b1SDimitry Andric 
writeDITemplateTypeParameter(const DITemplateTypeParameter * N,SmallVectorImpl<uint64_t> & Record,unsigned Abbrev)1605145449b1SDimitry Andric void DXILBitcodeWriter::writeDITemplateTypeParameter(
1606145449b1SDimitry Andric     const DITemplateTypeParameter *N, SmallVectorImpl<uint64_t> &Record,
1607145449b1SDimitry Andric     unsigned Abbrev) {
1608145449b1SDimitry Andric   Record.push_back(N->isDistinct());
1609145449b1SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1610145449b1SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getType()));
1611145449b1SDimitry Andric 
1612145449b1SDimitry Andric   Stream.EmitRecord(bitc::METADATA_TEMPLATE_TYPE, Record, Abbrev);
1613145449b1SDimitry Andric   Record.clear();
1614145449b1SDimitry Andric }
1615145449b1SDimitry Andric 
writeDITemplateValueParameter(const DITemplateValueParameter * N,SmallVectorImpl<uint64_t> & Record,unsigned Abbrev)1616145449b1SDimitry Andric void DXILBitcodeWriter::writeDITemplateValueParameter(
1617145449b1SDimitry Andric     const DITemplateValueParameter *N, SmallVectorImpl<uint64_t> &Record,
1618145449b1SDimitry Andric     unsigned Abbrev) {
1619145449b1SDimitry Andric   Record.push_back(N->isDistinct());
1620145449b1SDimitry Andric   Record.push_back(N->getTag());
1621145449b1SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1622145449b1SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getType()));
1623145449b1SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getValue()));
1624145449b1SDimitry Andric 
1625145449b1SDimitry Andric   Stream.EmitRecord(bitc::METADATA_TEMPLATE_VALUE, Record, Abbrev);
1626145449b1SDimitry Andric   Record.clear();
1627145449b1SDimitry Andric }
1628145449b1SDimitry Andric 
writeDIGlobalVariable(const DIGlobalVariable * N,SmallVectorImpl<uint64_t> & Record,unsigned Abbrev)1629145449b1SDimitry Andric void DXILBitcodeWriter::writeDIGlobalVariable(const DIGlobalVariable *N,
1630145449b1SDimitry Andric                                               SmallVectorImpl<uint64_t> &Record,
1631145449b1SDimitry Andric                                               unsigned Abbrev) {
1632145449b1SDimitry Andric   Record.push_back(N->isDistinct());
1633145449b1SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1634145449b1SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1635145449b1SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getRawLinkageName()));
1636145449b1SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1637145449b1SDimitry Andric   Record.push_back(N->getLine());
1638145449b1SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getType()));
1639145449b1SDimitry Andric   Record.push_back(N->isLocalToUnit());
1640145449b1SDimitry Andric   Record.push_back(N->isDefinition());
1641145449b1SDimitry Andric   Record.push_back(/* N->getRawVariable() */ 0);
1642145449b1SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getStaticDataMemberDeclaration()));
1643145449b1SDimitry Andric 
1644145449b1SDimitry Andric   Stream.EmitRecord(bitc::METADATA_GLOBAL_VAR, Record, Abbrev);
1645145449b1SDimitry Andric   Record.clear();
1646145449b1SDimitry Andric }
1647145449b1SDimitry Andric 
writeDILocalVariable(const DILocalVariable * N,SmallVectorImpl<uint64_t> & Record,unsigned Abbrev)1648145449b1SDimitry Andric void DXILBitcodeWriter::writeDILocalVariable(const DILocalVariable *N,
1649145449b1SDimitry Andric                                              SmallVectorImpl<uint64_t> &Record,
1650145449b1SDimitry Andric                                              unsigned Abbrev) {
1651145449b1SDimitry Andric   Record.push_back(N->isDistinct());
1652145449b1SDimitry Andric   Record.push_back(N->getTag());
1653145449b1SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1654145449b1SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1655145449b1SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1656145449b1SDimitry Andric   Record.push_back(N->getLine());
1657145449b1SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getType()));
1658145449b1SDimitry Andric   Record.push_back(N->getArg());
1659145449b1SDimitry Andric   Record.push_back(N->getFlags());
1660145449b1SDimitry Andric 
1661145449b1SDimitry Andric   Stream.EmitRecord(bitc::METADATA_LOCAL_VAR, Record, Abbrev);
1662145449b1SDimitry Andric   Record.clear();
1663145449b1SDimitry Andric }
1664145449b1SDimitry Andric 
writeDIExpression(const DIExpression * N,SmallVectorImpl<uint64_t> & Record,unsigned Abbrev)1665145449b1SDimitry Andric void DXILBitcodeWriter::writeDIExpression(const DIExpression *N,
1666145449b1SDimitry Andric                                           SmallVectorImpl<uint64_t> &Record,
1667145449b1SDimitry Andric                                           unsigned Abbrev) {
1668145449b1SDimitry Andric   Record.reserve(N->getElements().size() + 1);
1669145449b1SDimitry Andric 
1670145449b1SDimitry Andric   Record.push_back(N->isDistinct());
1671145449b1SDimitry Andric   Record.append(N->elements_begin(), N->elements_end());
1672145449b1SDimitry Andric 
1673145449b1SDimitry Andric   Stream.EmitRecord(bitc::METADATA_EXPRESSION, Record, Abbrev);
1674145449b1SDimitry Andric   Record.clear();
1675145449b1SDimitry Andric }
1676145449b1SDimitry Andric 
writeDIObjCProperty(const DIObjCProperty * N,SmallVectorImpl<uint64_t> & Record,unsigned Abbrev)1677145449b1SDimitry Andric void DXILBitcodeWriter::writeDIObjCProperty(const DIObjCProperty *N,
1678145449b1SDimitry Andric                                             SmallVectorImpl<uint64_t> &Record,
1679145449b1SDimitry Andric                                             unsigned Abbrev) {
1680145449b1SDimitry Andric   llvm_unreachable("DXIL does not support objc!!!");
1681145449b1SDimitry Andric }
1682145449b1SDimitry Andric 
writeDIImportedEntity(const DIImportedEntity * N,SmallVectorImpl<uint64_t> & Record,unsigned Abbrev)1683145449b1SDimitry Andric void DXILBitcodeWriter::writeDIImportedEntity(const DIImportedEntity *N,
1684145449b1SDimitry Andric                                               SmallVectorImpl<uint64_t> &Record,
1685145449b1SDimitry Andric                                               unsigned Abbrev) {
1686145449b1SDimitry Andric   Record.push_back(N->isDistinct());
1687145449b1SDimitry Andric   Record.push_back(N->getTag());
1688145449b1SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1689145449b1SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getEntity()));
1690145449b1SDimitry Andric   Record.push_back(N->getLine());
1691145449b1SDimitry Andric   Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1692145449b1SDimitry Andric 
1693145449b1SDimitry Andric   Stream.EmitRecord(bitc::METADATA_IMPORTED_ENTITY, Record, Abbrev);
1694145449b1SDimitry Andric   Record.clear();
1695145449b1SDimitry Andric }
1696145449b1SDimitry Andric 
createDILocationAbbrev()1697145449b1SDimitry Andric unsigned DXILBitcodeWriter::createDILocationAbbrev() {
1698145449b1SDimitry Andric   // Abbrev for METADATA_LOCATION.
1699145449b1SDimitry Andric   //
1700145449b1SDimitry Andric   // Assume the column is usually under 128, and always output the inlined-at
1701145449b1SDimitry Andric   // location (it's never more expensive than building an array size 1).
1702145449b1SDimitry Andric   std::shared_ptr<BitCodeAbbrev> Abbv = std::make_shared<BitCodeAbbrev>();
1703145449b1SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_LOCATION));
1704145449b1SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));
1705145449b1SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
1706145449b1SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
1707145449b1SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
1708145449b1SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
1709145449b1SDimitry Andric   return Stream.EmitAbbrev(std::move(Abbv));
1710145449b1SDimitry Andric }
1711145449b1SDimitry Andric 
createGenericDINodeAbbrev()1712145449b1SDimitry Andric unsigned DXILBitcodeWriter::createGenericDINodeAbbrev() {
1713145449b1SDimitry Andric   // Abbrev for METADATA_GENERIC_DEBUG.
1714145449b1SDimitry Andric   //
1715145449b1SDimitry Andric   // Assume the column is usually under 128, and always output the inlined-at
1716145449b1SDimitry Andric   // location (it's never more expensive than building an array size 1).
1717145449b1SDimitry Andric   std::shared_ptr<BitCodeAbbrev> Abbv = std::make_shared<BitCodeAbbrev>();
1718145449b1SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_GENERIC_DEBUG));
1719145449b1SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));
1720145449b1SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
1721145449b1SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));
1722145449b1SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
1723145449b1SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1724145449b1SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
1725145449b1SDimitry Andric   return Stream.EmitAbbrev(std::move(Abbv));
1726145449b1SDimitry Andric }
1727145449b1SDimitry Andric 
writeMetadataRecords(ArrayRef<const Metadata * > MDs,SmallVectorImpl<uint64_t> & Record,std::vector<unsigned> * MDAbbrevs,std::vector<uint64_t> * IndexPos)1728145449b1SDimitry Andric void DXILBitcodeWriter::writeMetadataRecords(ArrayRef<const Metadata *> MDs,
1729145449b1SDimitry Andric                                              SmallVectorImpl<uint64_t> &Record,
1730145449b1SDimitry Andric                                              std::vector<unsigned> *MDAbbrevs,
1731145449b1SDimitry Andric                                              std::vector<uint64_t> *IndexPos) {
1732145449b1SDimitry Andric   if (MDs.empty())
1733145449b1SDimitry Andric     return;
1734145449b1SDimitry Andric 
1735145449b1SDimitry Andric     // Initialize MDNode abbreviations.
1736145449b1SDimitry Andric #define HANDLE_MDNODE_LEAF(CLASS) unsigned CLASS##Abbrev = 0;
1737145449b1SDimitry Andric #include "llvm/IR/Metadata.def"
1738145449b1SDimitry Andric 
1739145449b1SDimitry Andric   for (const Metadata *MD : MDs) {
1740145449b1SDimitry Andric     if (IndexPos)
1741145449b1SDimitry Andric       IndexPos->push_back(Stream.GetCurrentBitNo());
1742145449b1SDimitry Andric     if (const MDNode *N = dyn_cast<MDNode>(MD)) {
1743145449b1SDimitry Andric       assert(N->isResolved() && "Expected forward references to be resolved");
1744145449b1SDimitry Andric 
1745145449b1SDimitry Andric       switch (N->getMetadataID()) {
1746145449b1SDimitry Andric       default:
1747145449b1SDimitry Andric         llvm_unreachable("Invalid MDNode subclass");
1748145449b1SDimitry Andric #define HANDLE_MDNODE_LEAF(CLASS)                                              \
1749145449b1SDimitry Andric   case Metadata::CLASS##Kind:                                                  \
1750145449b1SDimitry Andric     if (MDAbbrevs)                                                             \
1751145449b1SDimitry Andric       write##CLASS(cast<CLASS>(N), Record,                                     \
1752145449b1SDimitry Andric                    (*MDAbbrevs)[MetadataAbbrev::CLASS##AbbrevID]);             \
1753145449b1SDimitry Andric     else                                                                       \
1754145449b1SDimitry Andric       write##CLASS(cast<CLASS>(N), Record, CLASS##Abbrev);                     \
1755145449b1SDimitry Andric     continue;
1756145449b1SDimitry Andric #include "llvm/IR/Metadata.def"
1757145449b1SDimitry Andric       }
1758145449b1SDimitry Andric     }
1759145449b1SDimitry Andric     writeValueAsMetadata(cast<ValueAsMetadata>(MD), Record);
1760145449b1SDimitry Andric   }
1761145449b1SDimitry Andric }
1762145449b1SDimitry Andric 
createMetadataStringsAbbrev()1763145449b1SDimitry Andric unsigned DXILBitcodeWriter::createMetadataStringsAbbrev() {
1764145449b1SDimitry Andric   auto Abbv = std::make_shared<BitCodeAbbrev>();
1765145449b1SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_STRING_OLD));
1766145449b1SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1767145449b1SDimitry Andric   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
1768145449b1SDimitry Andric   return Stream.EmitAbbrev(std::move(Abbv));
1769145449b1SDimitry Andric }
1770145449b1SDimitry Andric 
writeMetadataStrings(ArrayRef<const Metadata * > Strings,SmallVectorImpl<uint64_t> & Record)1771145449b1SDimitry Andric void DXILBitcodeWriter::writeMetadataStrings(
1772145449b1SDimitry Andric     ArrayRef<const Metadata *> Strings, SmallVectorImpl<uint64_t> &Record) {
1773b1c73532SDimitry Andric   if (Strings.empty())
1774b1c73532SDimitry Andric     return;
1775b1c73532SDimitry Andric 
1776b1c73532SDimitry Andric   unsigned MDSAbbrev = createMetadataStringsAbbrev();
1777b1c73532SDimitry Andric 
1778145449b1SDimitry Andric   for (const Metadata *MD : Strings) {
1779145449b1SDimitry Andric     const MDString *MDS = cast<MDString>(MD);
1780145449b1SDimitry Andric     // Code: [strchar x N]
1781145449b1SDimitry Andric     Record.append(MDS->bytes_begin(), MDS->bytes_end());
1782145449b1SDimitry Andric 
1783145449b1SDimitry Andric     // Emit the finished record.
1784b1c73532SDimitry Andric     Stream.EmitRecord(bitc::METADATA_STRING_OLD, Record, MDSAbbrev);
1785145449b1SDimitry Andric     Record.clear();
1786145449b1SDimitry Andric   }
1787145449b1SDimitry Andric }
1788145449b1SDimitry Andric 
writeModuleMetadata()1789145449b1SDimitry Andric void DXILBitcodeWriter::writeModuleMetadata() {
1790145449b1SDimitry Andric   if (!VE.hasMDs() && M.named_metadata_empty())
1791145449b1SDimitry Andric     return;
1792145449b1SDimitry Andric 
1793145449b1SDimitry Andric   Stream.EnterSubblock(bitc::METADATA_BLOCK_ID, 5);
1794145449b1SDimitry Andric 
1795145449b1SDimitry Andric   // Emit all abbrevs upfront, so that the reader can jump in the middle of the
1796145449b1SDimitry Andric   // block and load any metadata.
1797145449b1SDimitry Andric   std::vector<unsigned> MDAbbrevs;
1798145449b1SDimitry Andric 
1799145449b1SDimitry Andric   MDAbbrevs.resize(MetadataAbbrev::LastPlusOne);
1800145449b1SDimitry Andric   MDAbbrevs[MetadataAbbrev::DILocationAbbrevID] = createDILocationAbbrev();
1801145449b1SDimitry Andric   MDAbbrevs[MetadataAbbrev::GenericDINodeAbbrevID] =
1802145449b1SDimitry Andric       createGenericDINodeAbbrev();
1803145449b1SDimitry Andric 
1804145449b1SDimitry Andric   unsigned NameAbbrev = 0;
1805145449b1SDimitry Andric   if (!M.named_metadata_empty()) {
1806145449b1SDimitry Andric     // Abbrev for METADATA_NAME.
1807145449b1SDimitry Andric     std::shared_ptr<BitCodeAbbrev> Abbv = std::make_shared<BitCodeAbbrev>();
1808145449b1SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_NAME));
1809145449b1SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1810145449b1SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
1811145449b1SDimitry Andric     NameAbbrev = Stream.EmitAbbrev(std::move(Abbv));
1812145449b1SDimitry Andric   }
1813145449b1SDimitry Andric 
1814145449b1SDimitry Andric   SmallVector<uint64_t, 64> Record;
1815145449b1SDimitry Andric   writeMetadataStrings(VE.getMDStrings(), Record);
1816145449b1SDimitry Andric 
1817145449b1SDimitry Andric   std::vector<uint64_t> IndexPos;
1818145449b1SDimitry Andric   IndexPos.reserve(VE.getNonMDStrings().size());
1819145449b1SDimitry Andric   writeMetadataRecords(VE.getNonMDStrings(), Record, &MDAbbrevs, &IndexPos);
1820145449b1SDimitry Andric 
1821145449b1SDimitry Andric   // Write named metadata.
1822145449b1SDimitry Andric   for (const NamedMDNode &NMD : M.named_metadata()) {
1823145449b1SDimitry Andric     // Write name.
1824145449b1SDimitry Andric     StringRef Str = NMD.getName();
1825145449b1SDimitry Andric     Record.append(Str.bytes_begin(), Str.bytes_end());
1826145449b1SDimitry Andric     Stream.EmitRecord(bitc::METADATA_NAME, Record, NameAbbrev);
1827145449b1SDimitry Andric     Record.clear();
1828145449b1SDimitry Andric 
1829145449b1SDimitry Andric     // Write named metadata operands.
1830145449b1SDimitry Andric     for (const MDNode *N : NMD.operands())
1831145449b1SDimitry Andric       Record.push_back(VE.getMetadataID(N));
1832145449b1SDimitry Andric     Stream.EmitRecord(bitc::METADATA_NAMED_NODE, Record, 0);
1833145449b1SDimitry Andric     Record.clear();
1834145449b1SDimitry Andric   }
1835145449b1SDimitry Andric 
1836145449b1SDimitry Andric   Stream.ExitBlock();
1837145449b1SDimitry Andric }
1838145449b1SDimitry Andric 
writeFunctionMetadata(const Function & F)1839145449b1SDimitry Andric void DXILBitcodeWriter::writeFunctionMetadata(const Function &F) {
1840145449b1SDimitry Andric   if (!VE.hasMDs())
1841145449b1SDimitry Andric     return;
1842145449b1SDimitry Andric 
1843145449b1SDimitry Andric   Stream.EnterSubblock(bitc::METADATA_BLOCK_ID, 4);
1844145449b1SDimitry Andric   SmallVector<uint64_t, 64> Record;
1845145449b1SDimitry Andric   writeMetadataStrings(VE.getMDStrings(), Record);
1846145449b1SDimitry Andric   writeMetadataRecords(VE.getNonMDStrings(), Record);
1847145449b1SDimitry Andric   Stream.ExitBlock();
1848145449b1SDimitry Andric }
1849145449b1SDimitry Andric 
writeFunctionMetadataAttachment(const Function & F)1850145449b1SDimitry Andric void DXILBitcodeWriter::writeFunctionMetadataAttachment(const Function &F) {
1851145449b1SDimitry Andric   Stream.EnterSubblock(bitc::METADATA_ATTACHMENT_ID, 3);
1852145449b1SDimitry Andric 
1853145449b1SDimitry Andric   SmallVector<uint64_t, 64> Record;
1854145449b1SDimitry Andric 
1855145449b1SDimitry Andric   // Write metadata attachments
1856145449b1SDimitry Andric   // METADATA_ATTACHMENT - [m x [value, [n x [id, mdnode]]]
1857145449b1SDimitry Andric   SmallVector<std::pair<unsigned, MDNode *>, 4> MDs;
1858145449b1SDimitry Andric   F.getAllMetadata(MDs);
1859145449b1SDimitry Andric   if (!MDs.empty()) {
1860145449b1SDimitry Andric     for (const auto &I : MDs) {
1861145449b1SDimitry Andric       Record.push_back(I.first);
1862145449b1SDimitry Andric       Record.push_back(VE.getMetadataID(I.second));
1863145449b1SDimitry Andric     }
1864145449b1SDimitry Andric     Stream.EmitRecord(bitc::METADATA_ATTACHMENT, Record, 0);
1865145449b1SDimitry Andric     Record.clear();
1866145449b1SDimitry Andric   }
1867145449b1SDimitry Andric 
1868145449b1SDimitry Andric   for (const BasicBlock &BB : F)
1869145449b1SDimitry Andric     for (const Instruction &I : BB) {
1870145449b1SDimitry Andric       MDs.clear();
1871145449b1SDimitry Andric       I.getAllMetadataOtherThanDebugLoc(MDs);
1872145449b1SDimitry Andric 
1873145449b1SDimitry Andric       // If no metadata, ignore instruction.
1874145449b1SDimitry Andric       if (MDs.empty())
1875145449b1SDimitry Andric         continue;
1876145449b1SDimitry Andric 
1877145449b1SDimitry Andric       Record.push_back(VE.getInstructionID(&I));
1878145449b1SDimitry Andric 
1879145449b1SDimitry Andric       for (unsigned i = 0, e = MDs.size(); i != e; ++i) {
1880145449b1SDimitry Andric         Record.push_back(MDs[i].first);
1881145449b1SDimitry Andric         Record.push_back(VE.getMetadataID(MDs[i].second));
1882145449b1SDimitry Andric       }
1883145449b1SDimitry Andric       Stream.EmitRecord(bitc::METADATA_ATTACHMENT, Record, 0);
1884145449b1SDimitry Andric       Record.clear();
1885145449b1SDimitry Andric     }
1886145449b1SDimitry Andric 
1887145449b1SDimitry Andric   Stream.ExitBlock();
1888145449b1SDimitry Andric }
1889145449b1SDimitry Andric 
writeModuleMetadataKinds()1890145449b1SDimitry Andric void DXILBitcodeWriter::writeModuleMetadataKinds() {
1891145449b1SDimitry Andric   SmallVector<uint64_t, 64> Record;
1892145449b1SDimitry Andric 
1893145449b1SDimitry Andric   // Write metadata kinds
1894145449b1SDimitry Andric   // METADATA_KIND - [n x [id, name]]
1895145449b1SDimitry Andric   SmallVector<StringRef, 8> Names;
1896145449b1SDimitry Andric   M.getMDKindNames(Names);
1897145449b1SDimitry Andric 
1898145449b1SDimitry Andric   if (Names.empty())
1899145449b1SDimitry Andric     return;
1900145449b1SDimitry Andric 
1901145449b1SDimitry Andric   Stream.EnterSubblock(bitc::METADATA_BLOCK_ID, 3);
1902145449b1SDimitry Andric 
1903145449b1SDimitry Andric   for (unsigned MDKindID = 0, e = Names.size(); MDKindID != e; ++MDKindID) {
1904145449b1SDimitry Andric     Record.push_back(MDKindID);
1905145449b1SDimitry Andric     StringRef KName = Names[MDKindID];
1906145449b1SDimitry Andric     Record.append(KName.begin(), KName.end());
1907145449b1SDimitry Andric 
1908145449b1SDimitry Andric     Stream.EmitRecord(bitc::METADATA_KIND, Record, 0);
1909145449b1SDimitry Andric     Record.clear();
1910145449b1SDimitry Andric   }
1911145449b1SDimitry Andric 
1912145449b1SDimitry Andric   Stream.ExitBlock();
1913145449b1SDimitry Andric }
1914145449b1SDimitry Andric 
writeConstants(unsigned FirstVal,unsigned LastVal,bool isGlobal)1915145449b1SDimitry Andric void DXILBitcodeWriter::writeConstants(unsigned FirstVal, unsigned LastVal,
1916145449b1SDimitry Andric                                        bool isGlobal) {
1917145449b1SDimitry Andric   if (FirstVal == LastVal)
1918145449b1SDimitry Andric     return;
1919145449b1SDimitry Andric 
1920145449b1SDimitry Andric   Stream.EnterSubblock(bitc::CONSTANTS_BLOCK_ID, 4);
1921145449b1SDimitry Andric 
1922145449b1SDimitry Andric   unsigned AggregateAbbrev = 0;
1923145449b1SDimitry Andric   unsigned String8Abbrev = 0;
1924145449b1SDimitry Andric   unsigned CString7Abbrev = 0;
1925145449b1SDimitry Andric   unsigned CString6Abbrev = 0;
1926145449b1SDimitry Andric   // If this is a constant pool for the module, emit module-specific abbrevs.
1927145449b1SDimitry Andric   if (isGlobal) {
1928145449b1SDimitry Andric     // Abbrev for CST_CODE_AGGREGATE.
1929145449b1SDimitry Andric     auto Abbv = std::make_shared<BitCodeAbbrev>();
1930145449b1SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_AGGREGATE));
1931145449b1SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1932145449b1SDimitry Andric     Abbv->Add(
1933145449b1SDimitry Andric         BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, Log2_32_Ceil(LastVal + 1)));
1934145449b1SDimitry Andric     AggregateAbbrev = Stream.EmitAbbrev(std::move(Abbv));
1935145449b1SDimitry Andric 
1936145449b1SDimitry Andric     // Abbrev for CST_CODE_STRING.
1937145449b1SDimitry Andric     Abbv = std::make_shared<BitCodeAbbrev>();
1938145449b1SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_STRING));
1939145449b1SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1940145449b1SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
1941145449b1SDimitry Andric     String8Abbrev = Stream.EmitAbbrev(std::move(Abbv));
1942145449b1SDimitry Andric     // Abbrev for CST_CODE_CSTRING.
1943145449b1SDimitry Andric     Abbv = std::make_shared<BitCodeAbbrev>();
1944145449b1SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_CSTRING));
1945145449b1SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1946145449b1SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7));
1947145449b1SDimitry Andric     CString7Abbrev = Stream.EmitAbbrev(std::move(Abbv));
1948145449b1SDimitry Andric     // Abbrev for CST_CODE_CSTRING.
1949145449b1SDimitry Andric     Abbv = std::make_shared<BitCodeAbbrev>();
1950145449b1SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_CSTRING));
1951145449b1SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1952145449b1SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
1953145449b1SDimitry Andric     CString6Abbrev = Stream.EmitAbbrev(std::move(Abbv));
1954145449b1SDimitry Andric   }
1955145449b1SDimitry Andric 
1956145449b1SDimitry Andric   SmallVector<uint64_t, 64> Record;
1957145449b1SDimitry Andric 
1958145449b1SDimitry Andric   const ValueEnumerator::ValueList &Vals = VE.getValues();
1959145449b1SDimitry Andric   Type *LastTy = nullptr;
1960145449b1SDimitry Andric   for (unsigned i = FirstVal; i != LastVal; ++i) {
1961145449b1SDimitry Andric     const Value *V = Vals[i].first;
1962145449b1SDimitry Andric     // If we need to switch types, do so now.
1963145449b1SDimitry Andric     if (V->getType() != LastTy) {
1964145449b1SDimitry Andric       LastTy = V->getType();
1965e3b55780SDimitry Andric       Record.push_back(getTypeID(LastTy, V));
1966145449b1SDimitry Andric       Stream.EmitRecord(bitc::CST_CODE_SETTYPE, Record,
1967145449b1SDimitry Andric                         CONSTANTS_SETTYPE_ABBREV);
1968145449b1SDimitry Andric       Record.clear();
1969145449b1SDimitry Andric     }
1970145449b1SDimitry Andric 
1971145449b1SDimitry Andric     if (const InlineAsm *IA = dyn_cast<InlineAsm>(V)) {
1972145449b1SDimitry Andric       Record.push_back(unsigned(IA->hasSideEffects()) |
1973145449b1SDimitry Andric                        unsigned(IA->isAlignStack()) << 1 |
1974145449b1SDimitry Andric                        unsigned(IA->getDialect() & 1) << 2);
1975145449b1SDimitry Andric 
1976145449b1SDimitry Andric       // Add the asm string.
1977145449b1SDimitry Andric       const std::string &AsmStr = IA->getAsmString();
1978145449b1SDimitry Andric       Record.push_back(AsmStr.size());
1979145449b1SDimitry Andric       Record.append(AsmStr.begin(), AsmStr.end());
1980145449b1SDimitry Andric 
1981145449b1SDimitry Andric       // Add the constraint string.
1982145449b1SDimitry Andric       const std::string &ConstraintStr = IA->getConstraintString();
1983145449b1SDimitry Andric       Record.push_back(ConstraintStr.size());
1984145449b1SDimitry Andric       Record.append(ConstraintStr.begin(), ConstraintStr.end());
1985145449b1SDimitry Andric       Stream.EmitRecord(bitc::CST_CODE_INLINEASM, Record);
1986145449b1SDimitry Andric       Record.clear();
1987145449b1SDimitry Andric       continue;
1988145449b1SDimitry Andric     }
1989145449b1SDimitry Andric     const Constant *C = cast<Constant>(V);
1990145449b1SDimitry Andric     unsigned Code = -1U;
1991145449b1SDimitry Andric     unsigned AbbrevToUse = 0;
1992145449b1SDimitry Andric     if (C->isNullValue()) {
1993145449b1SDimitry Andric       Code = bitc::CST_CODE_NULL;
1994145449b1SDimitry Andric     } else if (isa<UndefValue>(C)) {
1995145449b1SDimitry Andric       Code = bitc::CST_CODE_UNDEF;
1996145449b1SDimitry Andric     } else if (const ConstantInt *IV = dyn_cast<ConstantInt>(C)) {
1997145449b1SDimitry Andric       if (IV->getBitWidth() <= 64) {
1998145449b1SDimitry Andric         uint64_t V = IV->getSExtValue();
1999145449b1SDimitry Andric         emitSignedInt64(Record, V);
2000145449b1SDimitry Andric         Code = bitc::CST_CODE_INTEGER;
2001145449b1SDimitry Andric         AbbrevToUse = CONSTANTS_INTEGER_ABBREV;
2002145449b1SDimitry Andric       } else { // Wide integers, > 64 bits in size.
2003145449b1SDimitry Andric         // We have an arbitrary precision integer value to write whose
2004145449b1SDimitry Andric         // bit width is > 64. However, in canonical unsigned integer
2005145449b1SDimitry Andric         // format it is likely that the high bits are going to be zero.
2006145449b1SDimitry Andric         // So, we only write the number of active words.
2007145449b1SDimitry Andric         unsigned NWords = IV->getValue().getActiveWords();
2008145449b1SDimitry Andric         const uint64_t *RawWords = IV->getValue().getRawData();
2009145449b1SDimitry Andric         for (unsigned i = 0; i != NWords; ++i) {
2010145449b1SDimitry Andric           emitSignedInt64(Record, RawWords[i]);
2011145449b1SDimitry Andric         }
2012145449b1SDimitry Andric         Code = bitc::CST_CODE_WIDE_INTEGER;
2013145449b1SDimitry Andric       }
2014145449b1SDimitry Andric     } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
2015145449b1SDimitry Andric       Code = bitc::CST_CODE_FLOAT;
2016145449b1SDimitry Andric       Type *Ty = CFP->getType();
2017145449b1SDimitry Andric       if (Ty->isHalfTy() || Ty->isFloatTy() || Ty->isDoubleTy()) {
2018145449b1SDimitry Andric         Record.push_back(CFP->getValueAPF().bitcastToAPInt().getZExtValue());
2019145449b1SDimitry Andric       } else if (Ty->isX86_FP80Ty()) {
2020145449b1SDimitry Andric         // api needed to prevent premature destruction
2021145449b1SDimitry Andric         // bits are not in the same order as a normal i80 APInt, compensate.
2022145449b1SDimitry Andric         APInt api = CFP->getValueAPF().bitcastToAPInt();
2023145449b1SDimitry Andric         const uint64_t *p = api.getRawData();
2024145449b1SDimitry Andric         Record.push_back((p[1] << 48) | (p[0] >> 16));
2025145449b1SDimitry Andric         Record.push_back(p[0] & 0xffffLL);
2026145449b1SDimitry Andric       } else if (Ty->isFP128Ty() || Ty->isPPC_FP128Ty()) {
2027145449b1SDimitry Andric         APInt api = CFP->getValueAPF().bitcastToAPInt();
2028145449b1SDimitry Andric         const uint64_t *p = api.getRawData();
2029145449b1SDimitry Andric         Record.push_back(p[0]);
2030145449b1SDimitry Andric         Record.push_back(p[1]);
2031145449b1SDimitry Andric       } else {
2032145449b1SDimitry Andric         assert(0 && "Unknown FP type!");
2033145449b1SDimitry Andric       }
2034145449b1SDimitry Andric     } else if (isa<ConstantDataSequential>(C) &&
2035145449b1SDimitry Andric                cast<ConstantDataSequential>(C)->isString()) {
2036145449b1SDimitry Andric       const ConstantDataSequential *Str = cast<ConstantDataSequential>(C);
2037145449b1SDimitry Andric       // Emit constant strings specially.
2038145449b1SDimitry Andric       unsigned NumElts = Str->getNumElements();
2039145449b1SDimitry Andric       // If this is a null-terminated string, use the denser CSTRING encoding.
2040145449b1SDimitry Andric       if (Str->isCString()) {
2041145449b1SDimitry Andric         Code = bitc::CST_CODE_CSTRING;
2042145449b1SDimitry Andric         --NumElts; // Don't encode the null, which isn't allowed by char6.
2043145449b1SDimitry Andric       } else {
2044145449b1SDimitry Andric         Code = bitc::CST_CODE_STRING;
2045145449b1SDimitry Andric         AbbrevToUse = String8Abbrev;
2046145449b1SDimitry Andric       }
2047145449b1SDimitry Andric       bool isCStr7 = Code == bitc::CST_CODE_CSTRING;
2048145449b1SDimitry Andric       bool isCStrChar6 = Code == bitc::CST_CODE_CSTRING;
2049145449b1SDimitry Andric       for (unsigned i = 0; i != NumElts; ++i) {
2050145449b1SDimitry Andric         unsigned char V = Str->getElementAsInteger(i);
2051145449b1SDimitry Andric         Record.push_back(V);
2052145449b1SDimitry Andric         isCStr7 &= (V & 128) == 0;
2053145449b1SDimitry Andric         if (isCStrChar6)
2054145449b1SDimitry Andric           isCStrChar6 = BitCodeAbbrevOp::isChar6(V);
2055145449b1SDimitry Andric       }
2056145449b1SDimitry Andric 
2057145449b1SDimitry Andric       if (isCStrChar6)
2058145449b1SDimitry Andric         AbbrevToUse = CString6Abbrev;
2059145449b1SDimitry Andric       else if (isCStr7)
2060145449b1SDimitry Andric         AbbrevToUse = CString7Abbrev;
2061145449b1SDimitry Andric     } else if (const ConstantDataSequential *CDS =
2062145449b1SDimitry Andric                    dyn_cast<ConstantDataSequential>(C)) {
2063145449b1SDimitry Andric       Code = bitc::CST_CODE_DATA;
2064e3b55780SDimitry Andric       Type *EltTy = CDS->getElementType();
2065145449b1SDimitry Andric       if (isa<IntegerType>(EltTy)) {
2066145449b1SDimitry Andric         for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i)
2067145449b1SDimitry Andric           Record.push_back(CDS->getElementAsInteger(i));
2068145449b1SDimitry Andric       } else if (EltTy->isFloatTy()) {
2069145449b1SDimitry Andric         for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
2070145449b1SDimitry Andric           union {
2071145449b1SDimitry Andric             float F;
2072145449b1SDimitry Andric             uint32_t I;
2073145449b1SDimitry Andric           };
2074145449b1SDimitry Andric           F = CDS->getElementAsFloat(i);
2075145449b1SDimitry Andric           Record.push_back(I);
2076145449b1SDimitry Andric         }
2077145449b1SDimitry Andric       } else {
2078145449b1SDimitry Andric         assert(EltTy->isDoubleTy() && "Unknown ConstantData element type");
2079145449b1SDimitry Andric         for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
2080145449b1SDimitry Andric           union {
2081145449b1SDimitry Andric             double F;
2082145449b1SDimitry Andric             uint64_t I;
2083145449b1SDimitry Andric           };
2084145449b1SDimitry Andric           F = CDS->getElementAsDouble(i);
2085145449b1SDimitry Andric           Record.push_back(I);
2086145449b1SDimitry Andric         }
2087145449b1SDimitry Andric       }
2088145449b1SDimitry Andric     } else if (isa<ConstantArray>(C) || isa<ConstantStruct>(C) ||
2089145449b1SDimitry Andric                isa<ConstantVector>(C)) {
2090145449b1SDimitry Andric       Code = bitc::CST_CODE_AGGREGATE;
2091145449b1SDimitry Andric       for (const Value *Op : C->operands())
2092145449b1SDimitry Andric         Record.push_back(VE.getValueID(Op));
2093145449b1SDimitry Andric       AbbrevToUse = AggregateAbbrev;
2094145449b1SDimitry Andric     } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
2095145449b1SDimitry Andric       switch (CE->getOpcode()) {
2096145449b1SDimitry Andric       default:
2097145449b1SDimitry Andric         if (Instruction::isCast(CE->getOpcode())) {
2098145449b1SDimitry Andric           Code = bitc::CST_CODE_CE_CAST;
2099145449b1SDimitry Andric           Record.push_back(getEncodedCastOpcode(CE->getOpcode()));
2100e3b55780SDimitry Andric           Record.push_back(
2101e3b55780SDimitry Andric               getTypeID(C->getOperand(0)->getType(), C->getOperand(0)));
2102145449b1SDimitry Andric           Record.push_back(VE.getValueID(C->getOperand(0)));
2103145449b1SDimitry Andric           AbbrevToUse = CONSTANTS_CE_CAST_Abbrev;
2104145449b1SDimitry Andric         } else {
2105145449b1SDimitry Andric           assert(CE->getNumOperands() == 2 && "Unknown constant expr!");
2106145449b1SDimitry Andric           Code = bitc::CST_CODE_CE_BINOP;
2107145449b1SDimitry Andric           Record.push_back(getEncodedBinaryOpcode(CE->getOpcode()));
2108145449b1SDimitry Andric           Record.push_back(VE.getValueID(C->getOperand(0)));
2109145449b1SDimitry Andric           Record.push_back(VE.getValueID(C->getOperand(1)));
2110145449b1SDimitry Andric           uint64_t Flags = getOptimizationFlags(CE);
2111145449b1SDimitry Andric           if (Flags != 0)
2112145449b1SDimitry Andric             Record.push_back(Flags);
2113145449b1SDimitry Andric         }
2114145449b1SDimitry Andric         break;
2115145449b1SDimitry Andric       case Instruction::GetElementPtr: {
2116145449b1SDimitry Andric         Code = bitc::CST_CODE_CE_GEP;
2117145449b1SDimitry Andric         const auto *GO = cast<GEPOperator>(C);
2118145449b1SDimitry Andric         if (GO->isInBounds())
2119145449b1SDimitry Andric           Code = bitc::CST_CODE_CE_INBOUNDS_GEP;
2120145449b1SDimitry Andric         Record.push_back(getTypeID(GO->getSourceElementType()));
2121145449b1SDimitry Andric         for (unsigned i = 0, e = CE->getNumOperands(); i != e; ++i) {
2122e3b55780SDimitry Andric           Record.push_back(
2123e3b55780SDimitry Andric               getTypeID(C->getOperand(i)->getType(), C->getOperand(i)));
2124145449b1SDimitry Andric           Record.push_back(VE.getValueID(C->getOperand(i)));
2125145449b1SDimitry Andric         }
2126145449b1SDimitry Andric         break;
2127145449b1SDimitry Andric       }
2128145449b1SDimitry Andric       case Instruction::Select:
2129145449b1SDimitry Andric         Code = bitc::CST_CODE_CE_SELECT;
2130145449b1SDimitry Andric         Record.push_back(VE.getValueID(C->getOperand(0)));
2131145449b1SDimitry Andric         Record.push_back(VE.getValueID(C->getOperand(1)));
2132145449b1SDimitry Andric         Record.push_back(VE.getValueID(C->getOperand(2)));
2133145449b1SDimitry Andric         break;
2134145449b1SDimitry Andric       case Instruction::ExtractElement:
2135145449b1SDimitry Andric         Code = bitc::CST_CODE_CE_EXTRACTELT;
2136145449b1SDimitry Andric         Record.push_back(getTypeID(C->getOperand(0)->getType()));
2137145449b1SDimitry Andric         Record.push_back(VE.getValueID(C->getOperand(0)));
2138145449b1SDimitry Andric         Record.push_back(getTypeID(C->getOperand(1)->getType()));
2139145449b1SDimitry Andric         Record.push_back(VE.getValueID(C->getOperand(1)));
2140145449b1SDimitry Andric         break;
2141145449b1SDimitry Andric       case Instruction::InsertElement:
2142145449b1SDimitry Andric         Code = bitc::CST_CODE_CE_INSERTELT;
2143145449b1SDimitry Andric         Record.push_back(VE.getValueID(C->getOperand(0)));
2144145449b1SDimitry Andric         Record.push_back(VE.getValueID(C->getOperand(1)));
2145145449b1SDimitry Andric         Record.push_back(getTypeID(C->getOperand(2)->getType()));
2146145449b1SDimitry Andric         Record.push_back(VE.getValueID(C->getOperand(2)));
2147145449b1SDimitry Andric         break;
2148145449b1SDimitry Andric       case Instruction::ShuffleVector:
2149145449b1SDimitry Andric         // If the return type and argument types are the same, this is a
2150145449b1SDimitry Andric         // standard shufflevector instruction.  If the types are different,
2151145449b1SDimitry Andric         // then the shuffle is widening or truncating the input vectors, and
2152145449b1SDimitry Andric         // the argument type must also be encoded.
2153145449b1SDimitry Andric         if (C->getType() == C->getOperand(0)->getType()) {
2154145449b1SDimitry Andric           Code = bitc::CST_CODE_CE_SHUFFLEVEC;
2155145449b1SDimitry Andric         } else {
2156145449b1SDimitry Andric           Code = bitc::CST_CODE_CE_SHUFVEC_EX;
2157145449b1SDimitry Andric           Record.push_back(getTypeID(C->getOperand(0)->getType()));
2158145449b1SDimitry Andric         }
2159145449b1SDimitry Andric         Record.push_back(VE.getValueID(C->getOperand(0)));
2160145449b1SDimitry Andric         Record.push_back(VE.getValueID(C->getOperand(1)));
2161145449b1SDimitry Andric         Record.push_back(VE.getValueID(C->getOperand(2)));
2162145449b1SDimitry Andric         break;
2163145449b1SDimitry Andric       }
2164145449b1SDimitry Andric     } else if (const BlockAddress *BA = dyn_cast<BlockAddress>(C)) {
2165145449b1SDimitry Andric       Code = bitc::CST_CODE_BLOCKADDRESS;
2166145449b1SDimitry Andric       Record.push_back(getTypeID(BA->getFunction()->getType()));
2167145449b1SDimitry Andric       Record.push_back(VE.getValueID(BA->getFunction()));
2168145449b1SDimitry Andric       Record.push_back(VE.getGlobalBasicBlockID(BA->getBasicBlock()));
2169145449b1SDimitry Andric     } else {
2170145449b1SDimitry Andric #ifndef NDEBUG
2171145449b1SDimitry Andric       C->dump();
2172145449b1SDimitry Andric #endif
2173145449b1SDimitry Andric       llvm_unreachable("Unknown constant!");
2174145449b1SDimitry Andric     }
2175145449b1SDimitry Andric     Stream.EmitRecord(Code, Record, AbbrevToUse);
2176145449b1SDimitry Andric     Record.clear();
2177145449b1SDimitry Andric   }
2178145449b1SDimitry Andric 
2179145449b1SDimitry Andric   Stream.ExitBlock();
2180145449b1SDimitry Andric }
2181145449b1SDimitry Andric 
writeModuleConstants()2182145449b1SDimitry Andric void DXILBitcodeWriter::writeModuleConstants() {
2183145449b1SDimitry Andric   const ValueEnumerator::ValueList &Vals = VE.getValues();
2184145449b1SDimitry Andric 
2185145449b1SDimitry Andric   // Find the first constant to emit, which is the first non-globalvalue value.
2186145449b1SDimitry Andric   // We know globalvalues have been emitted by WriteModuleInfo.
2187145449b1SDimitry Andric   for (unsigned i = 0, e = Vals.size(); i != e; ++i) {
2188145449b1SDimitry Andric     if (!isa<GlobalValue>(Vals[i].first)) {
2189145449b1SDimitry Andric       writeConstants(i, Vals.size(), true);
2190145449b1SDimitry Andric       return;
2191145449b1SDimitry Andric     }
2192145449b1SDimitry Andric   }
2193145449b1SDimitry Andric }
2194145449b1SDimitry Andric 
2195145449b1SDimitry Andric /// pushValueAndType - The file has to encode both the value and type id for
2196145449b1SDimitry Andric /// many values, because we need to know what type to create for forward
2197145449b1SDimitry Andric /// references.  However, most operands are not forward references, so this type
2198145449b1SDimitry Andric /// field is not needed.
2199145449b1SDimitry Andric ///
2200145449b1SDimitry Andric /// This function adds V's value ID to Vals.  If the value ID is higher than the
2201145449b1SDimitry Andric /// instruction ID, then it is a forward reference, and it also includes the
2202145449b1SDimitry Andric /// type ID.  The value ID that is written is encoded relative to the InstID.
pushValueAndType(const Value * V,unsigned InstID,SmallVectorImpl<unsigned> & Vals)2203145449b1SDimitry Andric bool DXILBitcodeWriter::pushValueAndType(const Value *V, unsigned InstID,
2204145449b1SDimitry Andric                                          SmallVectorImpl<unsigned> &Vals) {
2205145449b1SDimitry Andric   unsigned ValID = VE.getValueID(V);
2206145449b1SDimitry Andric   // Make encoding relative to the InstID.
2207145449b1SDimitry Andric   Vals.push_back(InstID - ValID);
2208145449b1SDimitry Andric   if (ValID >= InstID) {
2209145449b1SDimitry Andric     Vals.push_back(getTypeID(V->getType(), V));
2210145449b1SDimitry Andric     return true;
2211145449b1SDimitry Andric   }
2212145449b1SDimitry Andric   return false;
2213145449b1SDimitry Andric }
2214145449b1SDimitry Andric 
2215145449b1SDimitry Andric /// pushValue - Like pushValueAndType, but where the type of the value is
2216145449b1SDimitry Andric /// omitted (perhaps it was already encoded in an earlier operand).
pushValue(const Value * V,unsigned InstID,SmallVectorImpl<unsigned> & Vals)2217145449b1SDimitry Andric void DXILBitcodeWriter::pushValue(const Value *V, unsigned InstID,
2218145449b1SDimitry Andric                                   SmallVectorImpl<unsigned> &Vals) {
2219145449b1SDimitry Andric   unsigned ValID = VE.getValueID(V);
2220145449b1SDimitry Andric   Vals.push_back(InstID - ValID);
2221145449b1SDimitry Andric }
2222145449b1SDimitry Andric 
pushValueSigned(const Value * V,unsigned InstID,SmallVectorImpl<uint64_t> & Vals)2223145449b1SDimitry Andric void DXILBitcodeWriter::pushValueSigned(const Value *V, unsigned InstID,
2224145449b1SDimitry Andric                                         SmallVectorImpl<uint64_t> &Vals) {
2225145449b1SDimitry Andric   unsigned ValID = VE.getValueID(V);
2226145449b1SDimitry Andric   int64_t diff = ((int32_t)InstID - (int32_t)ValID);
2227145449b1SDimitry Andric   emitSignedInt64(Vals, diff);
2228145449b1SDimitry Andric }
2229145449b1SDimitry Andric 
2230145449b1SDimitry Andric /// WriteInstruction - Emit an instruction
writeInstruction(const Instruction & I,unsigned InstID,SmallVectorImpl<unsigned> & Vals)2231145449b1SDimitry Andric void DXILBitcodeWriter::writeInstruction(const Instruction &I, unsigned InstID,
2232145449b1SDimitry Andric                                          SmallVectorImpl<unsigned> &Vals) {
2233145449b1SDimitry Andric   unsigned Code = 0;
2234145449b1SDimitry Andric   unsigned AbbrevToUse = 0;
2235145449b1SDimitry Andric   VE.setInstructionID(&I);
2236145449b1SDimitry Andric   switch (I.getOpcode()) {
2237145449b1SDimitry Andric   default:
2238145449b1SDimitry Andric     if (Instruction::isCast(I.getOpcode())) {
2239145449b1SDimitry Andric       Code = bitc::FUNC_CODE_INST_CAST;
2240145449b1SDimitry Andric       if (!pushValueAndType(I.getOperand(0), InstID, Vals))
2241145449b1SDimitry Andric         AbbrevToUse = (unsigned)FUNCTION_INST_CAST_ABBREV;
2242145449b1SDimitry Andric       Vals.push_back(getTypeID(I.getType(), &I));
2243145449b1SDimitry Andric       Vals.push_back(getEncodedCastOpcode(I.getOpcode()));
2244145449b1SDimitry Andric     } else {
2245145449b1SDimitry Andric       assert(isa<BinaryOperator>(I) && "Unknown instruction!");
2246145449b1SDimitry Andric       Code = bitc::FUNC_CODE_INST_BINOP;
2247145449b1SDimitry Andric       if (!pushValueAndType(I.getOperand(0), InstID, Vals))
2248145449b1SDimitry Andric         AbbrevToUse = (unsigned)FUNCTION_INST_BINOP_ABBREV;
2249145449b1SDimitry Andric       pushValue(I.getOperand(1), InstID, Vals);
2250145449b1SDimitry Andric       Vals.push_back(getEncodedBinaryOpcode(I.getOpcode()));
2251145449b1SDimitry Andric       uint64_t Flags = getOptimizationFlags(&I);
2252145449b1SDimitry Andric       if (Flags != 0) {
2253145449b1SDimitry Andric         if (AbbrevToUse == (unsigned)FUNCTION_INST_BINOP_ABBREV)
2254145449b1SDimitry Andric           AbbrevToUse = (unsigned)FUNCTION_INST_BINOP_FLAGS_ABBREV;
2255145449b1SDimitry Andric         Vals.push_back(Flags);
2256145449b1SDimitry Andric       }
2257145449b1SDimitry Andric     }
2258145449b1SDimitry Andric     break;
2259145449b1SDimitry Andric 
2260145449b1SDimitry Andric   case Instruction::GetElementPtr: {
2261145449b1SDimitry Andric     Code = bitc::FUNC_CODE_INST_GEP;
2262145449b1SDimitry Andric     AbbrevToUse = (unsigned)FUNCTION_INST_GEP_ABBREV;
2263145449b1SDimitry Andric     auto &GEPInst = cast<GetElementPtrInst>(I);
2264145449b1SDimitry Andric     Vals.push_back(GEPInst.isInBounds());
2265145449b1SDimitry Andric     Vals.push_back(getTypeID(GEPInst.getSourceElementType()));
2266145449b1SDimitry Andric     for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
2267145449b1SDimitry Andric       pushValueAndType(I.getOperand(i), InstID, Vals);
2268145449b1SDimitry Andric     break;
2269145449b1SDimitry Andric   }
2270145449b1SDimitry Andric   case Instruction::ExtractValue: {
2271145449b1SDimitry Andric     Code = bitc::FUNC_CODE_INST_EXTRACTVAL;
2272145449b1SDimitry Andric     pushValueAndType(I.getOperand(0), InstID, Vals);
2273145449b1SDimitry Andric     const ExtractValueInst *EVI = cast<ExtractValueInst>(&I);
2274145449b1SDimitry Andric     Vals.append(EVI->idx_begin(), EVI->idx_end());
2275145449b1SDimitry Andric     break;
2276145449b1SDimitry Andric   }
2277145449b1SDimitry Andric   case Instruction::InsertValue: {
2278145449b1SDimitry Andric     Code = bitc::FUNC_CODE_INST_INSERTVAL;
2279145449b1SDimitry Andric     pushValueAndType(I.getOperand(0), InstID, Vals);
2280145449b1SDimitry Andric     pushValueAndType(I.getOperand(1), InstID, Vals);
2281145449b1SDimitry Andric     const InsertValueInst *IVI = cast<InsertValueInst>(&I);
2282145449b1SDimitry Andric     Vals.append(IVI->idx_begin(), IVI->idx_end());
2283145449b1SDimitry Andric     break;
2284145449b1SDimitry Andric   }
2285145449b1SDimitry Andric   case Instruction::Select:
2286145449b1SDimitry Andric     Code = bitc::FUNC_CODE_INST_VSELECT;
2287145449b1SDimitry Andric     pushValueAndType(I.getOperand(1), InstID, Vals);
2288145449b1SDimitry Andric     pushValue(I.getOperand(2), InstID, Vals);
2289145449b1SDimitry Andric     pushValueAndType(I.getOperand(0), InstID, Vals);
2290145449b1SDimitry Andric     break;
2291145449b1SDimitry Andric   case Instruction::ExtractElement:
2292145449b1SDimitry Andric     Code = bitc::FUNC_CODE_INST_EXTRACTELT;
2293145449b1SDimitry Andric     pushValueAndType(I.getOperand(0), InstID, Vals);
2294145449b1SDimitry Andric     pushValueAndType(I.getOperand(1), InstID, Vals);
2295145449b1SDimitry Andric     break;
2296145449b1SDimitry Andric   case Instruction::InsertElement:
2297145449b1SDimitry Andric     Code = bitc::FUNC_CODE_INST_INSERTELT;
2298145449b1SDimitry Andric     pushValueAndType(I.getOperand(0), InstID, Vals);
2299145449b1SDimitry Andric     pushValue(I.getOperand(1), InstID, Vals);
2300145449b1SDimitry Andric     pushValueAndType(I.getOperand(2), InstID, Vals);
2301145449b1SDimitry Andric     break;
2302145449b1SDimitry Andric   case Instruction::ShuffleVector:
2303145449b1SDimitry Andric     Code = bitc::FUNC_CODE_INST_SHUFFLEVEC;
2304145449b1SDimitry Andric     pushValueAndType(I.getOperand(0), InstID, Vals);
2305145449b1SDimitry Andric     pushValue(I.getOperand(1), InstID, Vals);
2306e3b55780SDimitry Andric     pushValue(cast<ShuffleVectorInst>(&I)->getShuffleMaskForBitcode(), InstID,
2307e3b55780SDimitry Andric               Vals);
2308145449b1SDimitry Andric     break;
2309145449b1SDimitry Andric   case Instruction::ICmp:
2310145449b1SDimitry Andric   case Instruction::FCmp: {
2311145449b1SDimitry Andric     // compare returning Int1Ty or vector of Int1Ty
2312145449b1SDimitry Andric     Code = bitc::FUNC_CODE_INST_CMP2;
2313145449b1SDimitry Andric     pushValueAndType(I.getOperand(0), InstID, Vals);
2314145449b1SDimitry Andric     pushValue(I.getOperand(1), InstID, Vals);
2315145449b1SDimitry Andric     Vals.push_back(cast<CmpInst>(I).getPredicate());
2316145449b1SDimitry Andric     uint64_t Flags = getOptimizationFlags(&I);
2317145449b1SDimitry Andric     if (Flags != 0)
2318145449b1SDimitry Andric       Vals.push_back(Flags);
2319145449b1SDimitry Andric     break;
2320145449b1SDimitry Andric   }
2321145449b1SDimitry Andric 
2322145449b1SDimitry Andric   case Instruction::Ret: {
2323145449b1SDimitry Andric     Code = bitc::FUNC_CODE_INST_RET;
2324145449b1SDimitry Andric     unsigned NumOperands = I.getNumOperands();
2325145449b1SDimitry Andric     if (NumOperands == 0)
2326145449b1SDimitry Andric       AbbrevToUse = (unsigned)FUNCTION_INST_RET_VOID_ABBREV;
2327145449b1SDimitry Andric     else if (NumOperands == 1) {
2328145449b1SDimitry Andric       if (!pushValueAndType(I.getOperand(0), InstID, Vals))
2329145449b1SDimitry Andric         AbbrevToUse = (unsigned)FUNCTION_INST_RET_VAL_ABBREV;
2330145449b1SDimitry Andric     } else {
2331145449b1SDimitry Andric       for (unsigned i = 0, e = NumOperands; i != e; ++i)
2332145449b1SDimitry Andric         pushValueAndType(I.getOperand(i), InstID, Vals);
2333145449b1SDimitry Andric     }
2334145449b1SDimitry Andric   } break;
2335145449b1SDimitry Andric   case Instruction::Br: {
2336145449b1SDimitry Andric     Code = bitc::FUNC_CODE_INST_BR;
2337145449b1SDimitry Andric     const BranchInst &II = cast<BranchInst>(I);
2338145449b1SDimitry Andric     Vals.push_back(VE.getValueID(II.getSuccessor(0)));
2339145449b1SDimitry Andric     if (II.isConditional()) {
2340145449b1SDimitry Andric       Vals.push_back(VE.getValueID(II.getSuccessor(1)));
2341145449b1SDimitry Andric       pushValue(II.getCondition(), InstID, Vals);
2342145449b1SDimitry Andric     }
2343145449b1SDimitry Andric   } break;
2344145449b1SDimitry Andric   case Instruction::Switch: {
2345145449b1SDimitry Andric     Code = bitc::FUNC_CODE_INST_SWITCH;
2346145449b1SDimitry Andric     const SwitchInst &SI = cast<SwitchInst>(I);
2347145449b1SDimitry Andric     Vals.push_back(getTypeID(SI.getCondition()->getType()));
2348145449b1SDimitry Andric     pushValue(SI.getCondition(), InstID, Vals);
2349145449b1SDimitry Andric     Vals.push_back(VE.getValueID(SI.getDefaultDest()));
2350145449b1SDimitry Andric     for (auto Case : SI.cases()) {
2351145449b1SDimitry Andric       Vals.push_back(VE.getValueID(Case.getCaseValue()));
2352145449b1SDimitry Andric       Vals.push_back(VE.getValueID(Case.getCaseSuccessor()));
2353145449b1SDimitry Andric     }
2354145449b1SDimitry Andric   } break;
2355145449b1SDimitry Andric   case Instruction::IndirectBr:
2356145449b1SDimitry Andric     Code = bitc::FUNC_CODE_INST_INDIRECTBR;
2357145449b1SDimitry Andric     Vals.push_back(getTypeID(I.getOperand(0)->getType()));
2358145449b1SDimitry Andric     // Encode the address operand as relative, but not the basic blocks.
2359145449b1SDimitry Andric     pushValue(I.getOperand(0), InstID, Vals);
2360145449b1SDimitry Andric     for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i)
2361145449b1SDimitry Andric       Vals.push_back(VE.getValueID(I.getOperand(i)));
2362145449b1SDimitry Andric     break;
2363145449b1SDimitry Andric 
2364145449b1SDimitry Andric   case Instruction::Invoke: {
2365145449b1SDimitry Andric     const InvokeInst *II = cast<InvokeInst>(&I);
2366145449b1SDimitry Andric     const Value *Callee = II->getCalledOperand();
2367145449b1SDimitry Andric     FunctionType *FTy = II->getFunctionType();
2368145449b1SDimitry Andric     Code = bitc::FUNC_CODE_INST_INVOKE;
2369145449b1SDimitry Andric 
2370145449b1SDimitry Andric     Vals.push_back(VE.getAttributeListID(II->getAttributes()));
2371145449b1SDimitry Andric     Vals.push_back(II->getCallingConv() | 1 << 13);
2372145449b1SDimitry Andric     Vals.push_back(VE.getValueID(II->getNormalDest()));
2373145449b1SDimitry Andric     Vals.push_back(VE.getValueID(II->getUnwindDest()));
2374145449b1SDimitry Andric     Vals.push_back(getTypeID(FTy));
2375145449b1SDimitry Andric     pushValueAndType(Callee, InstID, Vals);
2376145449b1SDimitry Andric 
2377145449b1SDimitry Andric     // Emit value #'s for the fixed parameters.
2378145449b1SDimitry Andric     for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
2379145449b1SDimitry Andric       pushValue(I.getOperand(i), InstID, Vals); // fixed param.
2380145449b1SDimitry Andric 
2381145449b1SDimitry Andric     // Emit type/value pairs for varargs params.
2382145449b1SDimitry Andric     if (FTy->isVarArg()) {
2383145449b1SDimitry Andric       for (unsigned i = FTy->getNumParams(), e = I.getNumOperands() - 3; i != e;
2384145449b1SDimitry Andric            ++i)
2385145449b1SDimitry Andric         pushValueAndType(I.getOperand(i), InstID, Vals); // vararg
2386145449b1SDimitry Andric     }
2387145449b1SDimitry Andric     break;
2388145449b1SDimitry Andric   }
2389145449b1SDimitry Andric   case Instruction::Resume:
2390145449b1SDimitry Andric     Code = bitc::FUNC_CODE_INST_RESUME;
2391145449b1SDimitry Andric     pushValueAndType(I.getOperand(0), InstID, Vals);
2392145449b1SDimitry Andric     break;
2393145449b1SDimitry Andric   case Instruction::Unreachable:
2394145449b1SDimitry Andric     Code = bitc::FUNC_CODE_INST_UNREACHABLE;
2395145449b1SDimitry Andric     AbbrevToUse = (unsigned)FUNCTION_INST_UNREACHABLE_ABBREV;
2396145449b1SDimitry Andric     break;
2397145449b1SDimitry Andric 
2398145449b1SDimitry Andric   case Instruction::PHI: {
2399145449b1SDimitry Andric     const PHINode &PN = cast<PHINode>(I);
2400145449b1SDimitry Andric     Code = bitc::FUNC_CODE_INST_PHI;
2401145449b1SDimitry Andric     // With the newer instruction encoding, forward references could give
2402145449b1SDimitry Andric     // negative valued IDs.  This is most common for PHIs, so we use
2403145449b1SDimitry Andric     // signed VBRs.
2404145449b1SDimitry Andric     SmallVector<uint64_t, 128> Vals64;
2405145449b1SDimitry Andric     Vals64.push_back(getTypeID(PN.getType()));
2406145449b1SDimitry Andric     for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
2407145449b1SDimitry Andric       pushValueSigned(PN.getIncomingValue(i), InstID, Vals64);
2408145449b1SDimitry Andric       Vals64.push_back(VE.getValueID(PN.getIncomingBlock(i)));
2409145449b1SDimitry Andric     }
2410145449b1SDimitry Andric     // Emit a Vals64 vector and exit.
2411145449b1SDimitry Andric     Stream.EmitRecord(Code, Vals64, AbbrevToUse);
2412145449b1SDimitry Andric     Vals64.clear();
2413145449b1SDimitry Andric     return;
2414145449b1SDimitry Andric   }
2415145449b1SDimitry Andric 
2416145449b1SDimitry Andric   case Instruction::LandingPad: {
2417145449b1SDimitry Andric     const LandingPadInst &LP = cast<LandingPadInst>(I);
2418145449b1SDimitry Andric     Code = bitc::FUNC_CODE_INST_LANDINGPAD;
2419145449b1SDimitry Andric     Vals.push_back(getTypeID(LP.getType()));
2420145449b1SDimitry Andric     Vals.push_back(LP.isCleanup());
2421145449b1SDimitry Andric     Vals.push_back(LP.getNumClauses());
2422145449b1SDimitry Andric     for (unsigned I = 0, E = LP.getNumClauses(); I != E; ++I) {
2423145449b1SDimitry Andric       if (LP.isCatch(I))
2424145449b1SDimitry Andric         Vals.push_back(LandingPadInst::Catch);
2425145449b1SDimitry Andric       else
2426145449b1SDimitry Andric         Vals.push_back(LandingPadInst::Filter);
2427145449b1SDimitry Andric       pushValueAndType(LP.getClause(I), InstID, Vals);
2428145449b1SDimitry Andric     }
2429145449b1SDimitry Andric     break;
2430145449b1SDimitry Andric   }
2431145449b1SDimitry Andric 
2432145449b1SDimitry Andric   case Instruction::Alloca: {
2433145449b1SDimitry Andric     Code = bitc::FUNC_CODE_INST_ALLOCA;
2434145449b1SDimitry Andric     const AllocaInst &AI = cast<AllocaInst>(I);
2435145449b1SDimitry Andric     Vals.push_back(getTypeID(AI.getAllocatedType()));
2436145449b1SDimitry Andric     Vals.push_back(getTypeID(I.getOperand(0)->getType()));
2437145449b1SDimitry Andric     Vals.push_back(VE.getValueID(I.getOperand(0))); // size.
2438e3b55780SDimitry Andric     unsigned AlignRecord = Log2_32(AI.getAlign().value()) + 1;
2439e3b55780SDimitry Andric     assert(AlignRecord < 1 << 5 && "alignment greater than 1 << 64");
2440e3b55780SDimitry Andric     AlignRecord |= AI.isUsedWithInAlloca() << 5;
2441e3b55780SDimitry Andric     AlignRecord |= 1 << 6;
2442e3b55780SDimitry Andric     Vals.push_back(AlignRecord);
2443145449b1SDimitry Andric     break;
2444145449b1SDimitry Andric   }
2445145449b1SDimitry Andric 
2446145449b1SDimitry Andric   case Instruction::Load:
2447145449b1SDimitry Andric     if (cast<LoadInst>(I).isAtomic()) {
2448145449b1SDimitry Andric       Code = bitc::FUNC_CODE_INST_LOADATOMIC;
2449145449b1SDimitry Andric       pushValueAndType(I.getOperand(0), InstID, Vals);
2450145449b1SDimitry Andric     } else {
2451145449b1SDimitry Andric       Code = bitc::FUNC_CODE_INST_LOAD;
2452145449b1SDimitry Andric       if (!pushValueAndType(I.getOperand(0), InstID, Vals)) // ptr
2453145449b1SDimitry Andric         AbbrevToUse = (unsigned)FUNCTION_INST_LOAD_ABBREV;
2454145449b1SDimitry Andric     }
2455145449b1SDimitry Andric     Vals.push_back(getTypeID(I.getType()));
2456145449b1SDimitry Andric     Vals.push_back(Log2(cast<LoadInst>(I).getAlign()) + 1);
2457145449b1SDimitry Andric     Vals.push_back(cast<LoadInst>(I).isVolatile());
2458145449b1SDimitry Andric     if (cast<LoadInst>(I).isAtomic()) {
2459145449b1SDimitry Andric       Vals.push_back(getEncodedOrdering(cast<LoadInst>(I).getOrdering()));
2460145449b1SDimitry Andric       Vals.push_back(getEncodedSyncScopeID(cast<LoadInst>(I).getSyncScopeID()));
2461145449b1SDimitry Andric     }
2462145449b1SDimitry Andric     break;
2463145449b1SDimitry Andric   case Instruction::Store:
2464145449b1SDimitry Andric     if (cast<StoreInst>(I).isAtomic())
2465145449b1SDimitry Andric       Code = bitc::FUNC_CODE_INST_STOREATOMIC;
2466145449b1SDimitry Andric     else
2467145449b1SDimitry Andric       Code = bitc::FUNC_CODE_INST_STORE;
2468145449b1SDimitry Andric     pushValueAndType(I.getOperand(1), InstID, Vals); // ptrty + ptr
2469145449b1SDimitry Andric     pushValueAndType(I.getOperand(0), InstID, Vals); // valty + val
2470145449b1SDimitry Andric     Vals.push_back(Log2(cast<StoreInst>(I).getAlign()) + 1);
2471145449b1SDimitry Andric     Vals.push_back(cast<StoreInst>(I).isVolatile());
2472145449b1SDimitry Andric     if (cast<StoreInst>(I).isAtomic()) {
2473145449b1SDimitry Andric       Vals.push_back(getEncodedOrdering(cast<StoreInst>(I).getOrdering()));
2474145449b1SDimitry Andric       Vals.push_back(
2475145449b1SDimitry Andric           getEncodedSyncScopeID(cast<StoreInst>(I).getSyncScopeID()));
2476145449b1SDimitry Andric     }
2477145449b1SDimitry Andric     break;
2478145449b1SDimitry Andric   case Instruction::AtomicCmpXchg:
2479145449b1SDimitry Andric     Code = bitc::FUNC_CODE_INST_CMPXCHG;
2480145449b1SDimitry Andric     pushValueAndType(I.getOperand(0), InstID, Vals); // ptrty + ptr
2481145449b1SDimitry Andric     pushValueAndType(I.getOperand(1), InstID, Vals); // cmp.
2482145449b1SDimitry Andric     pushValue(I.getOperand(2), InstID, Vals);        // newval.
2483145449b1SDimitry Andric     Vals.push_back(cast<AtomicCmpXchgInst>(I).isVolatile());
2484145449b1SDimitry Andric     Vals.push_back(
2485145449b1SDimitry Andric         getEncodedOrdering(cast<AtomicCmpXchgInst>(I).getSuccessOrdering()));
2486145449b1SDimitry Andric     Vals.push_back(
2487145449b1SDimitry Andric         getEncodedSyncScopeID(cast<AtomicCmpXchgInst>(I).getSyncScopeID()));
2488145449b1SDimitry Andric     Vals.push_back(
2489145449b1SDimitry Andric         getEncodedOrdering(cast<AtomicCmpXchgInst>(I).getFailureOrdering()));
2490145449b1SDimitry Andric     Vals.push_back(cast<AtomicCmpXchgInst>(I).isWeak());
2491145449b1SDimitry Andric     break;
2492145449b1SDimitry Andric   case Instruction::AtomicRMW:
2493145449b1SDimitry Andric     Code = bitc::FUNC_CODE_INST_ATOMICRMW;
2494145449b1SDimitry Andric     pushValueAndType(I.getOperand(0), InstID, Vals); // ptrty + ptr
2495145449b1SDimitry Andric     pushValue(I.getOperand(1), InstID, Vals);        // val.
2496145449b1SDimitry Andric     Vals.push_back(
2497145449b1SDimitry Andric         getEncodedRMWOperation(cast<AtomicRMWInst>(I).getOperation()));
2498145449b1SDimitry Andric     Vals.push_back(cast<AtomicRMWInst>(I).isVolatile());
2499145449b1SDimitry Andric     Vals.push_back(getEncodedOrdering(cast<AtomicRMWInst>(I).getOrdering()));
2500145449b1SDimitry Andric     Vals.push_back(
2501145449b1SDimitry Andric         getEncodedSyncScopeID(cast<AtomicRMWInst>(I).getSyncScopeID()));
2502145449b1SDimitry Andric     break;
2503145449b1SDimitry Andric   case Instruction::Fence:
2504145449b1SDimitry Andric     Code = bitc::FUNC_CODE_INST_FENCE;
2505145449b1SDimitry Andric     Vals.push_back(getEncodedOrdering(cast<FenceInst>(I).getOrdering()));
2506145449b1SDimitry Andric     Vals.push_back(getEncodedSyncScopeID(cast<FenceInst>(I).getSyncScopeID()));
2507145449b1SDimitry Andric     break;
2508145449b1SDimitry Andric   case Instruction::Call: {
2509145449b1SDimitry Andric     const CallInst &CI = cast<CallInst>(I);
2510145449b1SDimitry Andric     FunctionType *FTy = CI.getFunctionType();
2511145449b1SDimitry Andric 
2512145449b1SDimitry Andric     Code = bitc::FUNC_CODE_INST_CALL;
2513145449b1SDimitry Andric 
2514145449b1SDimitry Andric     Vals.push_back(VE.getAttributeListID(CI.getAttributes()));
2515145449b1SDimitry Andric     Vals.push_back((CI.getCallingConv() << 1) | unsigned(CI.isTailCall()) |
2516145449b1SDimitry Andric                    unsigned(CI.isMustTailCall()) << 14 | 1 << 15);
2517e3b55780SDimitry Andric     Vals.push_back(getGlobalObjectValueTypeID(FTy, CI.getCalledFunction()));
2518145449b1SDimitry Andric     pushValueAndType(CI.getCalledOperand(), InstID, Vals); // Callee
2519145449b1SDimitry Andric 
2520145449b1SDimitry Andric     // Emit value #'s for the fixed parameters.
2521145449b1SDimitry Andric     for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i) {
2522145449b1SDimitry Andric       // Check for labels (can happen with asm labels).
2523145449b1SDimitry Andric       if (FTy->getParamType(i)->isLabelTy())
2524145449b1SDimitry Andric         Vals.push_back(VE.getValueID(CI.getArgOperand(i)));
2525145449b1SDimitry Andric       else
2526145449b1SDimitry Andric         pushValue(CI.getArgOperand(i), InstID, Vals); // fixed param.
2527145449b1SDimitry Andric     }
2528145449b1SDimitry Andric 
2529145449b1SDimitry Andric     // Emit type/value pairs for varargs params.
2530145449b1SDimitry Andric     if (FTy->isVarArg()) {
2531145449b1SDimitry Andric       for (unsigned i = FTy->getNumParams(), e = CI.arg_size(); i != e; ++i)
2532145449b1SDimitry Andric         pushValueAndType(CI.getArgOperand(i), InstID, Vals); // varargs
2533145449b1SDimitry Andric     }
2534145449b1SDimitry Andric     break;
2535145449b1SDimitry Andric   }
2536145449b1SDimitry Andric   case Instruction::VAArg:
2537145449b1SDimitry Andric     Code = bitc::FUNC_CODE_INST_VAARG;
2538145449b1SDimitry Andric     Vals.push_back(getTypeID(I.getOperand(0)->getType())); // valistty
2539145449b1SDimitry Andric     pushValue(I.getOperand(0), InstID, Vals);              // valist.
2540145449b1SDimitry Andric     Vals.push_back(getTypeID(I.getType()));                // restype.
2541145449b1SDimitry Andric     break;
2542145449b1SDimitry Andric   }
2543145449b1SDimitry Andric 
2544145449b1SDimitry Andric   Stream.EmitRecord(Code, Vals, AbbrevToUse);
2545145449b1SDimitry Andric   Vals.clear();
2546145449b1SDimitry Andric }
2547145449b1SDimitry Andric 
2548145449b1SDimitry Andric // Emit names for globals/functions etc.
writeFunctionLevelValueSymbolTable(const ValueSymbolTable & VST)2549145449b1SDimitry Andric void DXILBitcodeWriter::writeFunctionLevelValueSymbolTable(
2550145449b1SDimitry Andric     const ValueSymbolTable &VST) {
2551145449b1SDimitry Andric   if (VST.empty())
2552145449b1SDimitry Andric     return;
2553145449b1SDimitry Andric   Stream.EnterSubblock(bitc::VALUE_SYMTAB_BLOCK_ID, 4);
2554145449b1SDimitry Andric 
2555145449b1SDimitry Andric   SmallVector<unsigned, 64> NameVals;
2556145449b1SDimitry Andric 
2557145449b1SDimitry Andric   // HLSL Change
2558145449b1SDimitry Andric   // Read the named values from a sorted list instead of the original list
2559145449b1SDimitry Andric   // to ensure the binary is the same no matter what values ever existed.
2560145449b1SDimitry Andric   SmallVector<const ValueName *, 16> SortedTable;
2561145449b1SDimitry Andric 
2562145449b1SDimitry Andric   for (auto &VI : VST) {
2563145449b1SDimitry Andric     SortedTable.push_back(VI.second->getValueName());
2564145449b1SDimitry Andric   }
2565145449b1SDimitry Andric   // The keys are unique, so there shouldn't be stability issues.
25664b4fe385SDimitry Andric   llvm::sort(SortedTable, [](const ValueName *A, const ValueName *B) {
2567145449b1SDimitry Andric     return A->first() < B->first();
2568145449b1SDimitry Andric   });
2569145449b1SDimitry Andric 
2570145449b1SDimitry Andric   for (const ValueName *SI : SortedTable) {
2571145449b1SDimitry Andric     auto &Name = *SI;
2572145449b1SDimitry Andric 
2573145449b1SDimitry Andric     // Figure out the encoding to use for the name.
2574145449b1SDimitry Andric     bool is7Bit = true;
2575145449b1SDimitry Andric     bool isChar6 = true;
2576145449b1SDimitry Andric     for (const char *C = Name.getKeyData(), *E = C + Name.getKeyLength();
2577145449b1SDimitry Andric          C != E; ++C) {
2578145449b1SDimitry Andric       if (isChar6)
2579145449b1SDimitry Andric         isChar6 = BitCodeAbbrevOp::isChar6(*C);
2580145449b1SDimitry Andric       if ((unsigned char)*C & 128) {
2581145449b1SDimitry Andric         is7Bit = false;
2582145449b1SDimitry Andric         break; // don't bother scanning the rest.
2583145449b1SDimitry Andric       }
2584145449b1SDimitry Andric     }
2585145449b1SDimitry Andric 
2586145449b1SDimitry Andric     unsigned AbbrevToUse = VST_ENTRY_8_ABBREV;
2587145449b1SDimitry Andric 
2588145449b1SDimitry Andric     // VST_ENTRY:   [valueid, namechar x N]
2589145449b1SDimitry Andric     // VST_BBENTRY: [bbid, namechar x N]
2590145449b1SDimitry Andric     unsigned Code;
2591145449b1SDimitry Andric     if (isa<BasicBlock>(SI->getValue())) {
2592145449b1SDimitry Andric       Code = bitc::VST_CODE_BBENTRY;
2593145449b1SDimitry Andric       if (isChar6)
2594145449b1SDimitry Andric         AbbrevToUse = VST_BBENTRY_6_ABBREV;
2595145449b1SDimitry Andric     } else {
2596145449b1SDimitry Andric       Code = bitc::VST_CODE_ENTRY;
2597145449b1SDimitry Andric       if (isChar6)
2598145449b1SDimitry Andric         AbbrevToUse = VST_ENTRY_6_ABBREV;
2599145449b1SDimitry Andric       else if (is7Bit)
2600145449b1SDimitry Andric         AbbrevToUse = VST_ENTRY_7_ABBREV;
2601145449b1SDimitry Andric     }
2602145449b1SDimitry Andric 
2603145449b1SDimitry Andric     NameVals.push_back(VE.getValueID(SI->getValue()));
2604145449b1SDimitry Andric     for (const char *P = Name.getKeyData(),
2605145449b1SDimitry Andric                     *E = Name.getKeyData() + Name.getKeyLength();
2606145449b1SDimitry Andric          P != E; ++P)
2607145449b1SDimitry Andric       NameVals.push_back((unsigned char)*P);
2608145449b1SDimitry Andric 
2609145449b1SDimitry Andric     // Emit the finished record.
2610145449b1SDimitry Andric     Stream.EmitRecord(Code, NameVals, AbbrevToUse);
2611145449b1SDimitry Andric     NameVals.clear();
2612145449b1SDimitry Andric   }
2613145449b1SDimitry Andric   Stream.ExitBlock();
2614145449b1SDimitry Andric }
2615145449b1SDimitry Andric 
2616145449b1SDimitry Andric /// Emit a function body to the module stream.
writeFunction(const Function & F)2617145449b1SDimitry Andric void DXILBitcodeWriter::writeFunction(const Function &F) {
2618145449b1SDimitry Andric   Stream.EnterSubblock(bitc::FUNCTION_BLOCK_ID, 4);
2619145449b1SDimitry Andric   VE.incorporateFunction(F);
2620145449b1SDimitry Andric 
2621145449b1SDimitry Andric   SmallVector<unsigned, 64> Vals;
2622145449b1SDimitry Andric 
2623145449b1SDimitry Andric   // Emit the number of basic blocks, so the reader can create them ahead of
2624145449b1SDimitry Andric   // time.
2625145449b1SDimitry Andric   Vals.push_back(VE.getBasicBlocks().size());
2626145449b1SDimitry Andric   Stream.EmitRecord(bitc::FUNC_CODE_DECLAREBLOCKS, Vals);
2627145449b1SDimitry Andric   Vals.clear();
2628145449b1SDimitry Andric 
2629145449b1SDimitry Andric   // If there are function-local constants, emit them now.
2630145449b1SDimitry Andric   unsigned CstStart, CstEnd;
2631145449b1SDimitry Andric   VE.getFunctionConstantRange(CstStart, CstEnd);
2632145449b1SDimitry Andric   writeConstants(CstStart, CstEnd, false);
2633145449b1SDimitry Andric 
2634145449b1SDimitry Andric   // If there is function-local metadata, emit it now.
2635145449b1SDimitry Andric   writeFunctionMetadata(F);
2636145449b1SDimitry Andric 
2637145449b1SDimitry Andric   // Keep a running idea of what the instruction ID is.
2638145449b1SDimitry Andric   unsigned InstID = CstEnd;
2639145449b1SDimitry Andric 
2640145449b1SDimitry Andric   bool NeedsMetadataAttachment = F.hasMetadata();
2641145449b1SDimitry Andric 
2642145449b1SDimitry Andric   DILocation *LastDL = nullptr;
2643145449b1SDimitry Andric 
2644145449b1SDimitry Andric   // Finally, emit all the instructions, in order.
2645145449b1SDimitry Andric   for (Function::const_iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
2646145449b1SDimitry Andric     for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I != E;
2647145449b1SDimitry Andric          ++I) {
2648145449b1SDimitry Andric       writeInstruction(*I, InstID, Vals);
2649145449b1SDimitry Andric 
2650145449b1SDimitry Andric       if (!I->getType()->isVoidTy())
2651145449b1SDimitry Andric         ++InstID;
2652145449b1SDimitry Andric 
2653145449b1SDimitry Andric       // If the instruction has metadata, write a metadata attachment later.
2654145449b1SDimitry Andric       NeedsMetadataAttachment |= I->hasMetadataOtherThanDebugLoc();
2655145449b1SDimitry Andric 
2656145449b1SDimitry Andric       // If the instruction has a debug location, emit it.
2657145449b1SDimitry Andric       DILocation *DL = I->getDebugLoc();
2658145449b1SDimitry Andric       if (!DL)
2659145449b1SDimitry Andric         continue;
2660145449b1SDimitry Andric 
2661145449b1SDimitry Andric       if (DL == LastDL) {
2662145449b1SDimitry Andric         // Just repeat the same debug loc as last time.
2663145449b1SDimitry Andric         Stream.EmitRecord(bitc::FUNC_CODE_DEBUG_LOC_AGAIN, Vals);
2664145449b1SDimitry Andric         continue;
2665145449b1SDimitry Andric       }
2666145449b1SDimitry Andric 
2667145449b1SDimitry Andric       Vals.push_back(DL->getLine());
2668145449b1SDimitry Andric       Vals.push_back(DL->getColumn());
2669145449b1SDimitry Andric       Vals.push_back(VE.getMetadataOrNullID(DL->getScope()));
2670145449b1SDimitry Andric       Vals.push_back(VE.getMetadataOrNullID(DL->getInlinedAt()));
2671145449b1SDimitry Andric       Stream.EmitRecord(bitc::FUNC_CODE_DEBUG_LOC, Vals);
2672145449b1SDimitry Andric       Vals.clear();
2673145449b1SDimitry Andric 
2674145449b1SDimitry Andric       LastDL = DL;
2675145449b1SDimitry Andric     }
2676145449b1SDimitry Andric 
2677145449b1SDimitry Andric   // Emit names for all the instructions etc.
2678145449b1SDimitry Andric   if (auto *Symtab = F.getValueSymbolTable())
2679145449b1SDimitry Andric     writeFunctionLevelValueSymbolTable(*Symtab);
2680145449b1SDimitry Andric 
2681145449b1SDimitry Andric   if (NeedsMetadataAttachment)
2682145449b1SDimitry Andric     writeFunctionMetadataAttachment(F);
2683145449b1SDimitry Andric 
2684145449b1SDimitry Andric   VE.purgeFunction();
2685145449b1SDimitry Andric   Stream.ExitBlock();
2686145449b1SDimitry Andric }
2687145449b1SDimitry Andric 
2688145449b1SDimitry Andric // Emit blockinfo, which defines the standard abbreviations etc.
writeBlockInfo()2689145449b1SDimitry Andric void DXILBitcodeWriter::writeBlockInfo() {
2690145449b1SDimitry Andric   // We only want to emit block info records for blocks that have multiple
2691145449b1SDimitry Andric   // instances: CONSTANTS_BLOCK, FUNCTION_BLOCK and VALUE_SYMTAB_BLOCK.
2692145449b1SDimitry Andric   // Other blocks can define their abbrevs inline.
2693145449b1SDimitry Andric   Stream.EnterBlockInfoBlock();
2694145449b1SDimitry Andric 
2695145449b1SDimitry Andric   { // 8-bit fixed-width VST_ENTRY/VST_BBENTRY strings.
2696145449b1SDimitry Andric     auto Abbv = std::make_shared<BitCodeAbbrev>();
2697145449b1SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 3));
2698145449b1SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
2699145449b1SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
2700145449b1SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
2701145449b1SDimitry Andric     if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID,
2702145449b1SDimitry Andric                                    std::move(Abbv)) != VST_ENTRY_8_ABBREV)
2703145449b1SDimitry Andric       assert(false && "Unexpected abbrev ordering!");
2704145449b1SDimitry Andric   }
2705145449b1SDimitry Andric 
2706145449b1SDimitry Andric   { // 7-bit fixed width VST_ENTRY strings.
2707145449b1SDimitry Andric     auto Abbv = std::make_shared<BitCodeAbbrev>();
2708145449b1SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_ENTRY));
2709145449b1SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
2710145449b1SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
2711145449b1SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7));
2712145449b1SDimitry Andric     if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID,
2713145449b1SDimitry Andric                                    std::move(Abbv)) != VST_ENTRY_7_ABBREV)
2714145449b1SDimitry Andric       assert(false && "Unexpected abbrev ordering!");
2715145449b1SDimitry Andric   }
2716145449b1SDimitry Andric   { // 6-bit char6 VST_ENTRY strings.
2717145449b1SDimitry Andric     auto Abbv = std::make_shared<BitCodeAbbrev>();
2718145449b1SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_ENTRY));
2719145449b1SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
2720145449b1SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
2721145449b1SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
2722145449b1SDimitry Andric     if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID,
2723145449b1SDimitry Andric                                    std::move(Abbv)) != VST_ENTRY_6_ABBREV)
2724145449b1SDimitry Andric       assert(false && "Unexpected abbrev ordering!");
2725145449b1SDimitry Andric   }
2726145449b1SDimitry Andric   { // 6-bit char6 VST_BBENTRY strings.
2727145449b1SDimitry Andric     auto Abbv = std::make_shared<BitCodeAbbrev>();
2728145449b1SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_BBENTRY));
2729145449b1SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
2730145449b1SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
2731145449b1SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
2732145449b1SDimitry Andric     if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID,
2733145449b1SDimitry Andric                                    std::move(Abbv)) != VST_BBENTRY_6_ABBREV)
2734145449b1SDimitry Andric       assert(false && "Unexpected abbrev ordering!");
2735145449b1SDimitry Andric   }
2736145449b1SDimitry Andric 
2737145449b1SDimitry Andric   { // SETTYPE abbrev for CONSTANTS_BLOCK.
2738145449b1SDimitry Andric     auto Abbv = std::make_shared<BitCodeAbbrev>();
2739145449b1SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_SETTYPE));
2740145449b1SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
2741ac9a064cSDimitry Andric                               VE.computeBitsRequiredForTypeIndices()));
2742145449b1SDimitry Andric     if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID, std::move(Abbv)) !=
2743145449b1SDimitry Andric         CONSTANTS_SETTYPE_ABBREV)
2744145449b1SDimitry Andric       assert(false && "Unexpected abbrev ordering!");
2745145449b1SDimitry Andric   }
2746145449b1SDimitry Andric 
2747145449b1SDimitry Andric   { // INTEGER abbrev for CONSTANTS_BLOCK.
2748145449b1SDimitry Andric     auto Abbv = std::make_shared<BitCodeAbbrev>();
2749145449b1SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_INTEGER));
2750145449b1SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
2751145449b1SDimitry Andric     if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID, std::move(Abbv)) !=
2752145449b1SDimitry Andric         CONSTANTS_INTEGER_ABBREV)
2753145449b1SDimitry Andric       assert(false && "Unexpected abbrev ordering!");
2754145449b1SDimitry Andric   }
2755145449b1SDimitry Andric 
2756145449b1SDimitry Andric   { // CE_CAST abbrev for CONSTANTS_BLOCK.
2757145449b1SDimitry Andric     auto Abbv = std::make_shared<BitCodeAbbrev>();
2758145449b1SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_CE_CAST));
2759145449b1SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // cast opc
2760145449b1SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,      // typeid
2761ac9a064cSDimitry Andric                               VE.computeBitsRequiredForTypeIndices()));
2762145449b1SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // value id
2763145449b1SDimitry Andric 
2764145449b1SDimitry Andric     if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID, std::move(Abbv)) !=
2765145449b1SDimitry Andric         CONSTANTS_CE_CAST_Abbrev)
2766145449b1SDimitry Andric       assert(false && "Unexpected abbrev ordering!");
2767145449b1SDimitry Andric   }
2768145449b1SDimitry Andric   { // NULL abbrev for CONSTANTS_BLOCK.
2769145449b1SDimitry Andric     auto Abbv = std::make_shared<BitCodeAbbrev>();
2770145449b1SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_NULL));
2771145449b1SDimitry Andric     if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID, std::move(Abbv)) !=
2772145449b1SDimitry Andric         CONSTANTS_NULL_Abbrev)
2773145449b1SDimitry Andric       assert(false && "Unexpected abbrev ordering!");
2774145449b1SDimitry Andric   }
2775145449b1SDimitry Andric 
2776145449b1SDimitry Andric   // FIXME: This should only use space for first class types!
2777145449b1SDimitry Andric 
2778145449b1SDimitry Andric   { // INST_LOAD abbrev for FUNCTION_BLOCK.
2779145449b1SDimitry Andric     auto Abbv = std::make_shared<BitCodeAbbrev>();
2780145449b1SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_LOAD));
2781145449b1SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Ptr
2782145449b1SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,    // dest ty
2783ac9a064cSDimitry Andric                               VE.computeBitsRequiredForTypeIndices()));
2784145449b1SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4));   // Align
2785145449b1SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // volatile
2786145449b1SDimitry Andric     if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, std::move(Abbv)) !=
2787145449b1SDimitry Andric         (unsigned)FUNCTION_INST_LOAD_ABBREV)
2788145449b1SDimitry Andric       assert(false && "Unexpected abbrev ordering!");
2789145449b1SDimitry Andric   }
2790145449b1SDimitry Andric   { // INST_BINOP abbrev for FUNCTION_BLOCK.
2791145449b1SDimitry Andric     auto Abbv = std::make_shared<BitCodeAbbrev>();
2792145449b1SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_BINOP));
2793145449b1SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));   // LHS
2794145449b1SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));   // RHS
2795145449b1SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
2796145449b1SDimitry Andric     if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, std::move(Abbv)) !=
2797145449b1SDimitry Andric         (unsigned)FUNCTION_INST_BINOP_ABBREV)
2798145449b1SDimitry Andric       assert(false && "Unexpected abbrev ordering!");
2799145449b1SDimitry Andric   }
2800145449b1SDimitry Andric   { // INST_BINOP_FLAGS abbrev for FUNCTION_BLOCK.
2801145449b1SDimitry Andric     auto Abbv = std::make_shared<BitCodeAbbrev>();
2802145449b1SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_BINOP));
2803145449b1SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));   // LHS
2804145449b1SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));   // RHS
2805145449b1SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
2806145449b1SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7)); // flags
2807145449b1SDimitry Andric     if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, std::move(Abbv)) !=
2808145449b1SDimitry Andric         (unsigned)FUNCTION_INST_BINOP_FLAGS_ABBREV)
2809145449b1SDimitry Andric       assert(false && "Unexpected abbrev ordering!");
2810145449b1SDimitry Andric   }
2811145449b1SDimitry Andric   { // INST_CAST abbrev for FUNCTION_BLOCK.
2812145449b1SDimitry Andric     auto Abbv = std::make_shared<BitCodeAbbrev>();
2813145449b1SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_CAST));
2814145449b1SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // OpVal
2815145449b1SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,    // dest ty
2816ac9a064cSDimitry Andric                               VE.computeBitsRequiredForTypeIndices()));
2817145449b1SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
2818145449b1SDimitry Andric     if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, std::move(Abbv)) !=
2819145449b1SDimitry Andric         (unsigned)FUNCTION_INST_CAST_ABBREV)
2820145449b1SDimitry Andric       assert(false && "Unexpected abbrev ordering!");
2821145449b1SDimitry Andric   }
2822145449b1SDimitry Andric 
2823145449b1SDimitry Andric   { // INST_RET abbrev for FUNCTION_BLOCK.
2824145449b1SDimitry Andric     auto Abbv = std::make_shared<BitCodeAbbrev>();
2825145449b1SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_RET));
2826145449b1SDimitry Andric     if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, std::move(Abbv)) !=
2827145449b1SDimitry Andric         (unsigned)FUNCTION_INST_RET_VOID_ABBREV)
2828145449b1SDimitry Andric       assert(false && "Unexpected abbrev ordering!");
2829145449b1SDimitry Andric   }
2830145449b1SDimitry Andric   { // INST_RET abbrev for FUNCTION_BLOCK.
2831145449b1SDimitry Andric     auto Abbv = std::make_shared<BitCodeAbbrev>();
2832145449b1SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_RET));
2833145449b1SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // ValID
2834145449b1SDimitry Andric     if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, std::move(Abbv)) !=
2835145449b1SDimitry Andric         (unsigned)FUNCTION_INST_RET_VAL_ABBREV)
2836145449b1SDimitry Andric       assert(false && "Unexpected abbrev ordering!");
2837145449b1SDimitry Andric   }
2838145449b1SDimitry Andric   { // INST_UNREACHABLE abbrev for FUNCTION_BLOCK.
2839145449b1SDimitry Andric     auto Abbv = std::make_shared<BitCodeAbbrev>();
2840145449b1SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_UNREACHABLE));
2841145449b1SDimitry Andric     if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, std::move(Abbv)) !=
2842145449b1SDimitry Andric         (unsigned)FUNCTION_INST_UNREACHABLE_ABBREV)
2843145449b1SDimitry Andric       assert(false && "Unexpected abbrev ordering!");
2844145449b1SDimitry Andric   }
2845145449b1SDimitry Andric   {
2846145449b1SDimitry Andric     auto Abbv = std::make_shared<BitCodeAbbrev>();
2847145449b1SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_GEP));
2848145449b1SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));
2849145449b1SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, // dest ty
2850145449b1SDimitry Andric                               Log2_32_Ceil(VE.getTypes().size() + 1)));
2851145449b1SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
2852145449b1SDimitry Andric     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
2853145449b1SDimitry Andric     if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, std::move(Abbv)) !=
2854145449b1SDimitry Andric         (unsigned)FUNCTION_INST_GEP_ABBREV)
2855145449b1SDimitry Andric       assert(false && "Unexpected abbrev ordering!");
2856145449b1SDimitry Andric   }
2857145449b1SDimitry Andric 
2858145449b1SDimitry Andric   Stream.ExitBlock();
2859145449b1SDimitry Andric }
2860145449b1SDimitry Andric 
writeModuleVersion()2861145449b1SDimitry Andric void DXILBitcodeWriter::writeModuleVersion() {
2862145449b1SDimitry Andric   // VERSION: [version#]
2863145449b1SDimitry Andric   Stream.EmitRecord(bitc::MODULE_CODE_VERSION, ArrayRef<unsigned>{1});
2864145449b1SDimitry Andric }
2865145449b1SDimitry Andric 
2866145449b1SDimitry Andric /// WriteModule - Emit the specified module to the bitstream.
write()2867145449b1SDimitry Andric void DXILBitcodeWriter::write() {
2868145449b1SDimitry Andric   // The identification block is new since llvm-3.7, but the old bitcode reader
2869145449b1SDimitry Andric   // will skip it.
2870145449b1SDimitry Andric   // writeIdentificationBlock(Stream);
2871145449b1SDimitry Andric 
2872145449b1SDimitry Andric   Stream.EnterSubblock(bitc::MODULE_BLOCK_ID, 3);
2873145449b1SDimitry Andric 
2874145449b1SDimitry Andric   // It is redundant to fully-specify this here, but nice to make it explicit
2875145449b1SDimitry Andric   // so that it is clear the DXIL module version is different.
2876145449b1SDimitry Andric   DXILBitcodeWriter::writeModuleVersion();
2877145449b1SDimitry Andric 
2878145449b1SDimitry Andric   // Emit blockinfo, which defines the standard abbreviations etc.
2879145449b1SDimitry Andric   writeBlockInfo();
2880145449b1SDimitry Andric 
2881145449b1SDimitry Andric   // Emit information about attribute groups.
2882145449b1SDimitry Andric   writeAttributeGroupTable();
2883145449b1SDimitry Andric 
2884145449b1SDimitry Andric   // Emit information about parameter attributes.
2885145449b1SDimitry Andric   writeAttributeTable();
2886145449b1SDimitry Andric 
2887145449b1SDimitry Andric   // Emit information describing all of the types in the module.
2888145449b1SDimitry Andric   writeTypeTable();
2889145449b1SDimitry Andric 
2890145449b1SDimitry Andric   writeComdats();
2891145449b1SDimitry Andric 
2892145449b1SDimitry Andric   // Emit top-level description of module, including target triple, inline asm,
2893145449b1SDimitry Andric   // descriptors for global variables, and function prototype info.
2894145449b1SDimitry Andric   writeModuleInfo();
2895145449b1SDimitry Andric 
2896145449b1SDimitry Andric   // Emit constants.
2897145449b1SDimitry Andric   writeModuleConstants();
2898145449b1SDimitry Andric 
2899145449b1SDimitry Andric   // Emit metadata.
2900145449b1SDimitry Andric   writeModuleMetadataKinds();
2901145449b1SDimitry Andric 
2902145449b1SDimitry Andric   // Emit metadata.
2903145449b1SDimitry Andric   writeModuleMetadata();
2904145449b1SDimitry Andric 
2905145449b1SDimitry Andric   // Emit names for globals/functions etc.
2906145449b1SDimitry Andric   // DXIL uses the same format for module-level value symbol table as for the
2907145449b1SDimitry Andric   // function level table.
2908145449b1SDimitry Andric   writeFunctionLevelValueSymbolTable(M.getValueSymbolTable());
2909145449b1SDimitry Andric 
2910145449b1SDimitry Andric   // Emit function bodies.
2911145449b1SDimitry Andric   for (const Function &F : M)
2912145449b1SDimitry Andric     if (!F.isDeclaration())
2913145449b1SDimitry Andric       writeFunction(F);
2914145449b1SDimitry Andric 
2915145449b1SDimitry Andric   Stream.ExitBlock();
2916145449b1SDimitry Andric }
2917