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