LLVM 24.0.0git
SPIRVLegalizePointerCast.cpp
Go to the documentation of this file.
1//===-- SPIRVLegalizePointerCast.cpp ----------------------*- C++ -*-===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// The LLVM IR has multiple legal patterns we cannot lower to Logical SPIR-V.
10// This pass modifies such loads to have an IR we can directly lower to valid
11// logical SPIR-V.
12// OpenCL can avoid this because they rely on ptrcast, which is not supported
13// by logical SPIR-V.
14//
15// This pass relies on the assign_ptr_type intrinsic to deduce the type of the
16// pointed values, must replace all occurences of `ptrcast`. This is why
17// unhandled cases are reported as unreachable: we MUST cover all cases.
18//
19// 1. Loading the first element of an array
20//
21// %array = [10 x i32]
22// %value = load i32, ptr %array
23//
24// LLVM can skip the GEP instruction, and only request loading the first 4
25// bytes. In logical SPIR-V, we need an OpAccessChain to access the first
26// element. This pass will add a getelementptr instruction before the load.
27//
28//
29// 2. Implicit downcast from load
30//
31// %1 = getelementptr <4 x i32>, ptr %vec4, i64 0
32// %2 = load <3 x i32>, ptr %1
33//
34// The pointer in the GEP instruction is only used for offset computations,
35// but it doesn't NEED to match the pointed type. OpAccessChain however
36// requires this. Also, LLVM loads define the bitwidth of the load, not the
37// pointer. In this example, we can guess %vec4 is a vec4 thanks to the GEP
38// instruction basetype, but we only want to load the first 3 elements, hence
39// do a partial load. In logical SPIR-V, this is not legal. What we must do
40// is load the full vector (basetype), extract 3 elements, and recombine them
41// to form a 3-element vector.
42//
43//===----------------------------------------------------------------------===//
44
45#include "SPIRV.h"
46#include "SPIRVSubtarget.h"
47#include "SPIRVTargetMachine.h"
48#include "SPIRVUtils.h"
49#include "llvm/IR/IRBuilder.h"
51#include "llvm/IR/Intrinsics.h"
52#include "llvm/IR/IntrinsicsSPIRV.h"
55
56using namespace llvm;
57
58namespace {
59class SPIRVLegalizePointerCastImpl {
60
61 // Builds the `spv_assign_type` assigning |Ty| to |Value| at the current
62 // builder position.
63 void buildAssignType(IRBuilder<> &B, Type *Ty, Value *Arg) {
64 Value *OfType = PoisonValue::get(Ty);
65 CallInst *AssignCI = buildIntrWithMD(Intrinsic::spv_assign_type,
66 {Arg->getType()}, OfType, Arg, {}, B);
67 GR->addAssignPtrTypeInstr(Arg, AssignCI);
68 }
69
70 static FixedVectorType *makeVectorFromTotalBits(Type *ElemTy,
71 TypeSize TotalBits) {
72 unsigned ElemBits = ElemTy->getScalarSizeInBits();
73 assert(ElemBits && TotalBits % ElemBits == 0 &&
74 "TotalBits must be divisible by element bit size");
75 return FixedVectorType::get(ElemTy, TotalBits / ElemBits);
76 }
77
78 Value *resizeVectorBitsWithShuffle(IRBuilder<> &B, Value *V,
79 FixedVectorType *DstTy) {
80 auto *SrcTy = cast<FixedVectorType>(V->getType());
81 assert(SrcTy->getElementType() == DstTy->getElementType() &&
82 "shuffle resize expects identical element types");
83
84 const unsigned NumNeeded = DstTy->getNumElements();
85 const unsigned NumSource = SrcTy->getNumElements();
86
87 SmallVector<int> Mask(NumNeeded);
88 for (unsigned I = 0; I < NumNeeded; ++I)
89 Mask[I] = (I < NumSource) ? static_cast<int>(I) : -1;
90
91 Value *Resized = B.CreateShuffleVector(V, V, Mask);
92 buildAssignType(B, DstTy, Resized);
93 return Resized;
94 }
95
96 // Loads parts of the vector of type |SourceType| from the pointer |Source|
97 // and create a new vector of type |TargetType|. |TargetType| must be a vector
98 // type.
99 // Returns the loaded value.
100 Value *loadVectorFromVector(IRBuilder<> &B, FixedVectorType *SourceType,
101 FixedVectorType *TargetType, Value *Source,
102 Align OriginalAlign) {
103 LoadInst *NewLoad = B.CreateLoad(SourceType, Source);
104 NewLoad->setAlignment(OriginalAlign);
105 buildAssignType(B, SourceType, NewLoad);
106 Value *AssignValue = NewLoad;
107 if (TargetType->getElementType() != SourceType->getElementType()) {
108 const DataLayout &DL = B.GetInsertBlock()->getModule()->getDataLayout();
109 TypeSize TargetTypeSize = DL.getTypeSizeInBits(TargetType);
110 TypeSize SourceTypeSize = DL.getTypeSizeInBits(SourceType);
111
112 Value *BitcastSrcVal = NewLoad;
113 FixedVectorType *BitcastSrcTy =
114 cast<FixedVectorType>(BitcastSrcVal->getType());
115 FixedVectorType *BitcastDstTy = TargetType;
116
117 if (TargetTypeSize != SourceTypeSize) {
118 unsigned TargetElemBits =
119 TargetType->getElementType()->getScalarSizeInBits();
120 if (SourceTypeSize % TargetElemBits == 0) {
121 // No Resize needed. Same total bits as source, but use target element
122 // type.
123 BitcastDstTy = makeVectorFromTotalBits(TargetType->getElementType(),
124 SourceTypeSize);
125 } else {
126 // Resize source to target total bitwidth using source element type.
127 BitcastSrcTy = makeVectorFromTotalBits(SourceType->getElementType(),
128 TargetTypeSize);
129 BitcastSrcVal = resizeVectorBitsWithShuffle(B, NewLoad, BitcastSrcTy);
130 }
131 }
132 AssignValue =
133 B.CreateIntrinsic(Intrinsic::spv_bitcast,
134 {BitcastDstTy, BitcastSrcTy}, {BitcastSrcVal});
135 buildAssignType(B, BitcastDstTy, AssignValue);
136 if (BitcastDstTy == TargetType)
137 return AssignValue;
138 }
139
140 auto *AssignVecTy = cast<FixedVectorType>(AssignValue->getType());
141 const unsigned NumTarget = TargetType->getNumElements();
142 const unsigned NumSource = AssignVecTy->getNumElements();
143
144 // Optimizations may widen a narrow load to cover padding (e.g., loading a
145 // <1 x float> column as <4 x float>). Since extra lanes read trailing
146 // padding, insert only the valid lanes into a poison vector to avoid poison
147 // scalars.
148 if (NumTarget > NumSource) {
149 Value *Result = PoisonValue::get(TargetType);
150 buildAssignType(B, TargetType, Result);
151 for (unsigned I = 0; I < NumSource; ++I) {
152 Value *Scalar = extractScalarFromVector(B, AssignValue, I);
153 Result = makeInsertElement(B, Result, Scalar, I);
154 }
155 return Result;
156 }
157
158 assert(NumTarget < NumSource);
159 SmallVector<int> Mask(/* Size= */ NumTarget);
160 for (unsigned I = 0; I < NumTarget; ++I)
161 Mask[I] = I;
162 Value *Output = B.CreateShuffleVector(AssignValue, AssignValue, Mask);
163 buildAssignType(B, TargetType, Output);
164 return Output;
165 }
166
167 // Returns true if |FromTy| has a memory layout compatible with loading or
168 // storing |ToTy|.
169 bool isCompatibleMemoryLayout(Type *ToTy, Type *FromTy) {
170 if (ToTy == FromTy)
171 return true;
172 auto *SVT = dyn_cast<FixedVectorType>(FromTy);
173 auto *DVT = dyn_cast<FixedVectorType>(ToTy);
174 if (SVT && DVT)
175 return true;
176 auto *SAT = dyn_cast<ArrayType>(FromTy);
177 if (SAT && DVT) {
178 if (SAT->getElementType() == DVT->getElementType())
179 return true;
180 if (auto *MAT = dyn_cast<FixedVectorType>(SAT->getElementType()))
181 if (MAT->getElementType() == DVT->getElementType())
182 return true;
183 }
184 return false;
185 }
186
187 // Traverses the aggregate type to find the first sub-type that matches
188 // the TargetElemType's memory layout, optionally emitting a GEP intrinsic.
189 std::optional<std::pair<Value *, Type *>>
190 getPointerToFirstCompatibleType(IRBuilder<> &B, Value *BasePtr,
191 Type *PointerType, Type *TargetElemType,
192 bool IsInBounds) {
193 Type *CurrentTy = GR->findDeducedElementType(BasePtr);
194 assert(CurrentTy && "Could not deduce aggregate type");
195 SmallVector<Value *, 8> Args{/* isInBounds= */ B.getInt1(IsInBounds),
196 BasePtr};
197 Args.push_back(B.getInt32(0)); // Pointer offset
198
199 while (!isCompatibleMemoryLayout(TargetElemType, CurrentTy)) {
200 if (auto *ST = dyn_cast<StructType>(CurrentTy)) {
201 if (ST->getNumElements() == 0)
202 return std::nullopt;
203 CurrentTy = ST->getTypeAtIndex(0u);
204 } else if (auto *AT = dyn_cast<ArrayType>(CurrentTy)) {
205 CurrentTy = AT->getElementType();
206 } else if (auto *VT = dyn_cast<FixedVectorType>(CurrentTy)) {
207 CurrentTy = VT->getElementType();
208 } else {
209 return std::nullopt;
210 }
211 Args.push_back(B.getInt32(0));
212 }
213
214 Value *GEP = BasePtr;
215 if (Args.size() > 3) {
216 std::array<Type *, 2> Types = {PointerType, BasePtr->getType()};
217 GEP = B.CreateIntrinsic(Intrinsic::spv_gep, {Types}, {Args});
218 GR->buildAssignPtr(B, CurrentTy, GEP);
219 }
220
221 return std::make_pair(GEP, CurrentTy);
222 }
223
224 static IntrinsicInst *getResourceGetPointer(Value *Ptr) {
225 if (auto *II = dyn_cast<IntrinsicInst>(Ptr))
226 if (II->getIntrinsicID() == Intrinsic::spv_resource_getpointer)
227 return II;
228 return nullptr;
229 }
230
231 Value *gepByteOffset(IRBuilder<> &B, Value *BasePtr, unsigned ByteOffset) {
232 if (ByteOffset == 0)
233 return BasePtr;
234
235 if (IntrinsicInst *ResourcePtr = getResourceGetPointer(BasePtr)) {
236 Value *Handle = ResourcePtr->getOperand(0);
237 Value *BaseOffset = ResourcePtr->getOperand(1);
238 Value *NewOffset;
239 if (auto *CI = dyn_cast<ConstantInt>(BaseOffset))
240 NewOffset =
241 ConstantInt::get(CI->getType(), CI->getZExtValue() + ByteOffset);
242 else
243 NewOffset = B.CreateAdd(
244 BaseOffset, ConstantInt::get(BaseOffset->getType(), ByteOffset));
246 ResourcePtr->getOperandBundlesAsDefs(OpBundles);
247 CallInst *ResourcePtrAtOffset = B.CreateCall(
248 ResourcePtr->getFunctionType(), ResourcePtr->getCalledOperand(),
249 {Handle, NewOffset}, OpBundles);
250 ResourcePtrAtOffset->setAttributes(ResourcePtr->getAttributes());
251 ResourcePtrAtOffset->setCallingConv(ResourcePtr->getCallingConv());
252 Type *I8Ty = Type::getInt8Ty(B.getContext());
253 GR->buildAssignPtr(B, I8Ty, ResourcePtrAtOffset);
254 return ResourcePtrAtOffset;
255 }
257 "byte layout pointer must come from spv.resource.getpointer");
258 }
259
260 Value *scalarToStoreInt(IRBuilder<> &B, Value *Scalar) {
261 Type *Ty = Scalar->getType();
262 const DataLayout &DL = B.GetInsertBlock()->getModule()->getDataLayout();
263 Type *IntTy =
264 IntegerType::get(B.getContext(), DL.getTypeStoreSizeInBits(Ty));
265 if (Ty == IntTy)
266 return Scalar;
267 if (Ty->isIntOrIntVectorTy())
268 return B.CreateIntCast(Scalar, IntTy, /*isSigned=*/false);
269 return B.CreateBitCast(Scalar, IntTy);
270 }
271
272 Value *storeIntToScalar(IRBuilder<> &B, Value *IntVal, Type *ScalarTy) {
273 if (IntVal->getType() == ScalarTy)
274 return IntVal;
275 if (ScalarTy->isIntOrIntVectorTy())
276 return B.CreateIntCast(IntVal, ScalarTy, /*isSigned=*/false);
277 return B.CreateBitCast(IntVal, ScalarTy);
278 }
279
280 void storeScalarToByteLayout(IRBuilder<> &B, Value *Src, Value *Dst,
281 Align Alignment) {
282 LLVMContext &Ctx = B.getContext();
283 Type *I8Ty = Type::getInt8Ty(Ctx);
284 const DataLayout &DL = B.GetInsertBlock()->getModule()->getDataLayout();
285 Value *IntVal = scalarToStoreInt(B, Src);
286 unsigned NumBytes = DL.getTypeStoreSize(Src->getType());
287
288 auto StoreByte = [&](unsigned I, Value *Shifted) {
289 Value *Byte = B.CreateTrunc(Shifted, I8Ty);
290 buildAssignType(B, I8Ty, Byte);
291 Value *Ptr = gepByteOffset(B, Dst, I);
292 StoreInst *SI = B.CreateStore(Byte, Ptr);
293 SI->setAlignment(commonAlignment(Alignment, I));
294 };
295
296 if (NumBytes > 0)
297 StoreByte(0, IntVal);
298
299 for (unsigned I = 1; I < NumBytes; ++I) {
300 Value *Shifted =
301 B.CreateLShr(IntVal, ConstantInt::get(IntVal->getType(), 8 * I));
302 StoreByte(I, Shifted);
303 }
304 }
305
306 Value *loadScalarFromByteLayout(IRBuilder<> &B, Type *AccessTy, Value *Src,
307 Align Alignment) {
308 LLVMContext &Ctx = B.getContext();
309 Type *I8Ty = Type::getInt8Ty(Ctx);
310 const DataLayout &DL = B.GetInsertBlock()->getModule()->getDataLayout();
311 unsigned NumBytes = DL.getTypeStoreSize(AccessTy);
312 Type *IntTy = IntegerType::get(Ctx, DL.getTypeStoreSizeInBits(AccessTy));
313 Value *IntVal = ConstantInt::get(IntTy, 0);
314
315 for (unsigned I = 0; I < NumBytes; ++I) {
316 Value *Ptr = gepByteOffset(B, Src, I);
317 LoadInst *LI = B.CreateLoad(I8Ty, Ptr);
318 LI->setAlignment(commonAlignment(Alignment, I));
319 buildAssignType(B, I8Ty, LI);
320 Value *Extended = B.CreateZExt(LI, IntTy);
321 buildAssignType(B, IntTy, Extended);
322
323 if (I == 0) {
325 } else {
326 Value *Shifted = B.CreateShl(Extended, ConstantInt::get(IntTy, 8 * I));
327 buildAssignType(B, IntTy, Shifted);
328 IntVal = B.CreateOr(IntVal, Shifted);
329 }
330 buildAssignType(B, IntTy, IntVal);
331 }
332
333 Value *Result = storeIntToScalar(B, IntVal, AccessTy);
334 if (Result != IntVal)
335 buildAssignType(B, AccessTy, Result);
336 return Result;
337 }
338
339 // Classifies a ptrcast reinterpretation: casted pointee matches the access
340 // type but differs from the original storage layout (e.g. i8 byte buffer as
341 // i32). ByteWise means multi-byte access must use per-byte i8 load/store.
342 bool shouldReinterpretByteWise(IRBuilder<> &B, Type *AccessTy,
343 Value *OriginalPtr) {
344 Type *OriginalElemTy = GR->findDeducedElementType(OriginalPtr);
345 const DataLayout &DL = B.GetInsertBlock()->getModule()->getDataLayout();
346 if (OriginalElemTy && OriginalElemTy == Type::getInt8Ty(B.getContext()) &&
347 AccessTy->isSingleValueType() && DL.getTypeStoreSize(AccessTy) > 1)
348 return true;
349
350 return false;
351 }
352
353 bool tryReinterpretLoad(IRBuilder<> &B, Type *AccessTy, Value *OriginalPtr,
354 Value *CastedPtr, LoadInst *IllegalLoad) {
355 Type *CastedElemTy = GR->findDeducedElementType(CastedPtr);
356 if (!CastedElemTy || CastedElemTy != AccessTy)
357 return false;
358
359 Align Alignment = IllegalLoad->getAlign();
360 if (shouldReinterpretByteWise(B, AccessTy, OriginalPtr)) {
361 const DataLayout &DL = B.GetInsertBlock()->getModule()->getDataLayout();
362 Value *Loaded;
363 if (auto *VT = dyn_cast<FixedVectorType>(AccessTy)) {
364 unsigned ElemSize = DL.getTypeStoreSize(VT->getElementType());
365 SmallVector<Value *, 4> LoadedElements;
366 for (unsigned I = 0; I < VT->getNumElements(); ++I) {
367 Value *ElemPtr = gepByteOffset(B, OriginalPtr, I * ElemSize);
368 LoadedElements.push_back(loadScalarFromByteLayout(
369 B, VT->getElementType(), ElemPtr,
370 commonAlignment(Alignment, I * ElemSize)));
371 }
372 Loaded = buildVectorFromLoadedElements(B, VT, LoadedElements);
373 } else {
374 Loaded = loadScalarFromByteLayout(B, AccessTy, OriginalPtr, Alignment);
375 buildAssignType(B, AccessTy, Loaded);
376 }
377 GR->replaceAllUsesWith(IllegalLoad, Loaded, /* DeleteOld= */ true);
378 DeadInstructions.push_back(IllegalLoad);
379 return true;
380 }
381
382 GR->buildAssignPtr(B, AccessTy, OriginalPtr);
383 LoadInst *LI = B.CreateLoad(AccessTy, OriginalPtr);
384 LI->setAlignment(Alignment);
385 buildAssignType(B, AccessTy, LI);
386 GR->replaceAllUsesWith(IllegalLoad, LI, /* DeleteOld= */ true);
387 DeadInstructions.push_back(IllegalLoad);
388 return true;
389 }
390
391 bool tryReinterpretStore(IRBuilder<> &B, Type *AccessTy, Value *OriginalPtr,
392 Value *CastedPtr, Value *StoreSrc, Align Alignment) {
393 Type *CastedElemTy = GR->findDeducedElementType(CastedPtr);
394 if (!CastedElemTy || CastedElemTy != AccessTy)
395 return false;
396
397 if (shouldReinterpretByteWise(B, AccessTy, OriginalPtr)) {
398 const DataLayout &DL = B.GetInsertBlock()->getModule()->getDataLayout();
399 if (auto *VT = dyn_cast<FixedVectorType>(StoreSrc->getType())) {
400 unsigned ElemSize = DL.getTypeStoreSize(VT->getElementType());
401 for (unsigned I = 0; I < VT->getNumElements(); ++I) {
402 Value *Elem = extractScalarFromVector(B, StoreSrc, I);
403 Value *ElemPtr = gepByteOffset(B, OriginalPtr, I * ElemSize);
404 storeScalarToByteLayout(B, Elem, ElemPtr,
405 commonAlignment(Alignment, I * ElemSize));
406 }
407 } else {
408 storeScalarToByteLayout(B, StoreSrc, OriginalPtr, Alignment);
409 }
410 return true;
411 }
412
413 GR->buildAssignPtr(B, AccessTy, OriginalPtr);
414 StoreInst *SI = B.CreateStore(StoreSrc, OriginalPtr);
415 SI->setAlignment(Alignment);
416 return true;
417 }
418
419 // Builds a legalized load from a pointer, drilling down through
420 // memory layouts to find a compatible type. Load flags will be
421 // copied from |IllegalLoad|, which should be the load being legalized.
422 Value *buildLegalizedLoad(IRBuilder<> &B, Type *ElementType, Value *Source,
423 LoadInst *IllegalLoad, Value *CastedPtr) {
424 auto ResultOpt = getPointerToFirstCompatibleType(
425 B, Source, IllegalLoad->getPointerOperandType(), ElementType, false);
426 if (!ResultOpt) {
427 if (tryReinterpretLoad(B, ElementType, Source, CastedPtr, IllegalLoad))
428 return nullptr;
429 llvm_unreachable("Failed to load from aggregate: "
430 "Could not find compatible memory layout.");
431 }
432 auto [GEP, CurrentTy] = *ResultOpt;
433
434 auto *SAT = dyn_cast<ArrayType>(CurrentTy);
435 auto *SVT = dyn_cast<FixedVectorType>(CurrentTy);
436 auto *DVT = dyn_cast<FixedVectorType>(ElementType);
437 auto *MAT =
438 SAT ? dyn_cast<FixedVectorType>(SAT->getElementType()) : nullptr;
439
440 if (ElementType == CurrentTy) {
441 LoadInst *LI = B.CreateLoad(ElementType, GEP);
442 LI->setAlignment(IllegalLoad->getAlign());
443 buildAssignType(B, ElementType, LI);
444 return LI;
445 }
446 if (SVT && DVT)
447 return loadVectorFromVector(B, SVT, DVT, GEP, IllegalLoad->getAlign());
448 if (SAT && DVT && SAT->getElementType() == DVT->getElementType())
449 return loadVectorFromArray(B, DVT, GEP, IllegalLoad->getAlign());
450 if (MAT && DVT && MAT->getElementType() == DVT->getElementType())
451 return loadVectorFromMatrixArray(B, DVT, GEP, MAT,
452 IllegalLoad->getAlign());
453
454 llvm_unreachable("Failed to load from aggregate.");
455 }
456
457 Value *
458 buildVectorFromLoadedElements(IRBuilder<> &B, FixedVectorType *TargetType,
459 SmallVector<Value *, 4> &LoadedElements) {
460 // <1 x T> shares the SPIR-V type with T, so emitting OpCompositeInsert on
461 // a scalar would be invalid. Bridge with spv_bitcast instead.
462 if (TargetType->getNumElements() == 1) {
463 Value *Scalar = LoadedElements[0];
464 Value *NewVector = B.CreateIntrinsic(
465 Intrinsic::spv_bitcast, {TargetType, Scalar->getType()}, {Scalar});
466 buildAssignType(B, TargetType, NewVector);
467 return NewVector;
468 }
469
470 // Build the vector from the loaded elements.
471 Value *NewVector = PoisonValue::get(TargetType);
472 buildAssignType(B, TargetType, NewVector);
473
474 for (unsigned I = 0, E = TargetType->getNumElements(); I < E; ++I) {
475 Value *Index = B.getInt32(I);
477 TargetType->getElementType(),
478 Index->getType()};
479 SmallVector<Value *> Args = {NewVector, LoadedElements[I], Index};
480 NewVector = B.CreateIntrinsic(Intrinsic::spv_insertelt, {Types}, {Args});
481 buildAssignType(B, TargetType, NewVector);
482 }
483 return NewVector;
484 }
485
486 // Loads elements from a matrix with an array of vector memory layout and
487 // constructs a vector.
488 Value *loadVectorFromMatrixArray(IRBuilder<> &B, FixedVectorType *TargetType,
489 Value *Source, FixedVectorType *ArrElemVecTy,
490 Align OriginalAlign) {
491 Type *TargetElemTy = TargetType->getElementType();
492 unsigned ScalarsPerArrayElement = ArrElemVecTy->getNumElements();
493 const DataLayout &DL = B.GetInsertBlock()->getModule()->getDataLayout();
494 uint64_t ArrElemVecSize = DL.getTypeAllocSize(ArrElemVecTy);
495 // Load each element of the array.
496 SmallVector<Value *, 4> LoadedElements;
497 std::array<Type *, 2> Types = {Source->getType(), Source->getType()};
498 for (unsigned I = 0, E = TargetType->getNumElements(); I < E; ++I) {
499 unsigned ArrayIndex = I / ScalarsPerArrayElement;
500 unsigned ElementIndexInArrayElem = I % ScalarsPerArrayElement;
501 // Create a GEP to access the i-th element of the array.
502 std::array<Value *, 4> Args = {
503 B.getInt1(/*Inbounds=*/false), Source, B.getInt32(0),
504 ConstantInt::get(B.getInt32Ty(), ArrayIndex)};
505 auto *ElementPtr = B.CreateIntrinsic(Intrinsic::spv_gep, {Types}, {Args});
506 GR->buildAssignPtr(B, ArrElemVecTy, ElementPtr);
507 LoadInst *LoadVec = B.CreateLoad(ArrElemVecTy, ElementPtr);
508 LoadVec->setAlignment(
509 commonAlignment(OriginalAlign, ArrayIndex * ArrElemVecSize));
510 buildAssignType(B, ArrElemVecTy, LoadVec);
511 LoadedElements.push_back(makeExtractElement(B, TargetElemTy, LoadVec,
512 ElementIndexInArrayElem));
513 }
514 return buildVectorFromLoadedElements(B, TargetType, LoadedElements);
515 }
516
517 // Loads elements from an array and constructs a vector.
518 Value *loadVectorFromArray(IRBuilder<> &B, FixedVectorType *TargetType,
519 Value *Source, Align OriginalAlign) {
520 // Load each element of the array.
521 SmallVector<Value *, 4> LoadedElements;
522 std::array<Type *, 2> Types = {Source->getType(), Source->getType()};
523 const DataLayout &DL = B.GetInsertBlock()->getModule()->getDataLayout();
524 uint64_t ElemSize = DL.getTypeAllocSize(TargetType->getElementType());
525 for (unsigned I = 0, E = TargetType->getNumElements(); I < E; ++I) {
526 // Create a GEP to access the i-th element of the array.
527 std::array<Value *, 4> Args = {B.getInt1(/*Inbounds=*/false), Source,
528 B.getInt32(0),
529 ConstantInt::get(B.getInt32Ty(), I)};
530 auto *ElementPtr = B.CreateIntrinsic(Intrinsic::spv_gep, {Types}, {Args});
531 GR->buildAssignPtr(B, TargetType->getElementType(), ElementPtr);
532
533 // Load the value from the element pointer.
534 LoadInst *Load = B.CreateLoad(TargetType->getElementType(), ElementPtr);
535 Load->setAlignment(commonAlignment(OriginalAlign, I * ElemSize));
536 buildAssignType(B, TargetType->getElementType(), Load);
537 LoadedElements.push_back(Load);
538 }
539 return buildVectorFromLoadedElements(B, TargetType, LoadedElements);
540 }
541
542 // Stores elements from a vector into a matrix (an array of vectors).
543 void storeMatrixArrayFromVector(IRBuilder<> &B, Value *SrcVector,
544 Value *DstArrayPtr, ArrayType *ArrTy,
545 Align Alignment) {
546 auto *SrcVecTy = cast<FixedVectorType>(SrcVector->getType());
547 auto *ArrElemVecTy = cast<FixedVectorType>(ArrTy->getElementType());
548 Type *ElemTy = ArrElemVecTy->getElementType();
549 unsigned ScalarsPerArrayElement = ArrElemVecTy->getNumElements();
550 unsigned SrcNumElements = SrcVecTy->getNumElements();
551 assert(
552 SrcNumElements % ScalarsPerArrayElement == 0 &&
553 "Source vector size must be a multiple of array element vector size");
554
555 std::array<Type *, 2> Types = {DstArrayPtr->getType(),
556 DstArrayPtr->getType()};
557 const DataLayout &DL = B.GetInsertBlock()->getModule()->getDataLayout();
558 uint64_t ArrElemVecSize = DL.getTypeAllocSize(ArrElemVecTy);
559
560 for (unsigned I = 0; I < SrcNumElements; I += ScalarsPerArrayElement) {
561 unsigned ArrayIndex = I / ScalarsPerArrayElement;
562 // Create a GEP to access the array element.
563 std::array<Value *, 4> Args = {
564 B.getInt1(/*Inbounds=*/false), DstArrayPtr, B.getInt32(0),
565 ConstantInt::get(B.getInt32Ty(), ArrayIndex)};
566 auto *ElementPtr = B.CreateIntrinsic(Intrinsic::spv_gep, {Types}, {Args});
567 GR->buildAssignPtr(B, ArrElemVecTy, ElementPtr);
568
569 // Extract scalar elements from the source vector for this array slot.
570 SmallVector<Value *, 4> Elements;
571 for (unsigned J = 0; J < ScalarsPerArrayElement; ++J)
572 Elements.push_back(makeExtractElement(B, ElemTy, SrcVector, I + J));
573
574 // Build a vector from the extracted elements and store it.
575 Value *Vec = buildVectorFromLoadedElements(B, ArrElemVecTy, Elements);
576 StoreInst *SI = B.CreateStore(Vec, ElementPtr);
577 SI->setAlignment(commonAlignment(Alignment, ArrayIndex * ArrElemVecSize));
578 }
579 }
580
581 // Stores elements from a vector into an array.
582 void storeArrayFromVector(IRBuilder<> &B, Value *SrcVector,
583 Value *DstArrayPtr, ArrayType *ArrTy,
584 Align Alignment) {
585 auto *VecTy = cast<FixedVectorType>(SrcVector->getType());
586 Type *ElemTy = ArrTy->getElementType();
587
588 // Ensure the element types of the array and vector are the same.
589 assert(VecTy->getElementType() == ElemTy &&
590 "Element types of array and vector must be the same.");
591 std::array<Type *, 2> Types = {DstArrayPtr->getType(),
592 DstArrayPtr->getType()};
593 const DataLayout &DL = B.GetInsertBlock()->getModule()->getDataLayout();
594 uint64_t ElemSize = DL.getTypeAllocSize(ElemTy);
595
596 for (unsigned I = 0, E = VecTy->getNumElements(); I < E; ++I) {
597 // Create a GEP to access the i-th element of the array.
598 std::array<Value *, 4> Args = {B.getInt1(/*Inbounds=*/false), DstArrayPtr,
599 B.getInt32(0),
600 ConstantInt::get(B.getInt32Ty(), I)};
601 auto *ElementPtr = B.CreateIntrinsic(Intrinsic::spv_gep, {Types}, {Args});
602 GR->buildAssignPtr(B, ElemTy, ElementPtr);
603
604 // Extract the element from the vector and store it.
605 Value *Element =
606 E == 1 ? SrcVector : makeExtractElement(B, ElemTy, SrcVector, I);
607 StoreInst *SI = B.CreateStore(Element, ElementPtr);
608 SI->setAlignment(commonAlignment(Alignment, I * ElemSize));
609 }
610 }
611
612 // Replaces the load instruction to get rid of the ptrcast used as source
613 // operand.
614 void transformLoad(IRBuilder<> &B, LoadInst *LI, Value *CastedOperand,
615 Value *OriginalOperand) {
616 Type *ToTy = GR->findDeducedElementType(CastedOperand);
617 B.SetInsertPoint(LI);
618
619 Value *Output =
620 buildLegalizedLoad(B, ToTy, OriginalOperand, LI, CastedOperand);
621 if (!Output)
622 return;
623
624 GR->replaceAllUsesWith(LI, Output, /* DeleteOld= */ true);
625 DeadInstructions.push_back(LI);
626 }
627
628 // Creates an spv_insertelt instruction (equivalent to llvm's insertelement).
629 Value *makeInsertElement(IRBuilder<> &B, Value *Vector, Value *Element,
630 unsigned Index) {
631 Type *Int32Ty = Type::getInt32Ty(B.getContext());
632 SmallVector<Type *, 4> Types = {Vector->getType(), Vector->getType(),
633 Element->getType(), Int32Ty};
634 SmallVector<Value *> Args = {Vector, Element, B.getInt32(Index)};
635 Value *NewI = B.CreateIntrinsic(Intrinsic::spv_insertelt, {Types}, {Args});
636 buildAssignType(B, Vector->getType(), NewI);
637 return NewI;
638 }
639
640 // Creates an spv_extractelt instruction (equivalent to llvm's
641 // extractelement).
642 Value *makeExtractElement(IRBuilder<> &B, Type *ElementType, Value *Vector,
643 unsigned Index) {
644 Type *Int32Ty = Type::getInt32Ty(B.getContext());
645 SmallVector<Type *, 3> Types = {ElementType, Vector->getType(), Int32Ty};
646 SmallVector<Value *> Args = {Vector, B.getInt32(Index)};
647 Value *NewI = B.CreateIntrinsic(Intrinsic::spv_extractelt, {Types}, {Args});
648 buildAssignType(B, ElementType, NewI);
649 return NewI;
650 }
651
652 // Extracts scalar element |Index| from |Vector|. A <1 x T> vector shares its
653 // SPIR-V type with the scalar T, so a plain extractelement would be invalid;
654 // bridge it with spv_bitcast instead.
655 Value *extractScalarFromVector(IRBuilder<> &B, Value *Vector,
656 unsigned Index) {
657 auto *VecTy = cast<FixedVectorType>(Vector->getType());
658 Type *ElemTy = VecTy->getElementType();
659 if (VecTy->getNumElements() == 1) {
660 Value *Scalar =
661 B.CreateIntrinsic(Intrinsic::spv_bitcast, {ElemTy, VecTy}, {Vector});
662 buildAssignType(B, ElemTy, Scalar);
663 return Scalar;
664 }
665 return makeExtractElement(B, ElemTy, Vector, Index);
666 }
667
668 // Stores the given Src vector operand into the Dst vector, adjusting the size
669 // if required.
670 Value *storeVectorFromVector(IRBuilder<> &B, Value *Src, Value *Dst,
671 Align Alignment) {
672 FixedVectorType *SrcType = cast<FixedVectorType>(Src->getType());
673 FixedVectorType *DstType =
674 cast<FixedVectorType>(GR->findDeducedElementType(Dst));
675 auto dstNumElements = DstType->getNumElements();
676 auto srcNumElements = SrcType->getNumElements();
677
678 // if the element type differs, it is a bitcast.
679 if (DstType->getElementType() != SrcType->getElementType()) {
680 // Support bitcast between vectors of different sizes only if
681 // the total bitwidth is the same.
682 [[maybe_unused]] auto dstBitWidth =
683 DstType->getElementType()->getScalarSizeInBits() * dstNumElements;
684 [[maybe_unused]] auto srcBitWidth =
685 SrcType->getElementType()->getScalarSizeInBits() * srcNumElements;
686 assert(dstBitWidth == srcBitWidth &&
687 "Unsupported bitcast between vectors of different sizes.");
688
689 Src =
690 B.CreateIntrinsic(Intrinsic::spv_bitcast, {DstType, SrcType}, {Src});
691 buildAssignType(B, DstType, Src);
692 SrcType = DstType;
693
694 StoreInst *SI = B.CreateStore(Src, Dst);
695 SI->setAlignment(Alignment);
696 return SI;
697 }
698
699 assert(DstType->getNumElements() >= SrcType->getNumElements());
700 LoadInst *LI = B.CreateLoad(DstType, Dst);
701 LI->setAlignment(Alignment);
702 Value *OldValues = LI;
703 buildAssignType(B, OldValues->getType(), OldValues);
704 Value *NewValues = Src;
705
706 for (unsigned I = 0; I < SrcType->getNumElements(); ++I) {
707 Value *Element =
708 makeExtractElement(B, SrcType->getElementType(), NewValues, I);
709 OldValues = makeInsertElement(B, OldValues, Element, I);
710 }
711
712 StoreInst *SI = B.CreateStore(OldValues, Dst);
713 SI->setAlignment(Alignment);
714 return SI;
715 }
716
717 // Builds a legalized store to a pointer, drilling down through
718 // memory layouts to find a compatible type.
719 void buildLegalizedStore(IRBuilder<> &B, Value *Src, Value *Dst,
720 Align Alignment, Value *CastedPtr,
721 Instruction *IllegalStore) {
722 auto ResultOpt = getPointerToFirstCompatibleType(B, Dst, Dst->getType(),
723 Src->getType(), true);
724 if (!ResultOpt) {
725 if (tryReinterpretStore(B, Src->getType(), Dst, CastedPtr, Src,
726 Alignment))
727 return;
728 llvm_unreachable("Failed to store to aggregate: "
729 "Could not find compatible memory layout.");
730 }
731 auto [GEP, CurrentTy] = *ResultOpt;
732
733 auto *DAT = dyn_cast<ArrayType>(CurrentTy);
734 auto *DVT = dyn_cast<FixedVectorType>(CurrentTy);
735 auto *SVT = dyn_cast<FixedVectorType>(Src->getType());
736 auto *DMAT =
737 DAT ? dyn_cast<FixedVectorType>(DAT->getElementType()) : nullptr;
738
739 if (Src->getType() == CurrentTy) {
740 StoreInst *SI = B.CreateStore(Src, GEP);
741 SI->setAlignment(Alignment);
742 return;
743 }
744 if (DVT && SVT) {
745 storeVectorFromVector(B, Src, GEP, Alignment);
746 return;
747 }
748 if (DAT && SVT && SVT->getElementType() == DAT->getElementType()) {
749 storeArrayFromVector(B, Src, GEP, DAT, Alignment);
750 return;
751 }
752 if (DMAT && SVT && DMAT->getElementType() == SVT->getElementType()) {
753 storeMatrixArrayFromVector(B, Src, GEP, DAT, Alignment);
754 return;
755 }
756
757 llvm_unreachable("Failed to store to aggregate.");
758 }
759
760 // Transforms a store instruction (or SPV intrinsic) using a ptrcast as
761 // operand into a valid logical SPIR-V store with no ptrcast.
762 void transformStore(IRBuilder<> &B, Instruction *IllegalStore, Value *Src,
763 Value *Dst, Value *CastedOperand, Align Alignment) {
764 B.SetInsertPoint(IllegalStore);
765 buildLegalizedStore(B, Src, Dst, Alignment, CastedOperand, IllegalStore);
766 DeadInstructions.push_back(IllegalStore);
767 }
768
769 void legalizePointerCast(IntrinsicInst *II) {
770 Value *CastedOperand = II;
771 Value *OriginalOperand = II->getOperand(0);
772
773 IRBuilder<> B(II->getContext());
774 std::vector<Value *> Users;
775 for (Use &U : II->uses())
776 Users.push_back(U.getUser());
777
778 for (Value *User : Users) {
779 if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
780 transformLoad(B, LI, CastedOperand, OriginalOperand);
781 continue;
782 }
783
784 if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
785 transformStore(B, SI, SI->getValueOperand(), OriginalOperand,
786 CastedOperand, SI->getAlign());
787 continue;
788 }
789
790 if (IntrinsicInst *Intrin = dyn_cast<IntrinsicInst>(User)) {
791 if (Intrin->getIntrinsicID() == Intrinsic::spv_assign_ptr_type) {
792 DeadInstructions.push_back(Intrin);
793 continue;
794 }
795
796 if (Intrin->getIntrinsicID() == Intrinsic::spv_gep) {
797 GR->replaceAllUsesWith(CastedOperand, OriginalOperand,
798 /* DeleteOld= */ false);
799 continue;
800 }
801
802 if (Intrin->getIntrinsicID() == Intrinsic::spv_store) {
804 if (ConstantInt *C = dyn_cast<ConstantInt>(Intrin->getOperand(3)))
805 Alignment = Align(C->getZExtValue());
806 transformStore(B, Intrin, Intrin->getArgOperand(0), OriginalOperand,
807 CastedOperand, Alignment);
808 continue;
809 }
810 }
811
812 llvm_unreachable("Unsupported ptrcast user. Please fix.");
813 }
814
815 DeadInstructions.push_back(II);
816 }
817
818public:
819 SPIRVLegalizePointerCastImpl(const SPIRVTargetMachine &TM) : TM(TM) {}
820
821 bool run(Function &F) {
822 const SPIRVSubtarget &ST = TM.getSubtarget<SPIRVSubtarget>(F);
823 GR = ST.getSPIRVGlobalRegistry();
824 DeadInstructions.clear();
825
826 std::vector<IntrinsicInst *> WorkList;
827 for (auto &BB : F) {
828 for (auto &I : BB) {
829 auto *II = dyn_cast<IntrinsicInst>(&I);
830 if (II && II->getIntrinsicID() == Intrinsic::spv_ptrcast)
831 WorkList.push_back(II);
832 }
833 }
834
835 for (IntrinsicInst *II : WorkList)
836 legalizePointerCast(II);
837
838 for (Instruction *I : DeadInstructions)
839 I->eraseFromParent();
840
841 return DeadInstructions.size() != 0;
842 }
843
844private:
845 const SPIRVTargetMachine &TM;
846 SPIRVGlobalRegistry *GR = nullptr;
847 std::vector<Instruction *> DeadInstructions;
848};
849
850class SPIRVLegalizePointerCastLegacy : public FunctionPass {
851public:
852 static char ID;
853 SPIRVLegalizePointerCastLegacy(const SPIRVTargetMachine &TM)
854 : FunctionPass(ID), TM(TM) {}
855
856 bool runOnFunction(Function &F) override {
857 return SPIRVLegalizePointerCastImpl(TM).run(F);
858 }
859
860private:
861 const SPIRVTargetMachine &TM;
862};
863} // namespace
864
867 return SPIRVLegalizePointerCastImpl(TM).run(F) ? PreservedAnalyses::none()
869}
870
871char SPIRVLegalizePointerCastLegacy::ID = 0;
872INITIALIZE_PASS(SPIRVLegalizePointerCastLegacy, "spirv-legalize-pointer-cast",
873 "SPIRV legalize pointer cast pass", false, false)
874
876 return new SPIRVLegalizePointerCastLegacy(*TM);
877}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
unsigned uint64_t
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
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 bool runOnFunction(Function &F, bool PostInlining)
Hexagon Common GEP
iv Induction Variable Users
Definition IVUsers.cpp:48
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
uint64_t IntrinsicInst * II
#define INITIALIZE_PASS(passName, arg, name, cfg, analysis)
Definition PassSupport.h:56
void setCallingConv(CallingConv::ID CC)
void setAttributes(AttributeList A)
Set the attributes for this call.
unsigned getNumElements() const
static LLVM_ABI FixedVectorType * get(Type *ElementType, unsigned NumElts)
Definition Type.cpp:867
FunctionPass class - This class is used to implement most global optimizations.
Definition Pass.h:314
static LLVM_ABI IntegerType * get(LLVMContext &C, unsigned NumBits)
This static method is the primary way of constructing an IntegerType.
Definition Type.cpp:348
void setAlignment(Align Align)
Type * getPointerOperandType() const
Align getAlign() const
Return the alignment of the access that is being performed.
static LLVM_ABI PoisonValue * get(Type *T)
Static factory methods - Return an 'poison' object of the specified type.
A set of analyses that are preserved following a run of a transformation pass.
Definition Analysis.h:112
static PreservedAnalyses none()
Convenience factory function for the empty preserved set.
Definition Analysis.h:115
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition Analysis.h:118
PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM)
void push_back(const T &Elt)
bool isIntOrIntVectorTy() const
Return true if this is an integer type or a vector of integer types.
Definition Type.h:263
bool isSingleValueType() const
Return true if the type is a valid type for a register in codegen.
Definition Type.h:311
LLVM_ABI unsigned getScalarSizeInBits() const LLVM_READONLY
If this is a vector type, return the getPrimitiveSizeInBits value for the element type.
Definition Type.cpp:232
Type * getType() const
All values are typed, get the type of this value.
Definition Value.h:255
Type * getElementType() const
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
constexpr char Align[]
Key for Kernel::Arg::Metadata::mAlign.
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.
DXILDebugInfoMap run(Module &M)
ElementType
The element type of an SRV or UAV resource.
Definition DXILABI.h:68
This is an optimization pass for GlobalISel generic memory operations.
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
@ Load
The value being inserted comes from a load (InsertElement only).
CallInst * buildIntrWithMD(Intrinsic::ID IntrID, ArrayRef< Type * > Types, Value *Arg, Value *Arg2, ArrayRef< Constant * > Imms, IRBuilder<> &B)
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Value
Definition InstrProf.h:143
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
IRBuilder(LLVMContext &, FolderTy, InserterTy, MDNode *, ArrayRef< OperandBundleDef >) -> IRBuilder< FolderTy, InserterTy >
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
Align commonAlignment(Align A, uint64_t Offset)
Returns the alignment that satisfies both alignments.
Definition Alignment.h:201
AnalysisManager< Function > FunctionAnalysisManager
Convenience typedef for the Function analysis manager.
FunctionPass * createSPIRVLegalizePointerCastPass(SPIRVTargetMachine *TM)