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