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