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