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