31#include "llvm/IR/IntrinsicsSPIRV.h"
67#define DEBUG_TYPE "spirv-emit-intrinsics"
70#define GET_BuiltinGroup_DECL
71#include "SPIRVGenTables.inc"
76class GlobalVariableUsers {
77 template <
typename T1,
typename T2>
78 using OneToManyMapTy = DenseMap<T1, SmallPtrSet<T2, 4>>;
80 OneToManyMapTy<const GlobalVariable *, const Function *> GlobalIsUsedByFun;
82 void collectGlobalUsers(
83 const GlobalVariable *GV,
84 OneToManyMapTy<const GlobalVariable *, const GlobalVariable *>
85 &GlobalIsUsedByGlobal) {
87 while (!
Stack.empty()) {
91 GlobalIsUsedByFun[GV].insert(
I->getFunction());
96 GlobalIsUsedByGlobal[GV].insert(UserGV);
101 Stack.append(
C->user_begin(),
C->user_end());
105 bool propagateGlobalToGlobalUsers(
106 OneToManyMapTy<const GlobalVariable *, const GlobalVariable *>
107 &GlobalIsUsedByGlobal) {
110 for (
auto &[GV, UserGlobals] : GlobalIsUsedByGlobal) {
111 OldUsersGlobals.
assign(UserGlobals.begin(), UserGlobals.end());
112 for (
const GlobalVariable *UserGV : OldUsersGlobals) {
113 auto It = GlobalIsUsedByGlobal.find(UserGV);
114 if (It == GlobalIsUsedByGlobal.end())
122 void propagateGlobalToFunctionReferences(
123 OneToManyMapTy<const GlobalVariable *, const GlobalVariable *>
124 &GlobalIsUsedByGlobal) {
125 for (
auto &[GV, UserGlobals] : GlobalIsUsedByGlobal) {
126 auto &UserFunctions = GlobalIsUsedByFun[GV];
127 for (
const GlobalVariable *UserGV : UserGlobals) {
128 auto It = GlobalIsUsedByFun.find(UserGV);
129 if (It == GlobalIsUsedByFun.end())
140 OneToManyMapTy<const GlobalVariable *, const GlobalVariable *>
141 GlobalIsUsedByGlobal;
142 GlobalIsUsedByFun.clear();
143 for (GlobalVariable &GV :
M.globals())
144 collectGlobalUsers(&GV, GlobalIsUsedByGlobal);
147 while (propagateGlobalToGlobalUsers(GlobalIsUsedByGlobal))
150 propagateGlobalToFunctionReferences(GlobalIsUsedByGlobal);
153 using FunctionSetType =
decltype(GlobalIsUsedByFun)::mapped_type;
154 const FunctionSetType &
155 getTransitiveUserFunctions(
const GlobalVariable &GV)
const {
156 auto It = GlobalIsUsedByFun.find(&GV);
157 if (It != GlobalIsUsedByFun.end())
160 static const FunctionSetType
Empty{};
165static bool isaGEP(
const Value *
V) {
171static std::optional<uint64_t> getByteAddressingMultiplier(
Type *Ty) {
177 return AT->getNumElements();
193static void foldConstantOffsetIntoArrayIndex(
Function &
F) {
196 if (!Outer ||
Outer->getNumIndices() != 1 ||
197 !
Outer->getSourceElementType()->isIntegerTy(8))
201 if (!
Offset || !Inner || Inner->getNumIndices() != 1)
203 Value *Index = Inner->getOperand(1);
204 std::optional<uint64_t> Stride =
205 getByteAddressingMultiplier(Inner->getSourceElementType());
210 Type *IdxTy =
F.getDataLayout().getIndexType(Inner->getType());
211 int64_t Bytes =
Offset->getValue()
214 int64_t
Size = *Stride;
223 Value *NewIndex =
B.CreateAdd(
B.CreateSExtOrTrunc(Index, IdxTy),
225 Value *Ptr =
B.CreateGEP(Inner->getSourceElementType(),
226 Inner->getPointerOperand(), NewIndex,
"", NW);
227 if (int64_t Remainder =
mod(Bytes,
Size))
228 Ptr =
B.CreateGEP(
B.getInt8Ty(), Ptr, ConstantInt::get(IdxTy, Remainder),
231 Outer->replaceAllUsesWith(Ptr);
232 Outer->eraseFromParent();
233 if (Inner->use_empty())
234 Inner->eraseFromParent();
238class SPIRVEmitIntrinsicsImpl
239 :
public InstVisitor<SPIRVEmitIntrinsicsImpl, Instruction *> {
240 const SPIRVTargetMachine &TM;
241 SPIRVGlobalRegistry *GR =
nullptr;
243 bool TrackConstants =
true;
244 bool HaveFunPtrs =
false;
245 bool CanUseAnyVectorRank =
false;
246 DenseMap<Instruction *, Constant *> AggrConsts;
247 DenseMap<Instruction *, Type *> AggrConstTypes;
248 SmallPtrSet<Instruction *, 0> AggrStores;
249 GlobalVariableUsers GVUsers;
250 SmallPtrSet<Value *, 0> Named;
252 SmallPtrSet<GetElementPtrInst *, 4> InvalidGEPs;
255 MapVector<Function *, SmallVector<std::pair<unsigned, Type *>>> FDeclPtrTys;
258 bool CanTodoType =
true;
259 unsigned TodoTypeSz = 0;
260 DenseMap<Value *, bool> TodoType;
261 void insertTodoType(
Value *
Op) {
263 if (CanTodoType && !isaGEP(
Op)) {
264 auto It = TodoType.try_emplace(
Op,
true);
269 void eraseTodoType(
Value *
Op) {
270 auto It = TodoType.find(
Op);
271 if (It != TodoType.end() && It->second) {
279 auto It = TodoType.find(
Op);
280 return It != TodoType.end() && It->second;
284 SmallPtrSet<Instruction *, 0> TypeValidated;
287 SmallVector<Instruction *> RetypedToRevalidate;
288 bool RevalidatingRetyped =
false;
291 enum WellKnownTypes { Event };
294 Type *deduceElementType(
Value *
I,
bool UnknownElemTypeI8);
295 Type *deduceElementTypeHelper(
Value *
I,
bool UnknownElemTypeI8);
296 Type *deduceElementTypeHelper(
Value *
I, SmallPtrSetImpl<Value *> &Visited,
297 bool UnknownElemTypeI8,
298 bool IgnoreKnownType =
false);
299 Type *deduceElementTypeByValueDeep(
Type *ValueTy,
Value *Operand,
300 bool UnknownElemTypeI8);
301 Type *deduceElementTypeByValueDeep(
Type *ValueTy,
Value *Operand,
302 SmallPtrSetImpl<Value *> &Visited,
303 bool UnknownElemTypeI8,
304 std::optional<unsigned> AddrSpace = {});
306 SmallPtrSetImpl<Value *> &Visited,
307 bool UnknownElemTypeI8);
309 bool UnknownElemTypeI8);
312 Type *deduceNestedTypeHelper(User *U,
bool UnknownElemTypeI8);
313 Type *deduceNestedTypeHelper(User *U,
Type *Ty,
314 SmallPtrSetImpl<Value *> &Visited,
315 bool UnknownElemTypeI8);
319 deduceOperandElementType(Instruction *
I,
320 SmallPtrSetImpl<Instruction *> *IncompleteRets,
321 const SmallPtrSetImpl<Value *> *AskOps =
nullptr,
322 bool IsPostprocessing =
false);
327 void insertCompositeAggregateArms(Instruction *
I,
IRBuilder<> &
B);
329 void simplifyNullAddrSpaceCasts();
331 Type *reconstructType(
Value *
Op,
bool UnknownElemTypeI8,
332 bool IsPostprocessing);
334 void replaceMemInstrUses(Instruction *Old, Instruction *New,
IRBuilder<> &
B);
336 bool insertAssignPtrTypeIntrs(Instruction *
I,
IRBuilder<> &
B,
337 bool UnknownElemTypeI8);
339 void insertAssignPtrTypeTargetExt(TargetExtType *AssignedType,
Value *
V,
341 void replacePointerOperandWithPtrCast(Instruction *
I,
Value *Pointer,
342 Type *ExpectedElementType,
343 unsigned OperandToReplace,
345 void insertPtrCastOrAssignTypeInstr(Instruction *
I,
IRBuilder<> &
B);
346 bool shouldTryToAddMemAliasingDecoration(Instruction *Inst);
348 void insertConstantsForFPFastMathDefault(
Module &M);
351 void processGlobalValue(GlobalVariable &GV,
IRBuilder<> &
B);
354 Type *deduceFunParamElementType(
Function *
F,
unsigned OpIdx);
356 SmallPtrSetImpl<Function *> &FVisited);
358 bool deduceOperandElementTypeCalledFunction(
360 Type *&KnownElemTy,
bool &Incomplete);
361 void deduceOperandElementTypeFunctionPointer(
363 Type *&KnownElemTy,
bool IsPostprocessing);
364 bool deduceOperandElementTypeFunctionRet(
365 Instruction *
I, SmallPtrSetImpl<Instruction *> *IncompleteRets,
366 const SmallPtrSetImpl<Value *> *AskOps,
bool IsPostprocessing,
370 void replaceUsesOfWithSpvPtrcast(
Value *
Op,
Type *ElemTy, Instruction *
I,
371 DenseMap<Function *, CallInst *> Ptrcasts);
373 DenseSet<std::pair<Value *, Value *>> &VisitedSubst);
376 DenseSet<std::pair<Value *, Value *>> &VisitedSubst);
377 void propagateElemTypeRec(
Value *
Op,
Type *PtrElemTy,
Type *CastElemTy,
378 DenseSet<std::pair<Value *, Value *>> &VisitedSubst,
379 SmallPtrSetImpl<Value *> &Visited,
380 DenseMap<Function *, CallInst *> Ptrcasts);
383 void replaceAllUsesWithAndErase(
IRBuilder<> &
B, Instruction *Src,
384 Instruction *Dest,
bool DeleteOld =
true);
388 GetElementPtrInst *simplifyZeroLengthArrayGepInst(GetElementPtrInst *
GEP);
391 bool postprocessTypes(
Module &M);
392 bool processFunctionPointers(
Module &M);
393 void parseFunDeclarations(
Module &M);
394 void useRoundingMode(ConstrainedFPIntrinsic *FPI,
IRBuilder<> &
B);
395 bool processMaskedMemIntrinsic(IntrinsicInst &
I);
396 bool convertMaskedMemIntrinsics(
Module &M);
397 bool preprocessModule(
Module &M);
398 void preprocessBoolVectorBitcasts(
Function &
F);
399 void scalarizeVectorPtrCasts(
Function &
F);
418 Expected<bool> walkLogicalAccessChain(
419 GetElementPtrInst &
GEP,
420 const std::function<
void(
Type *PointedType,
uint64_t Index)>
423 uint64_t Multiplier)> &OnDynamicIndexing);
425 bool walkLogicalAccessChainDynamic(
427 const std::function<
void(
Type *,
uint64_t)> &OnLiteralIndexing,
430 Expected<bool> walkLogicalAccessChainConstant(
432 const std::function<
void(
Type *,
uint64_t)> &OnLiteralIndexing);
434 void recordAccessChainError(GetElementPtrInst &
GEP,
Error Err);
440 Type *getGEPType(GetElementPtrInst *
GEP);
447 Type *getGEPTypeLogical(GetElementPtrInst *
GEP);
449 Instruction *buildLogicalAccessChainFromGEP(GetElementPtrInst &
GEP);
454 SPIRVEmitIntrinsicsImpl(
const SPIRVTargetMachine &TM) : TM(TM) {}
457 Instruction *visitGetElementPtrInst(GetElementPtrInst &
I);
460 Instruction *visitInsertElementInst(InsertElementInst &
I);
461 Instruction *visitExtractElementInst(ExtractElementInst &
I);
463 Instruction *visitExtractValueInst(ExtractValueInst &
I);
467 Instruction *visitAtomicCmpXchgInst(AtomicCmpXchgInst &
I);
472 bool runOnModule(
Module &M);
475class SPIRVEmitIntrinsicsLegacy :
public ModulePass {
476 const SPIRVTargetMachine &TM;
480 SPIRVEmitIntrinsicsLegacy(
const SPIRVTargetMachine &TM)
481 : ModulePass(ID), TM(TM) {}
483 StringRef getPassName()
const override {
return "SPIRV emit intrinsics"; }
485 bool runOnModule(
Module &M)
override {
486 return SPIRVEmitIntrinsicsImpl(TM).runOnModule(M);
492 Intrinsic::experimental_convergence_loop,
493 Intrinsic::experimental_convergence_anchor>());
496bool expectIgnoredInIRTranslation(
const Instruction *
I) {
498 Intrinsic::spv_resource_handlefrombinding,
499 Intrinsic::spv_resource_getbasepointer,
500 Intrinsic::spv_resource_getpointer>());
507 return getPointerRoot(
V);
513char SPIRVEmitIntrinsicsLegacy::ID = 0;
516 "SPIRV emit intrinsics",
false,
false)
543 B.SetInsertPoint(
I->getParent()->getFirstNonPHIOrAlloca());
549 B.SetCurrentDebugLocation(
I->getDebugLoc());
550 if (
I->getType()->isVoidTy())
551 B.SetInsertPoint(
I->getNextNode());
553 B.SetInsertPoint(*
I->getInsertionPointAfterDef());
563 if (
I->getType()->isTokenTy())
565 "does not support token type",
571 if (!
I->hasName() ||
I->getType()->isAggregateType() ||
572 expectIgnoredInIRTranslation(
I))
577 bool KeepName = CLOpts.emit_op_names;
583 if (
F &&
F->getName().starts_with(
"llvm.spv.alloca"))
594 std::vector<Value *> Args = {
597 B.CreateIntrinsic(Intrinsic::spv_assign_name, {
I->getType()}, Args);
600void SPIRVEmitIntrinsicsImpl::replaceAllUsesWith(
Value *Src,
Value *Dest,
604 if (isTodoType(Src)) {
607 insertTodoType(Dest);
611void SPIRVEmitIntrinsicsImpl::replaceAllUsesWithAndErase(
IRBuilder<> &
B,
616 std::string
Name = Src->hasName() ? Src->getName().str() :
"";
617 Src->eraseFromParent();
620 if (Named.
insert(Dest).second)
635 V =
V->stripPointerCasts();
665Type *SPIRVEmitIntrinsicsImpl::reconstructType(
Value *
Op,
666 bool UnknownElemTypeI8,
667 bool IsPostprocessing) {
671 if (
auto It = AggrConstTypes.
find(OpI); It != AggrConstTypes.
end())
685 if (UnknownElemTypeI8) {
686 if (!IsPostprocessing)
702 B.SetInsertPointPastAllocas(OpA->getParent());
705 B.SetInsertPoint(
F->getEntryBlock().getFirstNonPHIOrAlloca());
707 Type *OpTy =
Op->getType();
709 SmallVector<Value *, 2>
Args = {
712 CallInst *PtrCasted =
713 B.CreateIntrinsicWithoutFolding(Intrinsic::spv_ptrcast, {
Types},
Args);
718void SPIRVEmitIntrinsicsImpl::replaceUsesOfWithSpvPtrcast(
720 DenseMap<Function *, CallInst *> Ptrcasts) {
722 CallInst *PtrCastedI =
nullptr;
723 auto It = Ptrcasts.
find(
F);
724 if (It == Ptrcasts.
end()) {
725 PtrCastedI = buildSpvPtrcast(
F,
Op, ElemTy);
726 Ptrcasts[
F] = PtrCastedI;
728 PtrCastedI = It->second;
730 I->replaceUsesOfWith(
Op, PtrCastedI);
733void SPIRVEmitIntrinsicsImpl::propagateElemType(
735 DenseSet<std::pair<Value *, Value *>> &VisitedSubst) {
736 DenseMap<Function *, CallInst *> Ptrcasts;
738 for (
auto *U :
Users) {
741 if (!VisitedSubst.insert(std::make_pair(U,
Op)).second)
746 if (isaGEP(UI) || TypeValidated.
find(UI) != TypeValidated.
end())
747 replaceUsesOfWithSpvPtrcast(
Op, ElemTy, UI, Ptrcasts);
751void SPIRVEmitIntrinsicsImpl::propagateElemTypeRec(
753 DenseSet<std::pair<Value *, Value *>> &VisitedSubst) {
754 SmallPtrSet<Value *, 0> Visited;
755 DenseMap<Function *, CallInst *> Ptrcasts;
756 propagateElemTypeRec(
Op, PtrElemTy, CastElemTy, VisitedSubst, Visited,
757 std::move(Ptrcasts));
760void SPIRVEmitIntrinsicsImpl::propagateElemTypeRec(
762 DenseSet<std::pair<Value *, Value *>> &VisitedSubst,
763 SmallPtrSetImpl<Value *> &Visited,
764 DenseMap<Function *, CallInst *> Ptrcasts) {
768 for (
auto *U :
Users) {
771 if (!VisitedSubst.insert(std::make_pair(U,
Op)).second)
776 if (isaGEP(UI) || TypeValidated.
find(UI) != TypeValidated.
end())
777 replaceUsesOfWithSpvPtrcast(
Op, CastElemTy, UI, Ptrcasts);
784Type *SPIRVEmitIntrinsicsImpl::deduceElementTypeByValueDeep(
785 Type *ValueTy,
Value *Operand,
bool UnknownElemTypeI8) {
786 SmallPtrSet<Value *, 0> Visited;
787 return deduceElementTypeByValueDeep(ValueTy, Operand, Visited,
791Type *SPIRVEmitIntrinsicsImpl::deduceElementTypeByValueDeep(
792 Type *ValueTy,
Value *Operand, SmallPtrSetImpl<Value *> &Visited,
793 bool UnknownElemTypeI8, std::optional<unsigned> AddrSpace) {
798 deduceElementTypeHelper(Operand, Visited, UnknownElemTypeI8))
800 NestedTy, AddrSpace.value_or(PtrTy->getAddressSpace()));
810Type *SPIRVEmitIntrinsicsImpl::deduceElementTypeByUsersDeep(
811 Value *
Op, SmallPtrSetImpl<Value *> &Visited,
bool UnknownElemTypeI8) {
823 for (User *OpU :
Op->users()) {
825 if (
Type *Ty = deduceElementTypeHelper(Inst, Visited, UnknownElemTypeI8))
837 Function *CalledF,
unsigned OpIdx) {
842 if (OpIdx == 0 && (Name ==
"printf" || Name ==
"get_fence"))
845 if (OpIdx == 2 && (Name ==
"capture_event_profiling_info" ||
846 Name ==
"__spirv_CaptureEventProfilingInfo"))
853Type *SPIRVEmitIntrinsicsImpl::deduceElementTypeHelper(
Value *
I,
854 bool UnknownElemTypeI8) {
855 SmallPtrSet<Value *, 0> Visited;
856 return deduceElementTypeHelper(
I, Visited, UnknownElemTypeI8);
859void SPIRVEmitIntrinsicsImpl::maybeAssignPtrType(
Type *&Ty,
Value *
Op,
861 bool UnknownElemTypeI8) {
863 if (!UnknownElemTypeI8)
872bool SPIRVEmitIntrinsicsImpl::walkLogicalAccessChainDynamic(
874 const std::function<
void(
Type *,
uint64_t)> &OnLiteralIndexing,
881 if (
ST->getNumElements() == 0)
883 CurType =
ST->getElementType(0);
884 OnLiteralIndexing(CurType, 0);
892 OnDynamicIndexing(AT->getElementType(), Operand, Multiplier);
893 return AT ==
nullptr;
896Expected<bool> SPIRVEmitIntrinsicsImpl::walkLogicalAccessChainConstant(
898 const std::function<
void(
Type *,
uint64_t)> &OnLiteralIndexing) {
904 uint64_t EltTypeSize =
DL.getTypeAllocSize(AT->getElementType());
908 CurType = AT->getElementType();
909 OnLiteralIndexing(CurType, Index);
911 uint32_t StructSize =
DL.getTypeSizeInBits(ST) / 8;
914 const auto &STL =
DL.getStructLayout(ST);
915 unsigned Element = STL->getElementContainingOffset(
Offset);
916 Offset -= STL->getElementOffset(Element);
917 CurType =
ST->getElementType(Element);
918 OnLiteralIndexing(CurType, Element);
920 Type *EltTy = VT->getElementType();
921 TypeSize EltSizeBits =
DL.getTypeSizeInBits(EltTy);
922 assert(EltSizeBits % 8 == 0 &&
923 "Element type size in bits must be a multiple of 8.");
924 uint32_t EltTypeSize = EltSizeBits / 8;
925 if (
Offset >= VT->getNumElements() * EltTypeSize)
927 "Cannot lower an access to vector padding for Logical SPIR-V");
931 OnLiteralIndexing(CurType, Index);
936 "Cannot lower a byte offset within a scalar or padding for "
944Expected<bool> SPIRVEmitIntrinsicsImpl::walkLogicalAccessChain(
945 GetElementPtrInst &
GEP,
946 const std::function<
void(
Type *,
uint64_t)> &OnLiteralIndexing,
950 std::optional<uint64_t> MultiplierOpt =
951 getByteAddressingMultiplier(
GEP.getSourceElementType());
952 assert(MultiplierOpt &&
"We only rewrite byte-addressing GEP");
953 uint64_t Multiplier = *MultiplierOpt;
956 Value *Src = getPointerRoot(
GEP.getPointerOperand());
957 Type *CurType = deduceElementType(Src,
true);
960 "Cannot lower byte addressing with an unsized type for Logical SPIR-V");
966 APInt
Offset(
DL.getIndexSizeInBits(
GEP.getPointerAddressSpace()), 0);
968 assert(IsConstant &&
"a constant index must give a constant offset");
969 return walkLogicalAccessChainConstant(CurType,
Offset.getZExtValue(),
973 return walkLogicalAccessChainDynamic(CurType, Operand, Multiplier,
974 OnLiteralIndexing, OnDynamicIndexing);
977void SPIRVEmitIntrinsicsImpl::recordAccessChainError(GetElementPtrInst &
GEP,
981 std::move(AccessChainErrors),
983 GEP.getFunction()->getName() +
"')"));
990Value *SPIRVEmitIntrinsicsImpl::truncateGEPIndex(
Value *Idx,
Type *IdxTy,
996 insertAssignTypeIntrs(TruncI,
B);
1000Instruction *SPIRVEmitIntrinsicsImpl::buildLogicalAccessChainFromGEP(
1001 GetElementPtrInst &
GEP) {
1007 B.SetInsertPoint(&
GEP);
1009 std::vector<Value *> Indices;
1010 Indices.push_back(ConstantInt::get(
1011 IntegerType::getInt32Ty(CurrF->
getContext()), 0,
false));
1012 Type *IdxTy =
DL.getIndexType(
GEP.getPointerOperandType());
1013 auto Result = walkLogicalAccessChain(
1016 Indices.push_back(ConstantInt::get(IdxTy, Index,
false));
1022 uint32_t EltTypeSize =
DL.getTypeSizeInBits(EltType) / 8;
1024 if (Multiplier == EltTypeSize) {
1026 }
else if (EltTypeSize % Multiplier == 0) {
1029 EltTypeSize / Multiplier,
1033 ConstantInt::get(
Offset->getType(), Multiplier,
1036 Index =
B.CreateUDiv(Index,
1037 ConstantInt::get(
Offset->getType(), EltTypeSize,
1041 Indices.push_back(Index);
1044 recordAccessChainError(
GEP,
Result.takeError());
1048 B.SetInsertPoint(&
GEP);
1050 SmallVector<Value *, 4>
Args;
1051 Args.push_back(
B.getInt1(
GEP.isInBounds()));
1052 Args.push_back(
GEP.getOperand(0));
1055 B.CreateIntrinsicWithoutFolding(Intrinsic::spv_gep, {
Types}, {
Args});
1056 replaceAllUsesWithAndErase(
B, &
GEP, NewI);
1060Type *SPIRVEmitIntrinsicsImpl::getGEPTypeLogical(GetElementPtrInst *
GEP) {
1064 Type *CurType =
GEP->getResultElementType();
1066 auto Result = walkLogicalAccessChain(
1067 *
GEP, [&CurType](
Type *EltType,
uint64_t Index) { CurType = EltType; },
1070 recordAccessChainError(*
GEP,
Result.takeError());
1074 return *
Result ?
GEP->getResultElementType() : CurType;
1077Type *SPIRVEmitIntrinsicsImpl::getGEPType(GetElementPtrInst *
Ref) {
1078 if (getByteAddressingMultiplier(
Ref->getSourceElementType()) &&
1080 return getGEPTypeLogical(
Ref);
1087 Ty =
Ref->getSourceElementType();
1091 Ty =
Ref->getResultElementType();
1096Type *SPIRVEmitIntrinsicsImpl::deduceElementTypeHelper(
1097 Value *
I, SmallPtrSetImpl<Value *> &Visited,
bool UnknownElemTypeI8,
1098 bool IgnoreKnownType) {
1104 if (!IgnoreKnownType)
1109 if (!Visited.
insert(
I).second)
1116 maybeAssignPtrType(Ty,
I,
Ref->getAllocatedType(), UnknownElemTypeI8);
1118 Ty = getGEPType(
Ref);
1120 Ty = SGEP->getResultElementType();
1125 KnownTy =
Op->getType();
1127 maybeAssignPtrType(Ty,
I, ElemTy, UnknownElemTypeI8);
1130 Ty = SPIRV::getOriginalFunctionType(*Fn);
1137 std::optional<unsigned> ProgramAS;
1142 SPIRV::Extension::SPV_INTEL_function_pointers))
1146 Ty = deduceElementTypeByValueDeep(
Ref->getValueType(),
Op, Visited,
1147 UnknownElemTypeI8, ProgramAS);
1150 Type *RefTy = deduceElementTypeHelper(
Ref->getPointerOperand(), Visited,
1152 maybeAssignPtrType(Ty,
I, RefTy, UnknownElemTypeI8);
1154 maybeAssignPtrType(Ty,
I,
Ref->getDestTy(), UnknownElemTypeI8);
1156 if (
Type *Src =
Ref->getSrcTy(), *Dest =
Ref->getDestTy();
1158 Ty = deduceElementTypeHelper(
Ref->getOperand(0), Visited,
1164 reconstructType(
Ref->getAggregateOperand(),
false,
false),
1169 Ty = deduceElementTypeHelper(
Op, Visited, UnknownElemTypeI8);
1173 Ty = deduceElementTypeHelper(
Op, Visited, UnknownElemTypeI8);
1175 Type *BestTy =
nullptr;
1177 DenseMap<Type *, unsigned> PhiTys;
1178 for (
int i =
Ref->getNumIncomingValues() - 1; i >= 0; --i) {
1179 Ty = deduceElementTypeByUsersDeep(
Ref->getIncomingValue(i), Visited,
1186 if (It.first->second > MaxN) {
1187 MaxN = It.first->second;
1195 for (
Value *
Op : {
Ref->getTrueValue(),
Ref->getFalseValue()}) {
1199 ? deduceElementTypeHelper(
Op, Visited, UnknownElemTypeI8)
1200 : deduceElementTypeByUsersDeep(
Op, Visited, UnknownElemTypeI8);
1205 static StringMap<unsigned> ResTypeByArg = {
1211 {
"__to_private", 0},
1212 {
"__spirv_GenericCastToPtr_ToGlobal", 0},
1213 {
"__spirv_GenericCastToPtr_ToLocal", 0},
1214 {
"__spirv_GenericCastToPtr_ToPrivate", 0},
1215 {
"__spirv_GenericCastToPtrExplicit_ToGlobal", 0},
1216 {
"__spirv_GenericCastToPtrExplicit_ToLocal", 0},
1217 {
"__spirv_GenericCastToPtrExplicit_ToPrivate", 0}};
1221 if (
II && (
II->getIntrinsicID() == Intrinsic::spv_resource_getbasepointer ||
1222 II->getIntrinsicID() == Intrinsic::spv_resource_getpointer)) {
1224 if (HandleType->getTargetExtName() ==
"spirv.Image" ||
1225 HandleType->getTargetExtName() ==
"spirv.SignedImage") {
1226 for (User *U :
II->users()) {
1231 }
else if (HandleType->getTargetExtName() ==
"spirv.VulkanBuffer") {
1233 Ty = HandleType->getTypeParameter(0);
1234 if (
II->getIntrinsicID() == Intrinsic::spv_resource_getpointer) {
1248 }
else if (
II &&
II->getIntrinsicID() ==
1249 Intrinsic::spv_generic_cast_to_ptr_explicit) {
1253 std::string DemangledName =
1255 if (DemangledName.length() > 0)
1256 DemangledName = SPIRV::lookupBuiltinNameHelper(DemangledName);
1257 auto AsArgIt = ResTypeByArg.
find(DemangledName);
1258 if (AsArgIt != ResTypeByArg.
end())
1259 Ty = deduceElementTypeHelper(CI->
getArgOperand(AsArgIt->second),
1260 Visited, UnknownElemTypeI8);
1267 if (Ty && !IgnoreKnownType) {
1278Type *SPIRVEmitIntrinsicsImpl::deduceNestedTypeHelper(User *U,
1279 bool UnknownElemTypeI8) {
1280 SmallPtrSet<Value *, 0> Visited;
1281 return deduceNestedTypeHelper(U,
U->getType(), Visited, UnknownElemTypeI8);
1284Type *SPIRVEmitIntrinsicsImpl::deduceNestedTypeHelper(
1285 User *U,
Type *OrigTy, SmallPtrSetImpl<Value *> &Visited,
1286 bool UnknownElemTypeI8) {
1296 if (!Visited.
insert(U).second)
1307 if (
Type *NestedTy =
1308 deduceElementTypeHelper(
Op, Visited, UnknownElemTypeI8))
1315 bool Change =
false;
1316 for (
unsigned i = 0; i <
U->getNumOperands(); ++i) {
1318 assert(
Op &&
"Operands should not be null.");
1319 Type *OpTy =
Op->getType();
1320 Type *Ty = DeduceOpTy(
Op, OpTy);
1322 Change |= Ty != OpTy;
1326 Tys, OrigStructTy->isLiteral() ?
"" : OrigStructTy->getName(),
1327 OrigStructTy->isPacked());
1333 Type *OpTy = ArrTy->getElementType();
1334 Type *Ty = DeduceOpTy(
Op, OpTy);
1336 Type *NewTy = ArrayType::get(Ty, ArrTy->getNumElements());
1343 Type *OpTy = VecTy->getElementType();
1344 Type *Ty = DeduceOpTy(
Op, OpTy);
1346 Type *NewTy = VectorType::get(Ty, VecTy->getElementCount());
1357Type *SPIRVEmitIntrinsicsImpl::deduceElementType(
Value *
I,
1358 bool UnknownElemTypeI8) {
1359 if (
Type *Ty = deduceElementTypeHelper(
I, UnknownElemTypeI8))
1361 if (!UnknownElemTypeI8)
1364 return IntegerType::getInt8Ty(
I->getContext());
1368 Value *PointerOperand) {
1374 return I->getType();
1382bool SPIRVEmitIntrinsicsImpl::deduceOperandElementTypeCalledFunction(
1384 Type *&KnownElemTy,
bool &Incomplete) {
1388 std::string DemangledName =
1390 if (DemangledName.length() > 0 &&
1392 const SPIRVSubtarget &
ST = TM.
getSubtarget<SPIRVSubtarget>(*CalledF);
1393 auto [Grp, Opcode, ExtNo] = SPIRV::mapBuiltinToOpcode(
1394 DemangledName,
ST.getPreferredInstructionSet());
1395 if (Opcode == SPIRV::OpGroupAsyncCopy) {
1396 for (
unsigned i = 0, PtrCnt = 0; i < CI->
arg_size() && PtrCnt < 2; ++i) {
1402 KnownElemTy = ElemTy;
1403 Ops.push_back(std::make_pair(
Op, i));
1405 }
else if (Grp == SPIRV::Atomic || Grp == SPIRV::AtomicFloating) {
1412 case SPIRV::OpAtomicFAddEXT:
1413 case SPIRV::OpAtomicFMinEXT:
1414 case SPIRV::OpAtomicFMaxEXT:
1415 case SPIRV::OpAtomicLoad:
1416 case SPIRV::OpAtomicCompareExchangeWeak:
1417 case SPIRV::OpAtomicCompareExchange:
1418 case SPIRV::OpAtomicExchange:
1419 case SPIRV::OpAtomicIAdd:
1420 case SPIRV::OpAtomicISub:
1421 case SPIRV::OpAtomicOr:
1422 case SPIRV::OpAtomicXor:
1423 case SPIRV::OpAtomicAnd:
1424 case SPIRV::OpAtomicUMin:
1425 case SPIRV::OpAtomicUMax:
1426 case SPIRV::OpAtomicSMin:
1427 case SPIRV::OpAtomicSMax: {
1432 Incomplete = isTodoType(
Op);
1433 Ops.push_back(std::make_pair(
Op, 0));
1435 case SPIRV::OpAtomicStore: {
1444 Incomplete = isTodoType(
Op);
1445 Ops.push_back(std::make_pair(
Op, 0));
1454void SPIRVEmitIntrinsicsImpl::deduceOperandElementTypeFunctionPointer(
1456 Type *&KnownElemTy,
bool IsPostprocessing) {
1460 Ops.push_back(std::make_pair(
Op, std::numeric_limits<unsigned>::max()));
1461 FunctionType *FTy = SPIRV::getOriginalFunctionType(*CI);
1462 bool IsNewFTy =
false, IsIncomplete =
false;
1465 Type *ArgTy = Arg->getType();
1470 if (isTodoType(Arg))
1471 IsIncomplete =
true;
1473 IsIncomplete =
true;
1476 ArgTy = FTy->getFunctionParamType(ParmIdx);
1480 Type *RetTy = FTy->getReturnType();
1487 IsIncomplete =
true;
1489 IsIncomplete =
true;
1492 if (!IsPostprocessing && IsIncomplete)
1495 IsNewFTy ? FunctionType::get(RetTy, ArgTys, FTy->isVarArg()) : FTy;
1498bool SPIRVEmitIntrinsicsImpl::deduceOperandElementTypeFunctionRet(
1499 Instruction *
I, SmallPtrSetImpl<Instruction *> *IncompleteRets,
1500 const SmallPtrSetImpl<Value *> *AskOps,
bool IsPostprocessing,
1512 DenseSet<std::pair<Value *, Value *>> VisitedSubst{std::make_pair(
I,
Op)};
1513 for (User *U :
F->users()) {
1522 propagateElemType(CI, PrevElemTy, VisitedSubst);
1532 for (Instruction *IncompleteRetI : *IncompleteRets)
1533 deduceOperandElementType(IncompleteRetI,
nullptr, AskOps,
1535 }
else if (IncompleteRets) {
1546void SPIRVEmitIntrinsicsImpl::deduceOperandElementType(
1547 Instruction *
I, SmallPtrSetImpl<Instruction *> *IncompleteRets,
1548 const SmallPtrSetImpl<Value *> *AskOps,
bool IsPostprocessing) {
1550 Type *KnownElemTy =
nullptr;
1551 bool Incomplete =
false;
1557 Incomplete = isTodoType(
I);
1558 for (
unsigned i = 0; i <
Ref->getNumIncomingValues(); i++) {
1561 Ops.push_back(std::make_pair(
Op, i));
1567 Incomplete = isTodoType(
I);
1568 Ops.push_back(std::make_pair(
Ref->getPointerOperand(), 0));
1575 Incomplete = isTodoType(
I);
1576 Ops.push_back(std::make_pair(
Ref->getOperand(0), 0));
1580 KnownElemTy =
Ref->getSourceElementType();
1581 Ops.push_back(std::make_pair(
Ref->getPointerOperand(),
1586 KnownElemTy =
Ref->getBaseType();
1587 Ops.push_back(std::make_pair(
Ref->getPointerOperand(),
1590 KnownElemTy =
I->getType();
1597 Value *Root =
Ref->getPointerOperand()->stripPointerCasts();
1606 Ops.push_back(std::make_pair(
Ref->getPointerOperand(),
1610 reconstructType(
Ref->getValueOperand(),
false, IsPostprocessing)))
1615 Ops.push_back(std::make_pair(
Ref->getPointerOperand(),
1623 Incomplete = isTodoType(
Ref->getPointerOperand());
1624 Ops.push_back(std::make_pair(
Ref->getPointerOperand(),
1632 Incomplete = isTodoType(
Ref->getPointerOperand());
1633 Ops.push_back(std::make_pair(
Ref->getPointerOperand(),
1639 Incomplete = isTodoType(
I);
1640 for (
unsigned i = 0; i <
Ref->getNumOperands(); i++) {
1643 Ops.push_back(std::make_pair(
Op, i));
1651 if (deduceOperandElementTypeFunctionRet(
I, IncompleteRets, AskOps,
1652 IsPostprocessing, KnownElemTy,
Op,
1655 Incomplete = isTodoType(CurrF);
1656 Ops.push_back(std::make_pair(
Op, 0));
1662 bool Incomplete0 = isTodoType(Op0);
1663 bool Incomplete1 = isTodoType(Op1);
1665 Type *ElemTy0 = (Incomplete0 && !Incomplete1 && ElemTy1)
1667 : GR->findDeducedElementType(Op0);
1669 KnownElemTy = ElemTy0;
1670 Incomplete = Incomplete0;
1671 Ops.push_back(std::make_pair(Op1, 1));
1672 }
else if (ElemTy1) {
1673 KnownElemTy = ElemTy1;
1674 Incomplete = Incomplete1;
1675 Ops.push_back(std::make_pair(Op0, 0));
1679 deduceOperandElementTypeCalledFunction(CI,
Ops, KnownElemTy, Incomplete);
1680 else if (HaveFunPtrs)
1681 deduceOperandElementTypeFunctionPointer(CI,
Ops, KnownElemTy,
1686 if (!KnownElemTy ||
Ops.size() == 0)
1690 for (
auto &OpIt :
Ops) {
1694 Type *AskTy =
nullptr;
1695 CallInst *AskCI =
nullptr;
1696 if (IsPostprocessing && AskOps) {
1702 if (Ty == KnownElemTy)
1705 Type *OpTy =
Op->getType();
1711 if (
Op->hasUseList() && !WouldClobberPtrWithNonPtr &&
1719 else if (!IsPostprocessing)
1723 if (AssignCI ==
nullptr) {
1732 DenseSet<std::pair<Value *, Value *>> VisitedSubst{
1733 std::make_pair(
I,
Op)};
1734 propagateElemTypeRec(
Op, KnownElemTy, PrevElemTy, VisitedSubst);
1745 CallInst *PtrCastI =
1746 buildSpvPtrcast(
I->getParent()->getParent(),
Op, KnownElemTy);
1747 if (OpIt.second == std::numeric_limits<unsigned>::max())
1750 I->setOperand(OpIt.second, PtrCastI);
1757 if (RevalidatingRetyped)
1759 RevalidatingRetyped =
true;
1760 while (!RetypedToRevalidate.
empty())
1761 deduceOperandElementType(RetypedToRevalidate.
pop_back_val(),
nullptr,
1762 nullptr, IsPostprocessing);
1763 RevalidatingRetyped =
false;
1766void SPIRVEmitIntrinsicsImpl::replaceMemInstrUses(Instruction *Old,
1771 if (isAssignTypeInstr(U)) {
1772 B.SetInsertPoint(U);
1773 SmallVector<Value *, 2>
Args = {
New,
U->getOperand(1)};
1774 CallInst *AssignCI =
B.CreateIntrinsicWithoutFolding(
1775 Intrinsic::spv_assign_type, {
New->getType()},
Args);
1777 U->eraseFromParent();
1780 U->replaceUsesOfWith(Old, New);
1788 Type *NewArgTy =
New->getType();
1790 if (NewArgTy != ExpectedArgTy) {
1793 M, Intrinsic::spv_abort, {NewArgTy});
1803 "aggregate PHI/select/freeze should have been mutated to value-id "
1805 U->replaceUsesOfWith(Old, New);
1810 New->copyMetadata(*Old);
1812 TypeValidated.
erase(Old);
1818 bool HasPoisonExt) {
1825 LLVM_DEBUG(
dbgs() <<
"SPV_KHR_poison_freeze is not enabled. Poison is "
1826 "lowered as undef\n");
1828 Intrinsic::ID IID = AsPoison ? Intrinsic::spv_poison : Intrinsic::spv_undef;
1829 Type *Ty = UV->getType();
1835 AsPoison ?
B.CreateIntrinsicWithoutFolding(IID, {
B.getInt32Ty()}, {})
1836 :
B.CreateIntrinsicWithoutFolding(IID, {});
1837 AggrConsts[
Call] = UV;
1838 AggrConstTypes[
Call] = Ty;
1843 return B.CreateIntrinsic(IID, {Ty}, {});
1850void SPIRVEmitIntrinsicsImpl::preprocessUndefsAndPoisons(
IRBuilder<> &
B) {
1855 SmallVector<Instruction *, 16> Insts;
1859 for (Instruction *
I : Insts) {
1860 bool BPrepared =
false;
1862 for (
unsigned Idx = 0;
Idx <
I->getNumOperands(); ++
Idx) {
1866 bool IsScalar = !
Op->getType()->isAggregateType();
1869 if (IsScalar && !AsPoison)
1873 if (IsScalar && Phi)
1874 B.SetInsertPoint(
Phi->getIncomingBlock(Idx)->getTerminator());
1875 else if (!BPrepared) {
1879 if (
Value *Repl = lowerUndefOrPoison(
Op,
B, HasPoisonExt))
1880 I->setOperand(Idx, Repl);
1889void SPIRVEmitIntrinsicsImpl::simplifyNullAddrSpaceCasts() {
1893 ASC->replaceAllUsesWith(
1895 ASC->eraseFromParent();
1903 if (!
V->getType()->isAggregateType())
1912 I.getType()->isAggregateType();
1918void SPIRVEmitIntrinsicsImpl::insertCompositeAggregateArms(Instruction *
I,
1923 SmallDenseMap<BasicBlock *, Value *> PhiArms;
1924 for (Use &U :
I->operands()) {
1928 if (
Value *Arm = Phi ? PhiArms.
lookup(
Phi->getIncomingBlock(U)) :
nullptr) {
1935 B.SetInsertPoint(
Phi->getIncomingBlock(U)->getTerminator());
1940 for (
unsigned Idx = 0,
E = AggrTy->getNumElements(); Idx !=
E; ++Idx) {
1942 Composite =
B.CreateInsertValue(Composite,
Field, Idx);
1946 PhiArms[
Phi->getIncomingBlock(U)] = Composite;
1954 bool HasPoisonExt) {
1956 CE &&
CE->getOpcode() == Instruction::AddrSpaceCast &&
1960 if (
Value *Repl = lowerUndefOrPoison(
Op,
B, HasPoisonExt))
1965void SPIRVEmitIntrinsicsImpl::preprocessCompositeConstants(
IRBuilder<> &
B) {
1969 std::queue<Instruction *> Worklist;
1973 while (!Worklist.empty()) {
1974 auto *
I = Worklist.front();
1977 bool KeepInst =
false;
1978 for (
const auto &
Op :
I->operands()) {
1980 Type *ResTy =
nullptr;
1983 ResTy = COp->getType();
1995 ResTy =
Op->getType()->isVectorTy() ? COp->getType() :
B.getInt32Ty();
1998 auto PrepareInsert = [&]() {
2001 IsPhi ?
B.SetInsertPointPastAllocas(
I->getParent()->getParent())
2002 :
B.SetInsertPoint(
I);
2006 Type *DeducedTy = deduceNestedTypeHelper(AggrConst,
false);
2010 if (DeducedTy != AggrConst->
getType() &&
2019 Value *LoweredBase =
2020 lowerCompositeMember(Composite,
B, HasPoisonExt);
2021 Value *LoweredMember =
2022 lowerCompositeMember(Member,
B, HasPoisonExt);
2026 Composite, Member,
B.getInt32(Idx),
"",
B.GetInsertPoint());
2029 B.GetInsertPoint());
2030 Insert->setOperand(0, LoweredBase);
2031 Insert->setOperand(1, LoweredMember);
2032 Worklist.push(Insert);
2035 I->replaceUsesOfWith(
Op, Composite);
2041 for (
unsigned i = 0; i < COp->getNumElements(); ++i)
2042 Args.push_back(COp->getElementAsConstant(i));
2045 Args.push_back(lowerCompositeMember(
Op,
B, HasPoisonExt));
2046 auto *CI =
B.CreateIntrinsicWithoutFolding(
2047 Intrinsic::spv_const_composite, {ResTy}, {
Args});
2051 AggrConsts[CI] = AggrConst;
2052 AggrConstTypes[CI] = DeducedTy;
2064 B.CreateIntrinsic(Intrinsic::spv_assign_decoration, {
I->getType()},
2069 unsigned RoundingModeDeco,
2076 ConstantInt::get(Int32Ty, SPIRV::Decoration::FPRoundingMode)),
2085 MDNode *SaturatedConversionNode =
2087 Int32Ty, SPIRV::Decoration::SaturatedConversion))});
2107 MDString *ConstraintString =
2112 for (
unsigned OpIdx = 0; OpIdx <
Call.
arg_size(); OpIdx++)
2116 B.SetInsertPoint(&
Call);
2117 B.CreateIntrinsic(Intrinsic::spv_inline_asm, {
Args});
2122void SPIRVEmitIntrinsicsImpl::useRoundingMode(ConstrainedFPIntrinsic *FPI,
2125 if (!
RM.has_value())
2127 unsigned RoundingModeDeco = std::numeric_limits<unsigned>::max();
2128 switch (
RM.value()) {
2132 case RoundingMode::NearestTiesToEven:
2133 RoundingModeDeco = SPIRV::FPRoundingMode::FPRoundingMode::RTE;
2135 case RoundingMode::TowardNegative:
2136 RoundingModeDeco = SPIRV::FPRoundingMode::FPRoundingMode::RTN;
2138 case RoundingMode::TowardPositive:
2139 RoundingModeDeco = SPIRV::FPRoundingMode::FPRoundingMode::RTP;
2141 case RoundingMode::TowardZero:
2142 RoundingModeDeco = SPIRV::FPRoundingMode::FPRoundingMode::RTZ;
2144 case RoundingMode::Dynamic:
2145 case RoundingMode::NearestTiesToAway:
2149 if (RoundingModeDeco == std::numeric_limits<unsigned>::max())
2155Instruction *SPIRVEmitIntrinsicsImpl::visitSwitchInst(SwitchInst &
I) {
2159 B.SetInsertPoint(&
I);
2160 SmallVector<Value *, 4>
Args;
2162 Args.push_back(
I.getCondition());
2165 for (
auto &Case :
I.cases()) {
2166 Args.push_back(Case.getCaseValue());
2167 BBCases.
push_back(Case.getCaseSuccessor());
2170 CallInst *NewI =
B.CreateIntrinsicWithoutFolding(
2171 Intrinsic::spv_switch, {
I.getOperand(0)->getType()}, {
Args});
2175 I.eraseFromParent();
2178 B.SetInsertPoint(ParentBB);
2179 IndirectBrInst *BrI =
B.CreateIndirectBr(
2182 for (BasicBlock *BBCase : BBCases)
2191Instruction *SPIRVEmitIntrinsicsImpl::visitIntrinsicInst(IntrinsicInst &
I) {
2197 B.SetInsertPoint(&
I);
2199 SmallVector<Value *, 4>
Args;
2200 Args.push_back(
B.getInt1(
true));
2201 Args.push_back(
I.getOperand(0));
2202 Args.push_back(
B.getInt32(0));
2203 for (
unsigned J = 0; J < SGEP->getNumIndices(); ++J)
2204 Args.push_back(SGEP->getIndexOperand(J));
2207 B.CreateIntrinsicWithoutFolding(Intrinsic::spv_gep, Types, Args);
2208 replaceAllUsesWithAndErase(
B, &
I, NewI);
2213SPIRVEmitIntrinsicsImpl::visitGetElementPtrInst(GetElementPtrInst &
I) {
2215 B.SetInsertPoint(&
I);
2220 unsigned N = RetVTy->getNumElements();
2221 Value *PtrOp =
I.getPointerOperand();
2223 Type *ResultPtrTy = RetVTy->getElementType();
2226 Value *InBounds =
B.getInt1(
I.isInBounds());
2227 Type *LanePointeeTy = getGEPType(&
I);
2230 Type *SrcElemTy =
I.getSourceElementType();
2239 for (
unsigned Lane = 0; Lane <
N; ++Lane) {
2240 Value *LaneIdx =
B.getInt32(Lane);
2241 Value *ScalarPtr = PtrOp;
2245 ScalarPtr =
B.CreateIntrinsic(Intrinsic::spv_extractelt, {ExtractTypes},
2249 SmallVector<Value *, 4>
Args;
2250 Args.push_back(InBounds);
2251 Args.push_back(ScalarPtr);
2252 for (
Value *Idx :
I.indices()) {
2260 Args.push_back(visitExtractElementInst(*EI));
2264 Args.push_back(Idx);
2267 Value *ScalarGep =
B.CreateIntrinsic(Intrinsic::spv_gep, GepTypes, Args);
2269 VecResult =
B.CreateInsertElement(VecResult, ScalarGep, LaneIdx);
2273 replaceAllUsesWithAndErase(
B, &
I, NewI);
2293 if (getByteAddressingMultiplier(
I.getSourceElementType())) {
2294 return buildLogicalAccessChainFromGEP(
I);
2299 Value *PtrOp =
I.getPointerOperand();
2300 Type *SrcElemTy =
I.getSourceElementType();
2301 Type *DeducedPointeeTy = deduceElementType(PtrOp,
true);
2304 if (ArrTy->getElementType() == SrcElemTy) {
2306 for (
Value *Idx :
I.indices())
2307 NewIndices.
push_back(truncateGEPIndex(Idx, IdxTy,
B));
2309 ConstantInt::get(NewIndices.
front()->getType(), 0));
2312 SmallVector<Value *, 4>
Args;
2313 Args.push_back(
B.getInt1(
I.isInBounds()));
2314 Args.push_back(
I.getPointerOperand());
2317 Instruction *NewI =
B.CreateIntrinsicWithoutFolding(Intrinsic::spv_gep,
2319 replaceAllUsesWithAndErase(
B, &
I, NewI);
2326 SmallVector<Value *, 4>
Args;
2327 Args.push_back(
B.getInt1(
I.isInBounds()));
2328 Args.push_back(
I.getPointerOperand());
2329 for (
Value *Idx :
I.indices())
2330 Args.push_back(IsLogical ? truncateGEPIndex(Idx, IdxTy,
B) : Idx);
2332 B.CreateIntrinsicWithoutFolding(Intrinsic::spv_gep, {
Types}, {
Args});
2333 replaceAllUsesWithAndErase(
B, &
I, NewI);
2337Instruction *SPIRVEmitIntrinsicsImpl::visitBitCastInst(BitCastInst &
I) {
2339 B.SetInsertPoint(&
I);
2348 I.eraseFromParent();
2355 B.CreateIntrinsicWithoutFolding(Intrinsic::spv_bitcast, {
Types}, {
Args});
2356 replaceAllUsesWithAndErase(
B, &
I, NewI);
2360void SPIRVEmitIntrinsicsImpl::insertAssignPtrTypeTargetExt(
2367 if (ElemTy != AssignedType)
2380 if (CurrentType == AssignedType)
2387 " for value " +
V->getName(),
2396void SPIRVEmitIntrinsicsImpl::replacePointerOperandWithPtrCast(
2397 Instruction *
I,
Value *Pointer,
Type *ExpectedElementType,
2402 Type *PointerElemTy = deduceElementTypeHelper(Pointer,
false);
2403 if (PointerElemTy == ExpectedElementType ||
2408 Value *ExpectedElementVal =
2410 MetadataAsValue *VMD =
buildMD(ExpectedElementVal);
2412 bool FirstPtrCastOrAssignPtrType =
true;
2418 for (
auto User :
Pointer->users()) {
2421 (
II->getIntrinsicID() != Intrinsic::spv_assign_ptr_type &&
2422 II->getIntrinsicID() != Intrinsic::spv_ptrcast) ||
2423 II->getOperand(0) != Pointer)
2428 FirstPtrCastOrAssignPtrType =
false;
2429 if (
II->getOperand(1) != VMD ||
2436 if (
II->getIntrinsicID() != Intrinsic::spv_ptrcast)
2441 if (
II->getParent() !=
I->getParent())
2444 I->setOperand(OperandToReplace,
II);
2459 if (FirstPtrCastOrAssignPtrType) {
2464 }
else if (isTodoType(Pointer)) {
2465 eraseTodoType(Pointer);
2473 DenseSet<std::pair<Value *, Value *>> VisitedSubst{
2474 std::make_pair(
I, Pointer)};
2476 propagateElemType(Pointer, PrevElemTy, VisitedSubst);
2489 B.CreateIntrinsicWithoutFolding(Intrinsic::spv_ptrcast, {
Types},
Args);
2495void SPIRVEmitIntrinsicsImpl::insertPtrCastOrAssignTypeInstr(Instruction *
I,
2500 replacePointerOperandWithPtrCast(
2501 I,
SI->getValueOperand(), IntegerType::getInt8Ty(CurrF->
getContext()),
2507 Type *OpTy =
Op->getType();
2510 if (
auto It = AggrConstTypes.
find(OpI); It != AggrConstTypes.
end())
2513 if (OpTy ==
Op->getType())
2514 OpTy = deduceElementTypeByValueDeep(OpTy,
Op,
false);
2515 replacePointerOperandWithPtrCast(
I, Pointer, OpTy, 1,
B);
2520 Type *OpTy = LI->getType();
2531 Type *NewOpTy = OpTy;
2532 OpTy = deduceElementTypeByValueDeep(OpTy, LI,
false);
2533 if (OpTy == NewOpTy)
2534 insertTodoType(Pointer);
2537 replacePointerOperandWithPtrCast(
I, Pointer, OpTy, 0,
B);
2542 Type *OpTy =
nullptr;
2554 OpTy = GEPI->getSourceElementType();
2556 replacePointerOperandWithPtrCast(
I, Pointer, OpTy, 0,
B);
2558 insertTodoType(Pointer);
2564 Value *
Op = IVI->getInsertedValueOperand();
2566 replacePointerOperandWithPtrCast(
2574 Value *
Op = IEI->getOperand(1);
2576 replacePointerOperandWithPtrCast(
2577 I,
Op, IntegerType::getInt8Ty(
I->getContext()), 1,
B);
2589 std::string DemangledName =
2593 bool HaveTypes =
false;
2594 for (
unsigned OpIdx = 0; OpIdx < CalledF->
arg_size(); ++OpIdx) {
2612 for (User *U : CalledArg->
users()) {
2614 if ((ElemTy = deduceElementTypeHelper(Inst,
false)) !=
nullptr)
2620 HaveTypes |= ElemTy !=
nullptr;
2625 if (DemangledName.empty() && !HaveTypes)
2629 TM.
getSubtarget<SPIRVSubtarget>(*CalledF).getPreferredInstructionSet();
2631 bool ParseBuiltinTypes =
2632 !DemangledName.empty() &&
2633 (!CalledF->
isDeclaration() || SPIRV::isBuiltin(DemangledName, Set));
2634 for (
unsigned OpIdx = 0; OpIdx < CI->
arg_size(); OpIdx++) {
2649 Type *ExpectedType =
2650 OpIdx < CalledArgTys.
size() ? CalledArgTys[OpIdx] :
nullptr;
2651 if (!ExpectedType && ParseBuiltinTypes)
2652 ExpectedType = SPIRV::parseBuiltinCallArgumentBaseType(
2653 DemangledName, OpIdx,
I->getContext());
2654 if (!ExpectedType || ExpectedType->
isVoidTy())
2662 replacePointerOperandWithPtrCast(CI, ArgOperand, ExpectedType, OpIdx,
B);
2667SPIRVEmitIntrinsicsImpl::visitInsertElementInst(InsertElementInst &
I) {
2670 if (
isVector1(
I.getType()) && !CanUseAnyVectorRank)
2674 I.getOperand(1)->getType(),
2675 I.getOperand(2)->getType()};
2677 B.SetInsertPoint(&
I);
2679 Instruction *NewI =
B.CreateIntrinsicWithoutFolding(Intrinsic::spv_insertelt,
2681 replaceAllUsesWithAndErase(
B, &
I, NewI);
2686SPIRVEmitIntrinsicsImpl::visitExtractElementInst(ExtractElementInst &
I) {
2689 if (
isVector1(
I.getVectorOperandType()) && !CanUseAnyVectorRank)
2693 B.SetInsertPoint(&
I);
2695 I.getIndexOperand()->getType()};
2696 SmallVector<Value *, 2>
Args = {
I.getVectorOperand(),
I.getIndexOperand()};
2697 Instruction *NewI =
B.CreateIntrinsicWithoutFolding(Intrinsic::spv_extractelt,
2699 replaceAllUsesWithAndErase(
B, &
I, NewI);
2707void SPIRVEmitIntrinsicsImpl::scalarizeVectorPtrCasts(
Function &
F) {
2711 if (
ST.canUseExtension(SPIRV::Extension::SPV_INTEL_masked_gather_scatter))
2714 SmallVector<Instruction *, 8> ToErase;
2719 if (!VecTy || !VecTy->getElementType()->isPointerTy())
2723 unsigned NumElems = VecTy->getNumElements();
2727 for (
unsigned Idx = 0;
Idx < NumElems; ++
Idx) {
2730 ElemPtr =
B.CreateExtractElement(PTI->getOperand(0),
B.getInt32(Idx));
2731 Value *Conv =
B.CreatePtrToInt(ElemPtr, ElemIntTy);
2732 Result =
B.CreateInsertElement(Result, Conv,
B.getInt32(Idx));
2735 PTI->replaceAllUsesWith(Result);
2739 if (!VecTy || !VecTy->getElementType()->isPointerTy())
2745 bool AllUsersExtract =
llvm::all_of(ITP->users(), [&](User *U) {
2746 auto *EE = dyn_cast<ExtractElementInst>(U);
2747 return EE && isa<ConstantInt>(EE->getIndexOperand());
2749 if (!AllUsersExtract)
2753 Type *ElemPtrTy = VecTy->getElementType();
2759 B.SetInsertPoint(EE);
2761 B.CreateExtractElement(ITP->getOperand(0),
B.getInt32(Idx));
2762 Value *Conv =
B.CreateIntToPtr(Elem, ElemPtrTy);
2771 if (ToErase.
empty())
2774 for (Instruction *
I : ToErase) {
2775 for (
Value *
Op :
I->operand_values())
2777 I->eraseFromParent();
2782Instruction *SPIRVEmitIntrinsicsImpl::visitInsertValueInst(InsertValueInst &
I) {
2784 B.SetInsertPoint(&
I);
2787 Value *AggregateOp =
I.getAggregateOperand();
2791 Args.push_back(AggregateOp);
2792 Args.push_back(
I.getInsertedValueOperand());
2793 for (
auto &
Op :
I.indices())
2794 Args.push_back(
B.getInt32(
Op));
2796 B.CreateIntrinsicWithoutFolding(Intrinsic::spv_insertv, {
Types}, {
Args});
2797 replaceMemInstrUses(&
I, NewI,
B);
2802SPIRVEmitIntrinsicsImpl::visitExtractValueInst(ExtractValueInst &
I) {
2804 B.SetInsertPoint(&
I);
2805 if (
I.getAggregateOperand()->getType()->isAggregateType()) {
2814 for (
auto &
Op :
I.indices())
2815 Args.push_back(
B.getInt32(
Op));
2816 Instruction *NewI =
B.CreateIntrinsicWithoutFolding(Intrinsic::spv_extractv,
2817 {
I.getType()}, {
Args});
2822 Type *AggrTy =
I.getType();
2823 AggrConstTypes[NewI] = AggrTy;
2825 replaceMemInstrUses(&
I, NewI,
B);
2832 replaceAllUsesWithAndErase(
B, &
I, NewI);
2836Instruction *SPIRVEmitIntrinsicsImpl::visitLoadInst(LoadInst &
I) {
2837 if (!
I.getType()->isAggregateType())
2840 B.SetInsertPoint(&
I);
2841 TrackConstants =
false;
2846 unsigned IntrinsicId;
2847 SmallVector<Value *, 4>
Args = {
I.getPointerOperand(),
B.getInt16(Flags)};
2848 if (!
I.isAtomic()) {
2849 IntrinsicId = Intrinsic::spv_load;
2850 Args.push_back(
B.getInt32(
I.getAlign().value()));
2852 IntrinsicId = Intrinsic::spv_atomic_load;
2853 Args.push_back(
B.getInt8(
static_cast<uint8_t
>(
I.getOrdering())));
2855 CallInst *NewI =
B.CreateIntrinsicWithoutFolding(
2856 IntrinsicId, {
I.getOperand(0)->getType()},
Args);
2858 replaceMemInstrUses(&
I, NewI,
B);
2862Instruction *SPIRVEmitIntrinsicsImpl::visitStoreInst(StoreInst &
I) {
2866 B.SetInsertPoint(&
I);
2867 TrackConstants =
false;
2871 auto *PtrOp =
I.getPointerOperand();
2873 if (
I.getValueOperand()->getType()->isAggregateType()) {
2881 "Unexpected argument of aggregate type, should be spv_extractv!");
2885 unsigned IntrinsicId;
2886 SmallVector<Value *, 4>
Args = {
I.getValueOperand(), PtrOp,
2888 if (!
I.isAtomic()) {
2889 IntrinsicId = Intrinsic::spv_store;
2890 Args.push_back(
B.getInt32(
I.getAlign().value()));
2892 IntrinsicId = Intrinsic::spv_atomic_store;
2893 Args.push_back(
B.getInt8(
static_cast<uint8_t
>(
I.getOrdering())));
2896 IntrinsicId, {
I.getValueOperand()->getType(), PtrOp->
getType()},
Args);
2898 I.eraseFromParent();
2902Instruction *SPIRVEmitIntrinsicsImpl::visitAllocaInst(AllocaInst &
I) {
2903 Value *ArraySize =
nullptr;
2904 if (
I.isArrayAllocation()) {
2907 SPIRV::Extension::SPV_INTEL_variable_length_array))
2909 "array allocation: this instruction requires the following "
2910 "SPIR-V extension: SPV_INTEL_variable_length_array",
2912 ArraySize =
I.getArraySize();
2915 B.SetInsertPoint(&
I);
2916 TrackConstants =
false;
2917 Type *PtrTy =
I.getType();
2920 ?
B.CreateIntrinsicWithoutFolding(
2921 Intrinsic::spv_alloca_array, {PtrTy, ArraySize->
getType()},
2922 {ArraySize,
B.getInt32(
I.getAlign().value())})
2923 :
B.CreateIntrinsicWithoutFolding(
Intrinsic::spv_alloca, {PtrTy},
2924 {
B.getInt32(
I.getAlign().value())});
2925 replaceAllUsesWithAndErase(
B, &
I, NewI);
2930SPIRVEmitIntrinsicsImpl::visitAtomicCmpXchgInst(AtomicCmpXchgInst &
I) {
2931 assert(
I.getType()->isAggregateType() &&
"Aggregate result is expected");
2933 B.SetInsertPoint(&
I);
2936 Args.push_back(
B.getInt32(
static_cast<uint32_t
>(
2940 const SPIRVSubtarget &
ST = TM.
getSubtarget<SPIRVSubtarget>(*
I.getFunction());
2941 unsigned AS =
I.getPointerOperand()->getType()->getPointerAddressSpace();
2942 uint32_t ScSem =
static_cast<uint32_t
>(
2951 Intrinsic::spv_cmpxchg, {
I.getPointerOperand()->getType()}, {
Args});
2952 replaceMemInstrUses(&
I, NewI,
B);
2956Instruction *SPIRVEmitIntrinsicsImpl::visitAtomicRMWInst(AtomicRMWInst &
I) {
2957 auto Op =
I.getOperation();
2968 B.SetInsertPoint(&
I);
2970 const SPIRVSubtarget &
ST = TM.
getSubtarget<SPIRVSubtarget>(*
I.getFunction());
2971 unsigned AS =
I.getPointerOperand()->getType()->getPointerAddressSpace();
2973 uint32_t
Scope =
static_cast<uint32_t
>(
2974 getMemScope(
M->getTargetTriple(),
I.getContext(),
I.getSyncScopeID()));
2975 uint32_t ScSem =
static_cast<uint32_t
>(
2978 M->getTargetTriple(),
2982 ?
"__translate_spirv_atomic_uinc_wrap"
2983 :
"__translate_spirv_atomic_udec_wrap");
2985 Type *ValTy =
I.getValOperand()->getType();
2986 Type *PtrTy =
I.getPointerOperand()->getType();
2988 raw_svector_ostream OS(FuncName);
2989 OS <<
"_p" << AS <<
"_";
2991 OS <<
"v" << VecTy->getNumElements();
2994 Type *Int32Ty =
B.getInt32Ty();
2995 Type *BoolTy =
B.getInt1Ty();
2997 ValTy, BoolTy, BoolTy};
2998 FunctionType *FT = FunctionType::get(ValTy, ArgTys,
false);
2999 FunctionCallee
FC =
M->getOrInsertFunction(FuncName, FT);
3003 I.getPointerOperand(),
B.getInt32(Scope),
3004 B.getInt32(MemSem),
I.getValOperand(),
3005 B.getInt1(
I.isVolatile()),
B.getInt1(
I.isElementwise())};
3006 CallInst *CI =
B.CreateCall(FC, Args);
3012 replaceAllUsesWithAndErase(
B, &
I, CI);
3021 case Intrinsic::spv_abort:
3023 case Intrinsic::trap:
3024 case Intrinsic::ubsantrap:
3026 return ST.canUseExtension(SPIRV::Extension::SPV_KHR_abort);
3042 [&ST](
const Instruction &
II) { return isAbortCall(II, ST); }) &&
3043 "abort-like call must be the last non-debug instruction before its "
3044 "block's terminator");
3048Instruction *SPIRVEmitIntrinsicsImpl::visitUnreachableInst(UnreachableInst &
I) {
3049 const SPIRVSubtarget &
ST = TM.
getSubtarget<SPIRVSubtarget>(*
I.getFunction());
3053 B.CreateIntrinsic(Intrinsic::spv_unreachable, {});
3060 return Name ==
"llvm.compiler.used" || Name ==
"llvm.used";
3074 while (!Stack.empty()) {
3075 const Value *
V = Stack.pop_back_val();
3076 if (!Visited.
insert(
V).second)
3084 Stack.append(
C->user_begin(),
C->user_end());
3100 auto &UserFunctions = GVUsers.getTransitiveUserFunctions(GV);
3101 if (UserFunctions.contains(
F))
3106 if (!UserFunctions.empty())
3111 const Module &M = *
F->getParent();
3112 const Function &FirstDefinition = *M.getFunctionDefs().
begin();
3113 return F == &FirstDefinition;
3116Value *SPIRVEmitIntrinsicsImpl::buildSpvUndefComposite(
Type *AggrTy,
3118 auto MakeLeaf = [&](
Type *ElemTy) -> Instruction * {
3119 CallInst *Leaf =
B.CreateIntrinsicWithoutFolding(Intrinsic::spv_undef, {});
3121 AggrConstTypes[Leaf] = ElemTy;
3124 SmallVector<Value *, 4> Elems;
3126 Elems.
assign(ArrTy->getNumElements(), MakeLeaf(ArrTy->getElementType()));
3129 DenseMap<Type *, Instruction *> LeafByType;
3130 for (
unsigned I = 0;
I < StructTy->getNumElements(); ++
I) {
3132 auto &
Entry = LeafByType[ElemTy];
3134 Entry = MakeLeaf(ElemTy);
3138 CallInst *Composite =
B.CreateIntrinsicWithoutFolding(
3139 Intrinsic::spv_const_composite, {
B.getInt32Ty()}, Elems);
3141 AggrConstTypes[Composite] = AggrTy;
3150void SPIRVEmitIntrinsicsImpl::reconstructAggregateReturns(
Function &Func,
3155 for (BasicBlock &BB : Func) {
3159 Value *RetVal = RI->getReturnValue();
3166 B.SetInsertPoint(RI);
3169 Value *Elt =
B.CreateExtractValue(RetVal,
I);
3170 Rebuilt =
B.CreateInsertValue(Rebuilt, Elt,
I);
3172 RI->setOperand(0, Rebuilt);
3176void SPIRVEmitIntrinsicsImpl::processGlobalValue(GlobalVariable &GV,
3186 deduceElementTypeHelper(&GV,
false);
3191 Value *InitOp = Init;
3198 CallInst *
Call =
B.CreateIntrinsicWithoutFolding(Intrinsic::spv_poison,
3199 {
B.getInt32Ty()}, {});
3204 InitOp = buildSpvUndefComposite(Init->
getType(),
B);
3209 CallInst *InitInst =
B.CreateIntrinsicWithoutFolding(
3210 Intrinsic::spv_init_global, {GV.
getType(), Ty}, {&GV,
Const});
3216 B.CreateIntrinsic(Intrinsic::spv_unref_global, GV.
getType(), &GV);
3222bool SPIRVEmitIntrinsicsImpl::insertAssignPtrTypeIntrs(Instruction *
I,
3224 bool UnknownElemTypeI8) {
3230 if (
Type *ElemTy = deduceElementType(
I, UnknownElemTypeI8)) {
3237void SPIRVEmitIntrinsicsImpl::insertAssignTypeIntrs(Instruction *
I,
3240 static StringMap<unsigned> ResTypeWellKnown = {
3241 {
"async_work_group_copy", WellKnownTypes::Event},
3242 {
"async_work_group_strided_copy", WellKnownTypes::Event},
3243 {
"__spirv_GroupAsyncCopy", WellKnownTypes::Event}};
3247 bool IsKnown =
false;
3252 std::string DemangledName =
3255 if (DemangledName.length() > 0)
3257 SPIRV::lookupBuiltinNameHelper(DemangledName, &DecorationId);
3258 auto ResIt = ResTypeWellKnown.
find(DemangledName);
3259 if (ResIt != ResTypeWellKnown.
end()) {
3262 switch (ResIt->second) {
3263 case WellKnownTypes::Event:
3266 CanUseAnyVectorRank);
3271 switch (DecorationId) {
3274 case FPDecorationId::SAT:
3277 case FPDecorationId::RTE:
3279 CI, SPIRV::FPRoundingMode::FPRoundingMode::RTE,
B);
3281 case FPDecorationId::RTZ:
3283 CI, SPIRV::FPRoundingMode::FPRoundingMode::RTZ,
B);
3285 case FPDecorationId::RTP:
3287 CI, SPIRV::FPRoundingMode::FPRoundingMode::RTP,
B);
3289 case FPDecorationId::RTN:
3291 CI, SPIRV::FPRoundingMode::FPRoundingMode::RTN,
B);
3297 Type *Ty =
I->getType();
3300 Type *TypeToAssign = Ty;
3303 auto It = AggrConstTypes.
find(
II);
3304 if (It == AggrConstTypes.
end())
3306 TypeToAssign = It->second;
3307 }
else if (
II->getIntrinsicID() == Intrinsic::spv_poison) {
3308 if (
auto It = AggrConstTypes.
find(
II); It != AggrConstTypes.
end())
3309 TypeToAssign = It->second;
3311 }
else if (
auto It = AggrConstTypes.
find(
I); It != AggrConstTypes.
end())
3312 TypeToAssign = It->second;
3316 for (
const auto &
Op :
I->operands()) {
3324 Type *OpTy =
Op->getType();
3326 CallInst *AssignCI =
3331 Type *OpTy =
Op->getType();
3347 Intrinsic::spv_assign_type, {OpTy},
3357bool SPIRVEmitIntrinsicsImpl::shouldTryToAddMemAliasingDecoration(
3358 Instruction *Inst) {
3360 if (!STI->
canUseExtension(SPIRV::Extension::SPV_INTEL_memory_access_aliasing))
3370void SPIRVEmitIntrinsicsImpl::insertSpirvDecorations(Instruction *
I,
3372 if (MDNode *MD =
I->getMetadata(
"spirv.Decorations")) {
3374 B.CreateIntrinsic(Intrinsic::spv_assign_decoration, {
I->getType()},
3379 auto processMemAliasingDecoration = [&](
unsigned Kind) {
3380 if (MDNode *AliasListMD =
I->getMetadata(Kind)) {
3381 if (shouldTryToAddMemAliasingDecoration(
I)) {
3382 uint32_t Dec =
Kind == LLVMContext::MD_alias_scope
3383 ? SPIRV::Decoration::AliasScopeINTEL
3384 : SPIRV::Decoration::NoAliasINTEL;
3386 I, ConstantInt::get(
B.getInt32Ty(), Dec),
3389 B.CreateIntrinsic(Intrinsic::spv_assign_aliasing_decoration,
3390 {
I->getType()}, {
Args});
3394 processMemAliasingDecoration(LLVMContext::MD_alias_scope);
3395 processMemAliasingDecoration(LLVMContext::MD_noalias);
3398 if (MDNode *MD =
I->getMetadata(LLVMContext::MD_fpmath)) {
3400 bool AllowFPMaxError =
3402 if (!AllowFPMaxError)
3406 B.CreateIntrinsic(Intrinsic::spv_assign_fpmaxerror_decoration,
3412 LLVMContext &Ctx =
B.getContext();
3414 B.getInt32Ty(), SPIRV::Decoration::AuxDataInstructionMetadata));
3417 if (
I->hasMetadata(
"amdgpu.no.fine.grained.memory"))
3419 Ctx, {AuxMD,
MDString::get(Ctx,
"amdgpu.no.fine.grained.memory")}));
3420 if (
I->hasMetadata(
"amdgpu.no.remote.memory"))
3422 Ctx, {AuxMD,
MDString::get(Ctx,
"amdgpu.no.remote.memory")}));
3423 if (
I->hasMetadata(LLVMContext::MD_atomic_ignore_denormal_mode))
3425 Ctx, {AuxMD,
MDString::get(Ctx,
"atomic.ignore.denormal.mode")}));
3428 B.CreateIntrinsic(Intrinsic::spv_assign_decoration, {
I->getType()},
3437 &FPFastMathDefaultInfoMap,
3439 auto it = FPFastMathDefaultInfoMap.
find(
F);
3440 if (it != FPFastMathDefaultInfoMap.
end())
3448 SPIRV::FPFastMathMode::None);
3450 SPIRV::FPFastMathMode::None);
3452 SPIRV::FPFastMathMode::None);
3453 return FPFastMathDefaultInfoMap[
F] = std::move(FPFastMathDefaultInfoVec);
3459 size_t BitWidth = Ty->getScalarSizeInBits();
3463 assert(Index >= 0 && Index < 3 &&
3464 "Expected FPFastMathDefaultInfo for half, float, or double");
3465 assert(FPFastMathDefaultInfoVec.
size() == 3 &&
3466 "Expected FPFastMathDefaultInfoVec to have exactly 3 elements");
3467 return FPFastMathDefaultInfoVec[Index];
3470void SPIRVEmitIntrinsicsImpl::insertConstantsForFPFastMathDefault(
Module &M) {
3472 if (!
ST->canUseExtension(SPIRV::Extension::SPV_KHR_float_controls2))
3481 auto Node =
M.getNamedMetadata(
"spirv.ExecutionMode");
3483 if (!
M.getNamedMetadata(
"opencl.enable.FP_CONTRACT")) {
3491 ConstantInt::get(Type::getInt32Ty(
M.getContext()), 0);
3494 [[maybe_unused]] GlobalVariable *GV =
3495 new GlobalVariable(M,
3496 Type::getInt32Ty(
M.getContext()),
3510 MapVector<Function *, SPIRV::FPFastMathDefaultInfoVector>
3511 FPFastMathDefaultInfoMap;
3513 for (
unsigned i = 0; i <
Node->getNumOperands(); i++) {
3522 if (EM == SPIRV::ExecutionMode::FPFastMathDefault) {
3524 "Expected 4 operands for FPFastMathDefault");
3530 SPIRV::FPFastMathDefaultInfoVector &FPFastMathDefaultInfoVec =
3532 SPIRV::FPFastMathDefaultInfo &
Info =
3535 Info.FPFastMathDefault =
true;
3536 }
else if (EM == SPIRV::ExecutionMode::ContractionOff) {
3538 "Expected no operands for ContractionOff");
3542 SPIRV::FPFastMathDefaultInfoVector &FPFastMathDefaultInfoVec =
3544 for (SPIRV::FPFastMathDefaultInfo &Info : FPFastMathDefaultInfoVec) {
3545 Info.ContractionOff =
true;
3547 }
else if (EM == SPIRV::ExecutionMode::SignedZeroInfNanPreserve) {
3549 "Expected 1 operand for SignedZeroInfNanPreserve");
3550 unsigned TargetWidth =
3555 SPIRV::FPFastMathDefaultInfoVector &FPFastMathDefaultInfoVec =
3559 assert(Index >= 0 && Index < 3 &&
3560 "Expected FPFastMathDefaultInfo for half, float, or double");
3561 assert(FPFastMathDefaultInfoVec.
size() == 3 &&
3562 "Expected FPFastMathDefaultInfoVec to have exactly 3 elements");
3563 FPFastMathDefaultInfoVec[
Index].SignedZeroInfNanPreserve =
true;
3567 DenseMap<unsigned, GlobalVariable *> GlobalVars;
3568 for (
auto &[Func, FPFastMathDefaultInfoVec] : FPFastMathDefaultInfoMap) {
3569 if (FPFastMathDefaultInfoVec.
empty())
3572 for (
const SPIRV::FPFastMathDefaultInfo &Info : FPFastMathDefaultInfoVec) {
3573 assert(
Info.Ty &&
"Expected target type for FPFastMathDefaultInfo");
3576 if (Flags == SPIRV::FPFastMathMode::None && !
Info.ContractionOff &&
3577 !
Info.SignedZeroInfNanPreserve && !
Info.FPFastMathDefault)
3581 if (
Info.ContractionOff && (Flags & SPIRV::FPFastMathMode::AllowContract))
3583 "and AllowContract");
3585 if (
Info.SignedZeroInfNanPreserve &&
3587 (SPIRV::FPFastMathMode::NotNaN | SPIRV::FPFastMathMode::NotInf |
3588 SPIRV::FPFastMathMode::NSZ))) {
3589 if (
Info.FPFastMathDefault)
3591 "SignedZeroInfNanPreserve but at least one of "
3592 "NotNaN/NotInf/NSZ is enabled.");
3595 if ((Flags & SPIRV::FPFastMathMode::AllowTransform) &&
3596 !((Flags & SPIRV::FPFastMathMode::AllowReassoc) &&
3597 (Flags & SPIRV::FPFastMathMode::AllowContract))) {
3599 "AllowTransform requires AllowReassoc and "
3600 "AllowContract to be set.");
3603 auto it = GlobalVars.
find(Flags);
3604 GlobalVariable *GV =
nullptr;
3605 if (it != GlobalVars.
end()) {
3611 ConstantInt::get(Type::getInt32Ty(
M.getContext()), Flags);
3614 GV =
new GlobalVariable(M,
3615 Type::getInt32Ty(
M.getContext()),
3620 GlobalVars[
Flags] = GV;
3626void SPIRVEmitIntrinsicsImpl::processInstrAfterVisit(Instruction *
I,
3629 bool IsConstComposite =
3630 II &&
II->getIntrinsicID() == Intrinsic::spv_const_composite;
3631 if (IsConstComposite && TrackConstants) {
3633 auto t = AggrConsts.
find(
I);
3637 {
II->getType(),
II->getType()}, t->second,
I, {},
B);
3639 NewOp->setArgOperand(0,
I);
3642 for (
const auto &
Op :
I->operands()) {
3646 unsigned OpNo =
Op.getOperandNo();
3647 if (
II && ((
II->getIntrinsicID() == Intrinsic::spv_gep && OpNo == 0) ||
3648 (!
II->isBundleOperand(OpNo) &&
3649 II->paramHasAttr(OpNo, Attribute::ImmArg))))
3653 IsPhi ?
B.SetInsertPointPastAllocas(
I->getParent()->getParent())
3654 :
B.SetInsertPoint(
I);
3657 Type *OpTy =
Op->getType();
3665 {OpTy, OpTyVal->
getType()},
Op, OpTyVal, {},
B);
3667 if (!IsConstComposite &&
isPointerTy(OpTy) && OpElemTy !=
nullptr &&
3668 OpElemTy != IntegerType::getInt8Ty(
I->getContext())) {
3670 SmallVector<Value *, 2>
Args = {
3674 CallInst *PtrCasted =
B.CreateIntrinsicWithoutFolding(
3680 I->setOperand(OpNo, NewOp);
3686Type *SPIRVEmitIntrinsicsImpl::deduceFunParamElementType(
Function *
F,
3688 SmallPtrSet<Function *, 0> FVisited;
3689 return deduceFunParamElementType(
F, OpIdx, FVisited);
3692Type *SPIRVEmitIntrinsicsImpl::deduceFunParamElementType(
3693 Function *
F,
unsigned OpIdx, SmallPtrSetImpl<Function *> &FVisited) {
3695 if (!FVisited.
insert(
F).second)
3698 SmallPtrSet<Value *, 0> Visited;
3701 for (User *U :
F->users()) {
3703 if (!CI || OpIdx >= CI->
arg_size())
3713 if (
Type *Ty = deduceElementTypeHelper(OpArg, Visited,
false))
3716 for (User *OpU : OpArg->
users()) {
3718 if (!Inst || Inst == CI)
3721 if (
Type *Ty = deduceElementTypeHelper(Inst, Visited,
false))
3728 if (FVisited.
find(OuterF) != FVisited.
end())
3730 for (
unsigned i = 0; i < OuterF->
arg_size(); ++i) {
3731 if (OuterF->
getArg(i) == OpArg) {
3732 Lookup.push_back(std::make_pair(OuterF, i));
3739 for (
auto &Pair :
Lookup) {
3740 if (
Type *Ty = deduceFunParamElementType(Pair.first, Pair.second, FVisited))
3747void SPIRVEmitIntrinsicsImpl::processParamTypesByFunHeader(
Function *
F,
3749 B.SetInsertPointPastAllocas(
F);
3750 for (
unsigned OpIdx = 0; OpIdx <
F->arg_size(); ++OpIdx) {
3756 for (User *U : Arg->
users()) {
3758 if (
GEP &&
GEP->getPointerOperand() == Arg) {
3776 for (User *U :
F->users()) {
3778 if (!CI || OpIdx >= CI->
arg_size())
3792 for (User *U : Arg->
users()) {
3796 CI->
getParent()->getParent() == CurrF) {
3798 deduceOperandElementTypeFunctionPointer(CI,
Ops, ElemTy,
false);
3810 B.SetInsertPointPastAllocas(
F);
3811 for (
unsigned OpIdx = 0; OpIdx <
F->arg_size(); ++OpIdx) {
3816 if (!ElemTy && (ElemTy = deduceFunParamElementType(
F, OpIdx)) !=
nullptr) {
3818 DenseSet<std::pair<Value *, Value *>> VisitedSubst;
3822 propagateElemType(Arg, IntegerType::getInt8Ty(
F->getContext()),
3834 bool IsNewFTy =
false;
3850bool SPIRVEmitIntrinsicsImpl::processFunctionPointers(
Module &M) {
3853 if (
F.isIntrinsic())
3855 if (
F.isDeclaration()) {
3856 for (User *U :
F.users()) {
3859 UF &&
UF->hasPersonalityFn() &&
UF->getPersonalityFn() == &
F)
3873 for (User *U :
F.users()) {
3875 if (!
II ||
II->arg_size() != 3 ||
II->getOperand(0) != &
F)
3877 if (
II->getIntrinsicID() == Intrinsic::spv_assign_ptr_type ||
3878 II->getIntrinsicID() == Intrinsic::spv_ptrcast) {
3886 if (Worklist.
empty())
3889 LLVMContext &Ctx =
M.getContext();
3896 for (
const auto &Arg :
F->args())
3899 IRB.CreateCall(
F, Args)->setTailCall(
true);
3901 IRB.CreateRetVoid();
3907void SPIRVEmitIntrinsicsImpl::applyDemangledPtrArgTypes(
IRBuilder<> &
B) {
3908 DenseMap<Function *, CallInst *> Ptrcasts;
3909 for (
auto It : FDeclPtrTys) {
3911 for (
auto *U :
F->users()) {
3916 for (
auto [Idx, ElemTy] : It.second) {
3924 B.SetInsertPointPastAllocas(Arg->
getParent());
3931 replaceUsesOfWithSpvPtrcast(
3932 Param,
normalizeType(ElemTy, CanUseAnyVectorRank), CI, Ptrcasts);
3941 .getFirstNonPHIOrAlloca());
3959 FDeclPtrTys.
clear();
3962GetElementPtrInst *SPIRVEmitIntrinsicsImpl::simplifyZeroLengthArrayGepInst(
3963 GetElementPtrInst *
GEP) {
3970 Type *SrcTy =
GEP->getSourceElementType();
3971 SmallVector<Value *, 8> Indices(
GEP->indices());
3973 if (ArrTy && ArrTy->getNumElements() == 0 &&
match(Indices[0],
m_Zero())) {
3974 Indices.erase(Indices.begin());
3975 SrcTy = ArrTy->getElementType();
3977 GEP->getNoWrapFlags(),
"",
3978 GEP->getIterator());
3983void SPIRVEmitIntrinsicsImpl::emitUnstructuredLoopControls(
Function &
F,
3990 if (
ST->canUseExtension(
3991 SPIRV::Extension::SPV_INTEL_unstructured_loop_controls)) {
3992 for (BasicBlock &BB :
F) {
3994 MDNode *LoopMD =
Term->getMetadata(LLVMContext::MD_loop);
3998 SmallVector<unsigned, 1>
Ops =
4000 unsigned LC =
Ops[0];
4001 if (LC == SPIRV::LoopControl::None)
4005 B.SetInsertPoint(Term);
4006 SmallVector<Value *, 4> IntrArgs;
4007 for (
unsigned Op :
Ops)
4009 B.CreateIntrinsic(Intrinsic::spv_loop_control_intel, IntrArgs);
4021 SmallPtrSet<BasicBlock *, 8> UsedMergeBlocks;
4028 SmallVector<unsigned, 1> LoopControlOps =
4030 if (LoopControlOps[0] == SPIRV::LoopControl::None)
4043 for (BasicBlock *BB : {Latch, Header}) {
4047 if (!
L->contains(Succ) && !UsedMergeBlocks.
contains(Succ))
4050 if (!MergeBlock || !UsedMergeBlocks.
insert(MergeBlock).second)
4053 B.SetInsertPoint(Header->getTerminator());
4056 SmallVector<Value *, 4>
Args = {MergeAddress, ContinueAddress};
4057 for (
unsigned Imm : LoopControlOps)
4058 Args.emplace_back(
B.getInt32(
Imm));
4059 B.CreateIntrinsic(Intrinsic::spv_loop_merge, {
Args});
4063bool SPIRVEmitIntrinsicsImpl::runOnFunction(
Function &Func) {
4064 if (
Func.isDeclaration())
4073 GR =
ST.getSPIRVGlobalRegistry();
4077 ST.canUseExtension(SPIRV::Extension::SPV_INTEL_function_pointers);
4079 CanUseAnyVectorRank =
4080 ST.canUseExtension(SPIRV::Extension::SPV_EXT_long_vector);
4084 AggrConstTypes.
clear();
4087 scalarizeVectorPtrCasts(Func);
4088 processParamTypesByFunHeader(CurrF,
B);
4090 if (
ST.isLogicalSPIRV())
4091 foldConstantOffsetIntoArrayIndex(Func);
4095 SmallPtrSet<Instruction *, 4> DeadInsts;
4098 Type *ElTy =
SI->getValueOperand()->getType();
4113 normalizeType(SGEP->getResultElementType(), CanUseAnyVectorRank));
4117 GetElementPtrInst *NewGEP = simplifyZeroLengthArrayGepInst(
GEP);
4119 GEP->replaceAllUsesWith(NewGEP);
4123 if (
Type *GepTy = getGEPType(
GEP))
4127 for (
auto *
I : DeadInsts) {
4128 assert(
I->use_empty() &&
"Dead instruction should not have any uses left");
4129 I->eraseFromParent();
4131 if (AccessChainErrors)
4134 B.SetInsertPoint(
Func.getEntryBlock().begin());
4135 for (
auto &GV :
Func.getParent()->globals())
4136 processGlobalValue(GV,
B);
4138 reconstructAggregateReturns(Func,
B);
4143 insertCompositeAggregateArms(&
I,
B);
4144 preprocessUndefsAndPoisons(
B);
4145 simplifyNullAddrSpaceCasts();
4146 preprocessCompositeConstants(
B);
4154 Type *I32Ty =
B.getInt32Ty();
4158 AggrConstTypes[&
I] =
I.getType();
4159 I.mutateType(I32Ty);
4162 preprocessBoolVectorBitcasts(Func);
4163 SmallVector<Instruction *> Worklist(
4166 applyDemangledPtrArgTypes(
B);
4169 for (
auto &
I : Worklist) {
4171 if (isConvergenceIntrinsic(
I))
4174 bool Postpone = insertAssignPtrTypeIntrs(
I,
B,
false);
4176 insertAssignTypeIntrs(
I,
B);
4177 insertPtrCastOrAssignTypeInstr(
I,
B);
4182 insertAssignPtrTypeIntrs(
I,
B,
true);
4185 useRoundingMode(FPI,
B);
4190 SmallPtrSet<Instruction *, 4> IncompleteRets;
4192 deduceOperandElementType(&
I, &IncompleteRets);
4196 for (BasicBlock &BB : Func)
4197 for (PHINode &Phi : BB.
phis())
4199 deduceOperandElementType(&Phi,
nullptr);
4201 for (
auto *
I : Worklist) {
4202 TrackConstants =
true;
4208 if (AccessChainErrors)
4214 if (isConvergenceIntrinsic(
I))
4218 processInstrAfterVisit(
I,
B);
4221 emitUnstructuredLoopControls(Func,
B);
4227bool SPIRVEmitIntrinsicsImpl::postprocessTypes(
Module &M) {
4228 if (!GR || TodoTypeSz == 0)
4231 unsigned SzTodo = TodoTypeSz;
4232 DenseMap<Value *, SmallPtrSet<Value *, 4>> ToProcess;
4239 if (!KnownTy || !AssignCI)
4245 SmallPtrSet<Value *, 0> Visited;
4246 if (
Type *ElemTy = deduceElementTypeHelper(
Op, Visited,
false,
true)) {
4247 if (ElemTy != KnownTy) {
4248 DenseSet<std::pair<Value *, Value *>> VisitedSubst;
4249 propagateElemType(CI, ElemTy, VisitedSubst);
4256 if (
Op->hasUseList()) {
4257 for (User *U :
Op->users()) {
4264 if (TodoTypeSz == 0)
4269 SmallPtrSet<Instruction *, 4> IncompleteRets;
4271 auto It = ToProcess.
find(&
I);
4272 if (It == ToProcess.
end())
4274 It->second.remove_if([
this](
Value *
V) {
return !isTodoType(
V); });
4275 if (It->second.size() == 0)
4277 deduceOperandElementType(&
I, &IncompleteRets, &It->second,
true);
4278 if (TodoTypeSz == 0)
4283 return SzTodo > TodoTypeSz;
4297 .Cases({
"char",
"signed char",
"unsigned char",
"short",
4298 "unsigned short",
"int",
"unsigned int",
"_Float16",
"float",
4306 unsigned NumElts = 0;
4307 if (
Count.getAsInteger(10, NumElts) || NumElts == 0)
4314 TypeStr.
split(Quals,
' ', -1,
false);
4317 if (Qual !=
"const" && Qual !=
"volatile" && Qual !=
"restrict" &&
4318 !(Qual.consume_front(
"AS") && !Qual.getAsInteger(10, AS)))
4325void SPIRVEmitIntrinsicsImpl::parseFunDeclarations(
Module &M) {
4327 if (!
F.isDeclaration() ||
F.isIntrinsic())
4330 if (DemangledName.empty())
4333 auto Set =
ST.getPreferredInstructionSet();
4334 auto [Grp, Opcode, ExtNo] = SPIRV::mapBuiltinToOpcode(DemangledName, Set);
4336 const bool IsBuiltin = Grp >= 0 || SPIRV::isBuiltin(DemangledName, Set);
4337 if (IsBuiltin && Opcode != SPIRV::OpGroupAsyncCopy)
4339 SmallVector<unsigned> Idxs;
4340 for (Argument &Arg :
F.args())
4345 LLVMContext &Ctx =
F.getContext();
4347 SPIRV::parseBuiltinTypeStr(TypeStrs, DemangledName, Ctx);
4348 if (TypeStrs.
empty())
4351 if (!IsBuiltin && (!
F.getName().starts_with(
"_Z") ||
F.hasStructRetAttr() ||
4352 StringRef(DemangledName).
count(
'(') != 1 ||
4353 StringRef(DemangledName).
count(
')') != 1 ||
4354 StringRef(DemangledName).
contains(
'<') ||
4355 TypeStrs.
size() !=
F.arg_size()))
4357 bool AllowLongVectors =
4358 ST.canUseExtension(SPIRV::Extension::SPV_EXT_long_vector);
4359 for (
unsigned Idx : Idxs) {
4360 if (Idx >= TypeStrs.
size())
4362 StringRef TypeStr = TypeStrs[
Idx].trim();
4363 Type *ElemTy = IsBuiltin
4364 ? SPIRV::parseBuiltinCallArgumentType(TypeStr, Ctx)
4374 FDeclPtrTys[&
F].emplace_back(Idx, ElemTy);
4376 ST.getSPIRVGlobalRegistry()->addDeducedElementType(
F.getArg(Idx),
4382bool SPIRVEmitIntrinsicsImpl::processMaskedMemIntrinsic(IntrinsicInst &
I) {
4383 const SPIRVSubtarget &
ST = TM.
getSubtarget<SPIRVSubtarget>(*
I.getFunction());
4385 if (
I.getIntrinsicID() == Intrinsic::masked_gather) {
4386 if (!
ST.canUseExtension(
4387 SPIRV::Extension::SPV_INTEL_masked_gather_scatter)) {
4388 I.getContext().emitError(
4389 &
I,
"llvm.masked.gather requires SPV_INTEL_masked_gather_scatter "
4393 I.eraseFromParent();
4399 Value *Ptrs =
I.getArgOperand(0);
4401 Value *Passthru =
I.getArgOperand(2);
4404 uint32_t
Alignment =
I.getParamAlign(0).valueOrOne().value();
4406 SmallVector<Value *, 4>
Args = {Ptrs,
B.getInt32(Alignment),
Mask,
4411 auto *NewI =
B.CreateIntrinsic(Intrinsic::spv_masked_gather, Types, Args);
4413 I.eraseFromParent();
4417 if (
I.getIntrinsicID() == Intrinsic::masked_scatter) {
4418 if (!
ST.canUseExtension(
4419 SPIRV::Extension::SPV_INTEL_masked_gather_scatter)) {
4420 I.getContext().emitError(
4421 &
I,
"llvm.masked.scatter requires SPV_INTEL_masked_gather_scatter "
4424 I.eraseFromParent();
4431 Value *Ptrs =
I.getArgOperand(1);
4436 uint32_t
Alignment =
I.getParamAlign(1).valueOrOne().value();
4438 SmallVector<Value *, 4>
Args = {
Values, Ptrs,
B.getInt32(Alignment),
Mask};
4442 B.CreateIntrinsic(Intrinsic::spv_masked_scatter, Types, Args);
4443 I.eraseFromParent();
4454void SPIRVEmitIntrinsicsImpl::preprocessBoolVectorBitcasts(
Function &
F) {
4455 struct BoolVecBitcast {
4457 FixedVectorType *BoolVecTy;
4461 auto getAsBoolVec = [](
Type *Ty) -> FixedVectorType * {
4463 return (VTy && VTy->getElementType()->
isIntegerTy(1)) ? VTy :
nullptr;
4471 if (
auto *BVTy = getAsBoolVec(BC->getSrcTy()))
4473 else if (
auto *BVTy = getAsBoolVec(BC->getDestTy()))
4477 for (
auto &[BC, BoolVecTy, SrcIsBoolVec] : ToReplace) {
4479 Value *Src = BC->getOperand(0);
4480 unsigned BoolVecN = BoolVecTy->getNumElements();
4483 Type *OtherTy = SrcIsBoolVec ? BC->getDestTy() : Src->getType();
4484 unsigned NumElts = 1;
4486 NumElts = VTy->getNumElements();
4492 if (!SrcIsBoolVec) {
4495 auto GetLane = [&](
unsigned I) {
4498 Elt =
B.CreateExtractElement(IntVal,
B.getInt32(
I / EltBits));
4502 return B.CreateICmpNE(
And, ConstantInt::get(EltTy, 0));
4510 if (!Idx ||
Idx->getValue().uge(BoolVecN))
4512 B.SetInsertPoint(EE);
4513 EE->replaceAllUsesWith(GetLane(
Idx->getZExtValue()));
4514 EE->eraseFromParent();
4516 if (BC->use_empty()) {
4517 BC->eraseFromParent();
4521 B.SetInsertPoint(BC);
4523 for (
unsigned I = 0;
I < BoolVecN; ++
I)
4524 Result =
B.CreateInsertElement(Result, GetLane(
I),
B.getInt32(
I));
4528 for (
unsigned J = 0; J < NumElts; ++J) {
4529 Value *Elt = ConstantInt::get(EltTy, 0);
4530 for (
unsigned Bit = 0;
Bit < EltBits; ++
Bit) {
4532 B.CreateExtractElement(Src,
B.getInt32(J * EltBits + Bit));
4533 Value *Ext =
B.CreateZExt(Lane, EltTy);
4535 Ext =
B.CreateShl(Ext, ConstantInt::get(EltTy, Bit));
4536 Elt =
B.CreateOr(Elt, Ext);
4538 IntVal = NumElts > 1 ?
B.CreateInsertElement(IntVal, Elt,
B.getInt32(J))
4541 Result =
B.CreateBitCast(IntVal, BC->getDestTy());
4544 BC->replaceAllUsesWith(Result);
4545 BC->eraseFromParent();
4549bool SPIRVEmitIntrinsicsImpl::convertMaskedMemIntrinsics(
Module &M) {
4553 if (!
F.isIntrinsic())
4556 if (IID != Intrinsic::masked_gather && IID != Intrinsic::masked_scatter)
4561 Changed |= processMaskedMemIntrinsic(*
II);
4565 F.eraseFromParent();
4571bool SPIRVEmitIntrinsicsImpl::preprocessModule(
Module &M) {
4575 Type *I32Ty = Type::getInt32Ty(
M.getContext());
4577 if (
F.isDeclaration())
4583 CE &&
CE->getOpcode() == Instruction::GetElementPtr)
4590 if (!AI || !AI->isStaticAlloca() || !AI->isArrayAllocation() ||
4591 AI->getAddressSpace() !=
4596 if (
Count->isZero() || !
Count->getValue().isIntN(32))
4598 AI->setAllocatedType(
4599 ArrayType::get(AI->getAllocatedType(),
Count->getZExtValue()));
4600 AI->setOperand(0, ConstantInt::get(I32Ty, 1));
4604 Changed |= convertMaskedMemIntrinsics(M);
4612 GEPs,
nullptr,
false,
true);
4617bool SPIRVEmitIntrinsicsImpl::runOnModule(
Module &M) {
4618 bool Changed = preprocessModule(M);
4620 parseFunDeclarations(M);
4621 insertConstantsForFPFastMathDefault(M);
4627 if (AccessChainErrors)
4634 if (!
F.isDeclaration() && !
F.isIntrinsic()) {
4636 processParamTypes(&
F,
B);
4640 CanTodoType =
false;
4641 Changed |= postprocessTypes(M);
4644 Changed |= processFunctionPointers(M);
4651 if (SPIRVEmitIntrinsicsImpl(TM).runOnModule(M))
4657 return new SPIRVEmitIntrinsicsLegacy(TM);
const TargetLowering & TLI
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
Expand Atomic instructions
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
static void replaceAllUsesWith(Value *Old, Value *New, SmallPtrSet< BasicBlock *, 32 > &FreshBBs, bool IsHuge)
Replace all old uses with new ones, and push the updated BBs into FreshBBs.
static Type * getPointeeType(Value *Ptr, const DataLayout &DL)
This file defines the DenseMap class.
This file defines the DenseSet and SmallDenseSet classes.
static bool runOnFunction(Function &F, bool PostInlining)
iv Induction Variable Users
const AbstractManglingParser< Derived, Alloc >::OperatorInfo AbstractManglingParser< Derived, Alloc >::Ops[]
Machine Check Debug Module
This file implements a map that provides insertion order iteration.
uint64_t IntrinsicInst * II
OptimizedStructLayoutField Field
#define INITIALIZE_PASS(passName, arg, name, cfg, analysis)
static bool isMemInstrToReplace(Instruction *I)
static bool isAggrConstForceInt32(const Value *V)
static Type * getAtomicElemTy(SPIRVGlobalRegistry *GR, Instruction *I, Value *PointerOperand)
static void reportFatalOnTokenType(const Instruction *I)
static void setInsertPointAfterDef(IRBuilder<> &B, Instruction *I)
static SPIRV::FPFastMathDefaultInfoVector & getOrCreateFPFastMathDefaultInfoVec(const Module &M, MapVector< Function *, SPIRV::FPFastMathDefaultInfoVector > &FPFastMathDefaultInfoMap, Function *F)
static bool isArtificialGlobal(StringRef Name)
static Type * getPointeeTypeByCallInst(StringRef DemangledName, Function *CalledF, unsigned OpIdx)
static void createRoundingModeDecoration(Instruction *I, unsigned RoundingModeDeco, IRBuilder<> &B)
static void createDecorationIntrinsic(Instruction *I, MDNode *Node, IRBuilder<> &B)
static void emitAssignName(const SPIRVOptions &CLOpts, Instruction *I, IRBuilder<> &B)
static bool hasOnlyArtificialUses(const GlobalVariable &GV)
static bool isAggregateValueIdInstr(const Instruction &I)
static SPIRV::FPFastMathDefaultInfo & getFPFastMathDefaultInfo(SPIRV::FPFastMathDefaultInfoVector &FPFastMathDefaultInfoVec, const Type *Ty)
static bool isAbortCall(const Instruction &I, const SPIRVSubtarget &ST)
static bool tracesToPointerAlloca(Value *V)
static bool isUseListGlobal(StringRef Name)
static bool IsKernelArgInt8(Function *F, StoreInst *SI)
static void addSaturatedDecorationToIntrinsic(Instruction *I, IRBuilder<> &B)
static bool isFirstIndexZero(const GetElementPtrInst *GEP)
static void setInsertPointSkippingPhis(IRBuilder<> &B, Instruction *I)
static bool isSpvAggrPlaceholder(const Value *V)
static Type * getMemberPointeeType(Type *AggrTy, ArrayRef< unsigned > Indices)
static bool precededByAbortIntrinsic(const UnreachableInst &I, const SPIRVSubtarget &ST)
static FunctionType * getFunctionPointerElemType(Function *F, SPIRVGlobalRegistry *GR)
static bool isMultiRegisterAggregate(Value *V)
static void createSaturatedConversionDecoration(Instruction *I, IRBuilder<> &B)
static Type * parseDeclPtrElemType(StringRef TypeStr, LLVMContext &Ctx)
static bool shouldEmitIntrinsicsForGlobalValue(const GlobalVariableUsers &GVUsers, const GlobalVariable &GV, const Function *F)
static Type * restoreMutatedType(SPIRVGlobalRegistry *GR, Instruction *I, Type *Ty)
static bool requireAssignType(Instruction *I)
static void insertSpirvDecorations(MachineFunction &MF, SPIRVGlobalRegistry *GR, MachineIRBuilder MIB)
static void visit(BasicBlock &Start, std::function< bool(BasicBlock *)> op)
BaseType
A given derived pointer can have multiple base pointers through phi/selects.
static bool contains(SmallPtrSetImpl< ConstantExpr * > &Cache, ConstantExpr *Expr, Constant *C)
This file defines the SmallPtrSet class.
This file defines the SmallString class.
This file implements the StringSwitch template, which mimics a switch() statement whose cases are str...
static SymbolRef::Type getType(const Symbol *Sym)
LocallyHashedType DenseMapInfo< LocallyHashedType >::Empty
static int Lookup(ArrayRef< TableEntry > Table, unsigned Opcode)
static APInt getOneBitSet(unsigned numBits, unsigned BitNo)
Return an APInt with exactly one bit set in the result.
This class represents an incoming formal argument to a Function.
const Function * getParent() const
unsigned getArgNo() const
Return the index of this formal argument in its containing function.
Represent a constant reference to an array (0 or more elements consecutively in memory),...
static unsigned getPointerOperandIndex()
static unsigned getPointerOperandIndex()
@ UIncWrap
Increment one up to a maximum value.
@ UDecWrap
Decrement one until a minimum value or zero.
iterator_range< const_phi_iterator > phis() const
Returns a range that iterates over the phis in the basic block.
const Function * getParent() const
Return the enclosing method, or null if none.
static BasicBlock * Create(LLVMContext &Context, const Twine &Name="", Function *Parent=nullptr, BasicBlock *InsertBefore=nullptr)
Creates a new BasicBlock.
LLVM_ABI LLVMContext & getContext() const
Get the context in which this basic block lives.
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction; assumes that the block is well-formed.
static LLVM_ABI BlockAddress * get(Function *F, BasicBlock *BB)
Return a BlockAddress for the specified function and basic block.
bool isInlineAsm() const
Check if this call is an inline asm statement.
void setCallingConv(CallingConv::ID CC)
Function * getCalledFunction() const
Returns the function called, or null if this is an indirect function invocation or the function signa...
LLVM_ABI bool isIndirectCall() const
Return true if the callsite is an indirect call.
Value * getCalledOperand() const
Value * getArgOperand(unsigned i) const
void setArgOperand(unsigned i, Value *v)
FunctionType * getFunctionType() const
LLVM_ABI Intrinsic::ID getIntrinsicID() const
Returns the intrinsic ID of the intrinsic called or Intrinsic::not_intrinsic if the called function i...
iterator_range< User::op_iterator > args()
Iteration adapter for range-for loops.
unsigned arg_size() const
void setCalledFunction(Function *Fn)
Sets the function called, including updating the function type.
This class represents a function call, abstracting a target machine's calling convention.
static ConstantInt * getSigned(IntegerType *Ty, int64_t V, bool ImplicitTrunc=false)
Return a ConstantInt with the specified value for the specified type.
static LLVM_ABI ConstantPointerNull * get(PointerType *T)
Static factory methods - Return objects of the specified value.
static LLVM_ABI Constant * getNullValue(Type *Ty)
Constructor to create a '0' constant of arbitrary type.
LLVM_ABI std::optional< RoundingMode > getRoundingMode() const
uint64_t getNumOperands() const
unsigned getProgramAddressSpace() const
LLVM_ABI IntegerType * getIndexType(LLVMContext &C, unsigned AddressSpace) const
Returns the type of a GEP index in AddressSpace.
iterator find(const_arg_type_t< KeyT > Val)
ValueT lookup(const_arg_type_t< KeyT > Val) const
Return the entry for the specified key, or a default constructed value if no such entry exists.
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
std::pair< iterator, bool > try_emplace(KeyT &&Key, Ts &&...Args)
static ErrorSuccess success()
Create a success value.
static LLVM_ABI FixedVectorType * get(Type *ElementType, unsigned NumElts)
Type * getParamType(unsigned i) const
Parameter type accessors.
static LLVM_ABI FunctionType * get(Type *Result, ArrayRef< Type * > Params, bool isVarArg)
This static method is the primary way of constructing a FunctionType.
const DataLayout & getDataLayout() const
Get the data layout of the module this function belongs to.
bool isIntrinsic() const
isIntrinsic - Returns true if the function's name starts with "llvm.".
LLVMContext & getContext() const
getContext - Return a reference to the LLVMContext associated with this function.
Type * getReturnType() const
Returns the type of the ret val.
Argument * getArg(unsigned i) const
Represents flags for the getelementptr instruction/expression.
static GEPNoWrapFlags inBounds()
an instruction for type-safe pointer arithmetic to access elements of arrays and structs
static LLVM_ABI Type * getTypeAtIndex(Type *Ty, Value *Idx)
Return the type of the element at the given index of an indexable type.
static GetElementPtrInst * Create(Type *PointeeType, Value *Ptr, ArrayRef< Value * > IdxList, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
static unsigned getPointerOperandIndex()
LLVM_ABI bool isDeclaration() const
Return true if the primary definition of this global value is outside of the current translation unit...
Module * getParent()
Get the module that this global value is contained inside of...
PointerType * getType() const
Global values are always pointers.
@ InternalLinkage
Rename collisions when linking (static functions).
const Constant * getInitializer() const
getInitializer - Return the initializer for this global variable.
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
LLVM_ABI void addDestination(BasicBlock *Dest)
Add a destination.
static InsertElementInst * Create(Value *Vec, Value *NewElt, Value *Idx, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
static unsigned getInsertedValueOperandIndex()
static InsertValueInst * Create(Value *Agg, Value *Val, ArrayRef< unsigned > Idxs, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
Base class for instruction visitors.
LLVM_ABI const Module * getModule() const
Return the module owning the function this instruction belongs to or nullptr it the function does not...
LLVM_ABI InstListType::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
Instruction * user_back()
LLVM_ABI const Function * getFunction() const
Return the function this instruction belongs to.
LLVM_ABI void copyMetadata(const Instruction &SrcInst, ArrayRef< unsigned > WL=ArrayRef< unsigned >())
Copy metadata from SrcInst to this instruction.
This is an important class for using LLVM in a threaded context.
static unsigned getPointerOperandIndex()
SmallVector< LoopT *, 4 > getLoopsInPreorder() const
Return all of the loops in the function in preorder across the loop nests, with siblings in forward p...
void analyze(ParentT F)
Create the loop forest for a function.
const MDOperand & getOperand(unsigned I) const
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata * > MDs)
unsigned getNumOperands() const
Return number of MDNode operands.
static LLVM_ABI MDString * get(LLVMContext &Context, StringRef Str)
Flags
Flags values. These may be or'd together.
This class implements a map that also provides access to all stored values in a deterministic order.
iterator find(const KeyT &Key)
ModulePass class - This class is used to implement unstructured interprocedural optimizations and ana...
A Module instance is used to store all the information related to an LLVM module.
static LLVM_ABI PoisonValue * get(Type *T)
Static factory methods - Return an 'poison' object of the specified type.
static PreservedAnalyses none()
Convenience factory function for the empty preserved set.
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
PreservedAnalyses run(Module &M, ModuleAnalysisManager &AM)
void buildAssignType(IRBuilder<> &B, Type *Ty, Value *Arg, bool CanUseAnyVectorRank)
void addAssignPtrTypeInstr(Value *Val, CallInst *AssignPtrTyCI)
void buildAssignPtr(IRBuilder<> &B, Type *ElemTy, Value *Arg)
Type * findDeducedCompositeType(const Value *Val)
void replaceAllUsesWith(Value *Old, Value *New, bool DeleteOld=true)
void addDeducedElementType(Value *Val, Type *Ty)
void addReturnType(const Function *ArgF, TypedPointerType *DerivedTy)
Type * findMutated(const Value *Val)
void addDeducedCompositeType(Value *Val, Type *Ty)
void removeAssignPtrTypeInstr(Value *OldVal)
Type * findDeducedElementType(const Value *Val)
void updateAssignType(CallInst *AssignCI, Value *Arg, Value *OfType)
CallInst * findAssignPtrTypeInstr(const Value *Val)
const SPIRVTargetLowering * getTargetLowering() const override
bool isLogicalSPIRV() const
bool canUseExtension(SPIRV::Extension::Extension E) const
const SPIRVOptions & getCLOpts() const
const SPIRVSubtarget * getSubtargetImpl() const
bool erase(PtrType Ptr)
Remove pointer from the set.
iterator find(ConstPtrType Ptr) const
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
bool contains(ConstPtrType Ptr) const
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
void assign(size_type NumElts, ValueParamT Elt)
reference emplace_back(ArgTypes &&... Args)
iterator insert(iterator I, T &&Elt)
void push_back(const T &Elt)
LLVM_NO_SANITIZE_CFI_UNRELATED_CAST iterator begin()
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
An instruction for storing to memory.
static unsigned getPointerOperandIndex()
iterator find(StringRef Key)
Represent a constant reference to a string, i.e.
std::pair< StringRef, StringRef > split(char Separator) const
Split into two substrings around the first occurrence of a separator character.
bool consume_back(StringRef Suffix)
Returns true if this StringRef has the given suffix and removes that suffix.
bool starts_with(StringRef Prefix) const
Check if this string starts with the given Prefix.
constexpr bool empty() const
Check if the string is empty.
constexpr size_t size() const
Get the string size.
bool consume_front(char Prefix)
Returns true if this StringRef has the given prefix and removes that prefix.
StringRef drop_back(size_t N=1) const
Return a StringRef equal to 'this' but with the last N elements dropped.
A switch()-like statement whose cases are string literals.
static LLVM_ABI StructType * create(LLVMContext &Context, StringRef Name)
This creates an identified struct.
static unsigned getPointerOperandIndex()
static LLVM_ABI TargetExtType * get(LLVMContext &Context, StringRef Name, ArrayRef< Type * > Types={}, ArrayRef< unsigned > Ints={})
Return a target extension type having the specified name and optional type and integer parameters.
MachineMemOperand::Flags getLoadMemOperandFlags(const LoadInst &LI, const DataLayout &DL, AssumptionCache *AC=nullptr, const TargetLibraryInfo *LibInfo=nullptr, CodeGenOptLevel OptLevel=CodeGenOptLevel::Default) const
MachineMemOperand::Flags getStoreMemOperandFlags(const StoreInst &SI, const DataLayout &DL) const
const Triple & getTargetTriple() const
const STC & getSubtarget(const Function &F) const
This method returns a pointer to the specified type of TargetSubtargetInfo.
VendorType getVendor() const
Get the parsed vendor type of this triple.
The instances of the Type class are immutable: once they are created, they are never changed.
bool isVectorTy() const
True if this is an instance of VectorType.
bool isArrayTy() const
True if this is an instance of ArrayType.
static LLVM_ABI IntegerType * getInt32Ty(LLVMContext &C)
bool isPointerTy() const
True if this is an instance of PointerType.
Type * getArrayElementType() const
bool isSized() const
Return true if it makes sense to take the size of this type.
LLVM_ABI StringRef getTargetExtName() const
unsigned getScalarSizeInBits() const LLVM_READONLY
If this is a vector type, return the getPrimitiveSizeInBits value for the element type.
static LLVM_ABI IntegerType * getInt8Ty(LLVMContext &C)
Type * getScalarType() const
If this is a vector type, return the element type, otherwise return 'this'.
bool isStructTy() const
True if this is an instance of StructType.
bool isTargetExtTy() const
Return true if this is a target extension type.
bool isAggregateType() const
Return true if the type is an aggregate type.
LLVMContext & getContext() const
Return the LLVMContext in which this type was uniqued.
bool isIntegerTy() const
True if this is an instance of IntegerType.
static LLVM_ABI IntegerType * getIntNTy(LLVMContext &C, unsigned N)
static LLVM_ABI Type * getDoubleTy(LLVMContext &C)
Type * getContainedType(unsigned i) const
This method is used to implement the type iterator (defined at the end of the file).
static LLVM_ABI Type * getFloatTy(LLVMContext &C)
static LLVM_ABI Type * getHalfTy(LLVMContext &C)
bool isVoidTy() const
Return true if this is 'void'.
static LLVM_ABI bool isValidElementType(Type *ElemTy)
Return true if the specified type is valid as a element type.
static LLVM_ABI TypedPointerType * get(Type *ElementType, unsigned AddressSpace)
This constructs a pointer to an object of the specified type in a numbered address space.
static LLVM_ABI UndefValue * get(Type *T)
Static factory methods - Return an 'undef' object of the specified type.
This function has undefined behavior.
void setOperand(unsigned i, Value *Val)
LLVM_ABI bool replaceUsesOfWith(Value *From, Value *To)
Replace uses of one Value with another.
Value * getOperand(unsigned i) const
unsigned getNumOperands() const
LLVM Value Representation.
Type * getType() const
All values are typed, get the type of this value.
user_iterator user_begin()
LLVM_ABI void setName(const Twine &Name)
Change the name of the value.
LLVM_ABI void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
iterator_range< user_iterator > users()
void mutateType(Type *Ty)
Mutate the type of this Value to be of the specified type.
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
LLVM_ABI void takeName(Value *V)
Transfer the name from V to this value.
const ParentTy * getParent() const
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
constexpr char Args[]
Key for Kernel::Metadata::mArgs.
constexpr std::underlying_type_t< E > Mask()
Get a bitmask with 1s in all places up to the high-order bit of E's largest value.
@ SPIR_KERNEL
Used for SPIR kernel functions.
@ BasicBlock
Various leaf nodes.
LLVM_ABI Function * getOrInsertDeclaration(Module *M, ID id, ArrayRef< Type * > OverloadTys={})
Look up the Function declaration of the intrinsic id in the Module M.
bool match(Val *V, const Pattern &P)
auto m_Value()
Match an arbitrary value and ignore it.
auto m_AnyIntrinsic()
Matches any intrinsic call and ignore it.
is_zero< true > m_Zero()
Match any null constant or a vector with all elements equal to 0.
auto m_Intrinsic(const Ts &...Ops)
Match intrinsic calls like this: m_Intrinsic<Intrinsic::fabs>(m_Value(X))
std::string lookupBuiltinNameHelper(StringRef DemangledCall, FPDecorationId *DecorationId)
Parses the name part of the demangled builtin call.
@ CE
Windows NT (Windows on ARM)
initializer< Ty > init(const Ty &Val)
Scope
Defines the scope in which this symbol should be visible: Default – Visible in the public interface o...
@ User
could "use" a pointer
NodeAddr< PhiNode * > Phi
NodeAddr< NodeBase * > Node
NodeAddr< FuncNode * > Func
friend class Instruction
Iterator for Instructions in a `BasicBlock.
unsigned getNumElements(Type *Ty)
This is an optimization pass for GlobalISel generic memory operations.
auto drop_begin(T &&RangeOrContainer, size_t N=1)
Return a range covering RangeOrContainer with the first N elements excluded.
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly.
LLVM_ATTRIBUTE_ALWAYS_INLINE DynamicAPInt mod(const DynamicAPInt &LHS, const DynamicAPInt &RHS)
is always non-negative.
ModulePass * createSPIRVEmitIntrinsicsPass(const SPIRVTargetMachine &TM)
bool isTypedPointerWrapper(const TargetExtType *ExtTy)
RelativeUniformCounterPtr Values
uint32_t getMemSemanticsWithStorageClass(const Triple &TT, uint32_t OrderSem, uint32_t StorageClassSem)
auto enumerate(FirstRange &&First, RestRanges &&...Rest)
Given two or more input ranges, returns a new range whose values are tuples (A, B,...
unsigned getPointerAddressSpace(const Type *T)
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
auto successors(const MachineBasicBlock *BB)
constexpr T divideFloorSigned(U Numerator, V Denominator)
Returns the integer floor(Numerator / Denominator).
CallInst * buildIntrWithMD(Intrinsic::ID IntrID, ArrayRef< Type * > Types, Value *Arg, Value *Arg2, ArrayRef< Constant * > Imms, IRBuilder<> &B)
bool isUntypedPointerVectorTy(const Type *T)
void append_range(Container &C, Range &&R)
Wrapper function to append range R to container C.
iterator_range< early_inc_iterator_impl< detail::IterOfRange< RangeT > > > make_early_inc_range(RangeT &&Range)
Make a range that does early increment to allow mutation of the underlying range without disrupting i...
bool sortBlocks(Function &F)
bool isa_and_nonnull(const Y &Val)
SPIRV::Scope::Scope getMemScope(const Triple &TT, LLVMContext &Ctx, SyncScope::ID Id)
Error createStringError(std::error_code EC, char const *Fmt, const Ts &... Vals)
Create formatted StringError object.
SPIRV::MemorySemantics::MemorySemantics getMemSemanticsForStorageClass(SPIRV::StorageClass::StorageClass SC)
constexpr unsigned storageClassToAddressSpace(SPIRV::StorageClass::StorageClass SC)
bool isNestedPointer(const Type *Ty)
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Value
Function * getOrCreateBackendServiceFunction(Module &M)
MetadataAsValue * buildMD(Value *Arg)
std::string getOclOrSpirvBuiltinDemangledName(StringRef Name)
LLVM_ABI bool convertUsersOfConstantsToInstructions(ArrayRef< Constant * > Consts, Function *RestrictToFunc=nullptr, bool RemoveDeadConstants=true, bool IncludeSelf=false)
Replace constant expressions users of the given constants with instructions.
SmallVector< unsigned, 1 > getSpirvLoopControlOperandsFromLoopMetadata(MDNode *LoopMD)
Type * normalizeType(Type *Ty, bool CanUseAnyVectorRank)
auto reverse(ContainerTy &&C)
Type * getTypedPointerWrapper(Type *ElemTy, unsigned AS)
Error joinErrors(Error E1, Error E2)
Concatenate errors.
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
bool isPointerTy(const Type *T)
bool none_of(R &&Range, UnaryPredicate P)
Provide wrappers to std::none_of which take ranges instead of having to pass begin/end explicitly.
IRBuilder(LLVMContext &, FolderTy, InserterTy) -> IRBuilder< FolderTy, InserterTy >
LLVM_ABI void report_fatal_error(Error Err, bool gen_crash_diag=true)
bool set_union(S1Ty &S1, const S2Ty &S2)
set_union(A, B) - Compute A := A u B, return whether A changed.
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
SPIRV::StorageClass::StorageClass addressSpaceToStorageClass(unsigned AddrSpace, const SPIRVSubtarget &STI)
@ Ref
The access may reference the value stored in memory.
@ And
Bitwise or logical AND of integers.
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Count
LLVM_ABI Value * findScalarElement(Value *V, unsigned EltNo)
Given a vector and an element number, see if the scalar value is already around as a register,...
auto count(R &&Range, const E &Element)
Wrapper function around std::count to count the number of times an element Element occurs in the give...
bool isLongVectorEXT(const Type *Ty, bool CanUseVector16=true)
Type * parseBasicTypeName(StringRef &TypeName, LLVMContext &Ctx)
DWARFExpression::Operation Op
Type * getPointeeTypeByAttr(Argument *Arg)
std::string toString(const APInt &I, unsigned Radix, bool Signed, bool formatAsCLiteral=false, bool UpperCase=true, bool InsertSeparators=false)
bool hasPointeeTypeAttr(Argument *Arg)
LLVM_ABI bool RecursivelyDeleteTriviallyDeadInstructionsPermissive(SmallVectorImpl< WeakTrackingVH > &DeadInsts, const TargetLibraryInfo *TLI=nullptr, MemorySSAUpdater *MSSAU=nullptr, std::function< void(Value *)> AboutToDeleteCallback=std::function< void(Value *)>())
Same functionality as RecursivelyDeleteTriviallyDeadInstructions, but allow instructions that are not...
constexpr unsigned BitWidth
bool isEquivalentTypes(Type *Ty1, Type *Ty2)
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
iterator_range< pointer_iterator< WrappedIteratorT > > make_pointer_range(RangeT &&Range)
bool hasInitializer(const GlobalVariable *GV)
bool isPointerTyOrWrapper(const Type *Ty)
@ Enabled
Convert any .debug_str_offsets tables to DWARF64 if needed.
bool isSpvIntrinsic(const MachineInstr &MI, Intrinsic::ID IntrinsicID)
PoisonValue * getNormalizedPoisonValue(Type *Ty, bool CanUseAnyVectorRank)
bool isUntypedPointerTy(const Type *T)
Type * reconstitutePeeledArrayType(Type *Ty)
bool spirvPreserveAuxData(const SPIRVOptions &CLOpts, const Triple &TT)
SPIRV::MemorySemantics::MemorySemantics getMemSemantics(AtomicOrdering Ord)
AnalysisManager< Module > ModuleAnalysisManager
Convenience typedef for the Module analysis manager.
static size_t computeFPFastMathDefaultInfoVecIndex(size_t BitWidth)