LLVM 24.0.0git
SPIRVEmitIntrinsics.cpp
Go to the documentation of this file.
1//===-- SPIRVEmitIntrinsics.cpp - emit SPIRV intrinsics ---------*- 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 pass emits SPIRV intrinsics keeping essential high-level information for
10// the translation of LLVM IR to SPIR-V.
11//
12//===----------------------------------------------------------------------===//
13
14#include "SPIRV.h"
15#include "SPIRVAuxDataHandler.h"
16#include "SPIRVBuiltins.h"
17#include "SPIRVSubtarget.h"
18#include "SPIRVTargetMachine.h"
19#include "SPIRVUtils.h"
20#include "llvm/ADT/DenseMap.h"
21#include "llvm/ADT/DenseSet.h"
22#include "llvm/ADT/MapVector.h"
28#include "llvm/IR/IRBuilder.h"
30#include "llvm/IR/InstVisitor.h"
31#include "llvm/IR/IntrinsicsSPIRV.h"
32#include "llvm/IR/LLVMContext.h"
36#include "llvm/IR/Value.h"
37#include "llvm/Support/Debug.h"
38#include "llvm/Support/Error.h"
41
42#include <cassert>
43#include <optional>
44#include <queue>
45
46// This pass performs the following transformation on LLVM IR level required
47// for the following translation to SPIR-V:
48// - replaces direct usages of aggregate constants with target-specific
49// intrinsics;
50// - replaces aggregates-related instructions (extract/insert, ld/st, etc)
51// with a target-specific intrinsics;
52// - emits intrinsics for the global variable initializers since IRTranslator
53// doesn't handle them and it's not very convenient to translate them
54// ourselves;
55// - emits intrinsics to keep track of the string names assigned to the values;
56// - emits intrinsics to keep track of constants (this is necessary to have an
57// LLVM IR constant after the IRTranslation is completed) for their further
58// deduplication;
59// - emits intrinsics to keep track of original LLVM types of the values
60// to be able to emit proper SPIR-V types eventually.
61//
62// TODO: consider removing spv.track.constant in favor of spv.assign.type.
63
64using namespace llvm;
65using namespace llvm::PatternMatch;
66
67#define DEBUG_TYPE "spirv-emit-intrinsics"
68
69namespace llvm::SPIRV {
70#define GET_BuiltinGroup_DECL
71#include "SPIRVGenTables.inc"
72} // namespace llvm::SPIRV
73
74namespace {
75// This class keeps track of which functions reference which global variables.
76class GlobalVariableUsers {
77 template <typename T1, typename T2>
78 using OneToManyMapTy = DenseMap<T1, SmallPtrSet<T2, 4>>;
79
80 OneToManyMapTy<const GlobalVariable *, const Function *> GlobalIsUsedByFun;
81
82 void collectGlobalUsers(
83 const GlobalVariable *GV,
84 OneToManyMapTy<const GlobalVariable *, const GlobalVariable *>
85 &GlobalIsUsedByGlobal) {
87 while (!Stack.empty()) {
88 const Value *V = Stack.pop_back_val();
89
90 if (const Instruction *I = dyn_cast<Instruction>(V)) {
91 GlobalIsUsedByFun[GV].insert(I->getFunction());
92 continue;
93 }
94
95 if (const GlobalVariable *UserGV = dyn_cast<GlobalVariable>(V)) {
96 GlobalIsUsedByGlobal[GV].insert(UserGV);
97 continue;
98 }
99
100 if (const Constant *C = dyn_cast<Constant>(V))
101 Stack.append(C->user_begin(), C->user_end());
102 }
103 }
104
105 bool propagateGlobalToGlobalUsers(
106 OneToManyMapTy<const GlobalVariable *, const GlobalVariable *>
107 &GlobalIsUsedByGlobal) {
109 bool Changed = false;
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())
115 continue;
116 Changed |= set_union(UserGlobals, It->second);
117 }
118 }
119 return Changed;
120 }
121
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())
130 continue;
131 set_union(UserFunctions, It->second);
132 }
133 }
134 }
135
136public:
137 void init(Module &M) {
138 // Collect which global variables are referenced by which global variables
139 // and which functions reference each global variables.
140 OneToManyMapTy<const GlobalVariable *, const GlobalVariable *>
141 GlobalIsUsedByGlobal;
142 GlobalIsUsedByFun.clear();
143 for (GlobalVariable &GV : M.globals())
144 collectGlobalUsers(&GV, GlobalIsUsedByGlobal);
145
146 // Compute indirect references by iterating until a fixed point is reached.
147 while (propagateGlobalToGlobalUsers(GlobalIsUsedByGlobal))
148 (void)0;
149
150 propagateGlobalToFunctionReferences(GlobalIsUsedByGlobal);
151 }
152
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())
158 return It->second;
159
160 static const FunctionSetType Empty{};
161 return Empty;
162 }
163};
164
165static bool isaGEP(const Value *V) {
167}
168
169// If Ty is a byte-addressing type, return the multiplier for the offset.
170// Otherwise return std::nullopt.
171static std::optional<uint64_t> getByteAddressingMultiplier(Type *Ty) {
172 if (Ty == IntegerType::getInt8Ty(Ty->getContext())) {
173 return 1;
174 }
175 if (auto *AT = dyn_cast<ArrayType>(Ty)) {
176 if (AT->getElementType() == IntegerType::getInt8Ty(Ty->getContext())) {
177 return AT->getNumElements();
178 }
179 }
180 return std::nullopt;
181}
182
183// InstCombine emits `P[I + K]` as a constant byte offset C from `P[I]`, which
184// can land past element I. Logical SPIR-V has no pointer arithmetic, and an
185// access chain based on `P[I]` can only index inside element I.
186//
187// To fix this, we split C into a count of array elements, which we add to the
188// array index, and the leftover bytes, fewer than one element, which stay a
189// byte offset inside the new element:
190//
191// gep i8, (gep [N x i8], P, I), C becomes
192// gep i8, (gep [N x i8], P, I + floor(C / N)), C mod N.
193static void foldConstantOffsetIntoArrayIndex(Function &F) {
196 if (!Outer || Outer->getNumIndices() != 1 ||
197 !Outer->getSourceElementType()->isIntegerTy(8))
198 continue;
199 auto *Offset = dyn_cast<ConstantInt>(Outer->getOperand(1));
200 auto *Inner = dyn_cast<GetElementPtrInst>(Outer->getPointerOperand());
201 if (!Offset || !Inner || Inner->getNumIndices() != 1)
202 continue;
203 Value *Index = Inner->getOperand(1);
204 std::optional<uint64_t> Stride =
205 getByteAddressingMultiplier(Inner->getSourceElementType());
206 if (isa<Constant>(Index) || !Stride || *Stride <= 1)
207 continue;
208
209 // Compute in the index type, as the GEP does.
210 Type *IdxTy = F.getDataLayout().getIndexType(Inner->getType());
211 int64_t Bytes = Offset->getValue()
212 .sextOrTrunc(IdxTy->getScalarSizeInBits())
213 .getSExtValue();
214 int64_t Size = *Stride;
215 int64_t Elements = divideFloorSigned(Bytes, Size);
216 if (Elements == 0)
217 continue;
218
219 GEPNoWrapFlags NW = Inner->isInBounds() && Outer->isInBounds()
221 : GEPNoWrapFlags::none();
222 IRBuilder<> B(Outer);
223 Value *NewIndex = B.CreateAdd(B.CreateSExtOrTrunc(Index, IdxTy),
224 ConstantInt::getSigned(IdxTy, Elements));
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),
229 "", NW);
230 Ptr->takeName(Outer);
231 Outer->replaceAllUsesWith(Ptr);
232 Outer->eraseFromParent();
233 if (Inner->use_empty())
234 Inner->eraseFromParent();
235 }
236}
237
238class SPIRVEmitIntrinsicsImpl
239 : public InstVisitor<SPIRVEmitIntrinsicsImpl, Instruction *> {
240 const SPIRVTargetMachine &TM;
241 SPIRVGlobalRegistry *GR = nullptr;
242 Function *CurrF = 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;
251 Error AccessChainErrors = Error::success();
252 SmallPtrSet<GetElementPtrInst *, 4> InvalidGEPs;
253
254 // map of function declarations to <pointer arg index => element type>
255 MapVector<Function *, SmallVector<std::pair<unsigned, Type *>>> FDeclPtrTys;
256
257 // a register of Instructions that don't have a complete type definition
258 bool CanTodoType = true;
259 unsigned TodoTypeSz = 0;
260 DenseMap<Value *, bool> TodoType;
261 void insertTodoType(Value *Op) {
262 // TODO: add isa<CallInst>(Op) to no-insert
263 if (CanTodoType && !isaGEP(Op)) {
264 auto It = TodoType.try_emplace(Op, true);
265 if (It.second)
266 ++TodoTypeSz;
267 }
268 }
269 void eraseTodoType(Value *Op) {
270 auto It = TodoType.find(Op);
271 if (It != TodoType.end() && It->second) {
272 It->second = false;
273 --TodoTypeSz;
274 }
275 }
276 bool isTodoType(Value *Op) {
277 if (isaGEP(Op))
278 return false;
279 auto It = TodoType.find(Op);
280 return It != TodoType.end() && It->second;
281 }
282 // a register of Instructions that were visited by deduceOperandElementType()
283 // to validate operand types with an instruction
284 SmallPtrSet<Instruction *, 0> TypeValidated;
285 // Type-validated PHIs and selects whose element type changed since, to be
286 // revalidated by the outermost deduceOperandElementType() call.
287 SmallVector<Instruction *> RetypedToRevalidate;
288 bool RevalidatingRetyped = false;
289
290 // well known result types of builtins
291 enum WellKnownTypes { Event };
292
293 // deduce element type of untyped pointers
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 = {});
305 Type *deduceElementTypeByUsersDeep(Value *Op,
306 SmallPtrSetImpl<Value *> &Visited,
307 bool UnknownElemTypeI8);
308 void maybeAssignPtrType(Type *&Ty, Value *I, Type *RefTy,
309 bool UnknownElemTypeI8);
310
311 // deduce nested types of composites
312 Type *deduceNestedTypeHelper(User *U, bool UnknownElemTypeI8);
313 Type *deduceNestedTypeHelper(User *U, Type *Ty,
314 SmallPtrSetImpl<Value *> &Visited,
315 bool UnknownElemTypeI8);
316
317 // deduce Types of operands of the Instruction if possible
318 void
319 deduceOperandElementType(Instruction *I,
320 SmallPtrSetImpl<Instruction *> *IncompleteRets,
321 const SmallPtrSetImpl<Value *> *AskOps = nullptr,
322 bool IsPostprocessing = false);
323
324 void preprocessCompositeConstants(IRBuilder<> &B);
325 Value *lowerUndefOrPoison(Value *Op, IRBuilder<> &B, bool HasPoisonExt);
326 void preprocessUndefsAndPoisons(IRBuilder<> &B);
327 void insertCompositeAggregateArms(Instruction *I, IRBuilder<> &B);
328 Value *lowerCompositeMember(Value *Op, IRBuilder<> &B, bool HasPoisonExt);
329 void simplifyNullAddrSpaceCasts();
330
331 Type *reconstructType(Value *Op, bool UnknownElemTypeI8,
332 bool IsPostprocessing);
333
334 void replaceMemInstrUses(Instruction *Old, Instruction *New, IRBuilder<> &B);
335 void processInstrAfterVisit(Instruction *I, IRBuilder<> &B);
336 bool insertAssignPtrTypeIntrs(Instruction *I, IRBuilder<> &B,
337 bool UnknownElemTypeI8);
338 void insertAssignTypeIntrs(Instruction *I, IRBuilder<> &B);
339 void insertAssignPtrTypeTargetExt(TargetExtType *AssignedType, Value *V,
340 IRBuilder<> &B);
341 void replacePointerOperandWithPtrCast(Instruction *I, Value *Pointer,
342 Type *ExpectedElementType,
343 unsigned OperandToReplace,
344 IRBuilder<> &B);
345 void insertPtrCastOrAssignTypeInstr(Instruction *I, IRBuilder<> &B);
346 bool shouldTryToAddMemAliasingDecoration(Instruction *Inst);
347 void insertSpirvDecorations(Instruction *I, IRBuilder<> &B);
348 void insertConstantsForFPFastMathDefault(Module &M);
349 Value *buildSpvUndefComposite(Type *AggrTy, IRBuilder<> &B);
350 void reconstructAggregateReturns(Function &Func, IRBuilder<> &B);
351 void processGlobalValue(GlobalVariable &GV, IRBuilder<> &B);
352 void processParamTypes(Function *F, IRBuilder<> &B);
353 void processParamTypesByFunHeader(Function *F, IRBuilder<> &B);
354 Type *deduceFunParamElementType(Function *F, unsigned OpIdx);
355 Type *deduceFunParamElementType(Function *F, unsigned OpIdx,
356 SmallPtrSetImpl<Function *> &FVisited);
357
358 bool deduceOperandElementTypeCalledFunction(
359 CallInst *CI, SmallVector<std::pair<Value *, unsigned>> &Ops,
360 Type *&KnownElemTy, bool &Incomplete);
361 void deduceOperandElementTypeFunctionPointer(
362 CallInst *CI, SmallVector<std::pair<Value *, unsigned>> &Ops,
363 Type *&KnownElemTy, bool IsPostprocessing);
364 bool deduceOperandElementTypeFunctionRet(
365 Instruction *I, SmallPtrSetImpl<Instruction *> *IncompleteRets,
366 const SmallPtrSetImpl<Value *> *AskOps, bool IsPostprocessing,
367 Type *&KnownElemTy, Value *Op, Function *F);
368
369 CallInst *buildSpvPtrcast(Function *F, Value *Op, Type *ElemTy);
370 void replaceUsesOfWithSpvPtrcast(Value *Op, Type *ElemTy, Instruction *I,
371 DenseMap<Function *, CallInst *> Ptrcasts);
372 void propagateElemType(Value *Op, Type *ElemTy,
373 DenseSet<std::pair<Value *, Value *>> &VisitedSubst);
374 void
375 propagateElemTypeRec(Value *Op, Type *PtrElemTy, Type *CastElemTy,
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);
381
382 void replaceAllUsesWith(Value *Src, Value *Dest, bool DeleteOld = true);
383 void replaceAllUsesWithAndErase(IRBuilder<> &B, Instruction *Src,
384 Instruction *Dest, bool DeleteOld = true);
385
386 void applyDemangledPtrArgTypes(IRBuilder<> &B);
387
388 GetElementPtrInst *simplifyZeroLengthArrayGepInst(GetElementPtrInst *GEP);
389
390 bool runOnFunction(Function &F);
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);
400
401 void emitUnstructuredLoopControls(Function &F, IRBuilder<> &B);
402
403 // Tries to walk the type accessed by the given GEP instruction.
404 // For each nested type access, one of the 2 callbacks is called:
405 // - OnLiteralIndexing when the index is a known constant value.
406 // Parameters:
407 // PointedType: the pointed type resulting of this indexing.
408 // If the parent type is an array, this is the index in the array.
409 // If the parent type is a struct, this is the field index.
410 // Index: index of the element in the parent type.
411 // - OnDynamnicIndexing when the index is a non-constant value.
412 // This callback is only called when indexing into an array.
413 // Parameters:
414 // ElementType: the type of the elements stored in the parent array.
415 // Offset: the Value* containing the byte offset into the array.
416 // Multiplier: a scaling factor for the offset.
417 // Return true for a fallback, false for a complete walk, or an error.
418 Expected<bool> walkLogicalAccessChain(
419 GetElementPtrInst &GEP,
420 const std::function<void(Type *PointedType, uint64_t Index)>
421 &OnLiteralIndexing,
422 const std::function<void(Type *ElementType, Value *Offset,
423 uint64_t Multiplier)> &OnDynamicIndexing);
424
425 bool walkLogicalAccessChainDynamic(
426 Type *CurType, Value *Operand, uint64_t Multiplier,
427 const std::function<void(Type *, uint64_t)> &OnLiteralIndexing,
428 const std::function<void(Type *, Value *, uint64_t)> &OnDynamicIndexing);
429
430 Expected<bool> walkLogicalAccessChainConstant(
431 Type *CurType, uint64_t Offset,
432 const std::function<void(Type *, uint64_t)> &OnLiteralIndexing);
433
434 void recordAccessChainError(GetElementPtrInst &GEP, Error Err);
435
436 // Returns the type accessed using the given GEP instruction by relying
437 // on the GEP type.
438 // FIXME: GEP types are not supposed to be used to retrieve the pointed
439 // type. This must be fixed.
440 Type *getGEPType(GetElementPtrInst *GEP);
441
442 // Returns the type accessed using the given GEP instruction by walking
443 // the source type using the GEP indices.
444 // FIXME: without help from the frontend, this method cannot reliably retrieve
445 // the stored type, nor can robustly determine the depth of the type
446 // we are accessing.
447 Type *getGEPTypeLogical(GetElementPtrInst *GEP);
448
449 Instruction *buildLogicalAccessChainFromGEP(GetElementPtrInst &GEP);
450
451 Value *truncateGEPIndex(Value *Idx, Type *IdxTy, IRBuilder<> &B);
452
453public:
454 SPIRVEmitIntrinsicsImpl(const SPIRVTargetMachine &TM) : TM(TM) {}
455 Instruction *visitInstruction(Instruction &I) { return &I; }
456 Instruction *visitSwitchInst(SwitchInst &I);
457 Instruction *visitGetElementPtrInst(GetElementPtrInst &I);
458 Instruction *visitIntrinsicInst(IntrinsicInst &I);
459 Instruction *visitBitCastInst(BitCastInst &I);
460 Instruction *visitInsertElementInst(InsertElementInst &I);
461 Instruction *visitExtractElementInst(ExtractElementInst &I);
462 Instruction *visitInsertValueInst(InsertValueInst &I);
463 Instruction *visitExtractValueInst(ExtractValueInst &I);
464 Instruction *visitLoadInst(LoadInst &I);
465 Instruction *visitStoreInst(StoreInst &I);
466 Instruction *visitAllocaInst(AllocaInst &I);
467 Instruction *visitAtomicCmpXchgInst(AtomicCmpXchgInst &I);
468 Instruction *visitAtomicRMWInst(AtomicRMWInst &I);
469 Instruction *visitUnreachableInst(UnreachableInst &I);
470 Instruction *visitCallInst(CallInst &I);
471
472 bool runOnModule(Module &M);
473};
474
475class SPIRVEmitIntrinsicsLegacy : public ModulePass {
476 const SPIRVTargetMachine &TM;
477
478public:
479 static char ID;
480 SPIRVEmitIntrinsicsLegacy(const SPIRVTargetMachine &TM)
481 : ModulePass(ID), TM(TM) {}
482
483 StringRef getPassName() const override { return "SPIRV emit intrinsics"; }
484
485 bool runOnModule(Module &M) override {
486 return SPIRVEmitIntrinsicsImpl(TM).runOnModule(M);
487 }
488};
489
490bool isConvergenceIntrinsic(const Instruction *I) {
491 return match(I, m_AnyIntrinsic<Intrinsic::experimental_convergence_entry,
492 Intrinsic::experimental_convergence_loop,
493 Intrinsic::experimental_convergence_anchor>());
494}
495
496bool expectIgnoredInIRTranslation(const Instruction *I) {
497 return match(I, m_AnyIntrinsic<Intrinsic::invariant_start,
498 Intrinsic::spv_resource_handlefrombinding,
499 Intrinsic::spv_resource_getbasepointer,
500 Intrinsic::spv_resource_getpointer>());
501}
502
503// Returns the source pointer from `I` ignoring intermediate ptrcast.
504Value *getPointerRoot(Value *I) {
505 Value *V;
507 return getPointerRoot(V);
508 return I;
509}
510
511} // namespace
512
513char SPIRVEmitIntrinsicsLegacy::ID = 0;
514
515INITIALIZE_PASS(SPIRVEmitIntrinsicsLegacy, "spirv-emit-intrinsics",
516 "SPIRV emit intrinsics", false, false)
517
518static inline bool isAssignTypeInstr(const Instruction *I) {
520}
521
526
527static bool isAggrConstForceInt32(const Value *V) {
528 bool IsAggrZero =
529 isa<ConstantAggregateZero>(V) && !V->getType()->isVectorTy();
530 bool IsUndefAggregate = isa<UndefValue>(V) && V->getType()->isAggregateType();
532 isa<ConstantDataArray>(V) || IsAggrZero || IsUndefAggregate;
533}
534
540
542 if (isa<PHINode>(I))
543 B.SetInsertPoint(I->getParent()->getFirstNonPHIOrAlloca());
544 else
545 B.SetInsertPoint(I);
546}
547
549 B.SetCurrentDebugLocation(I->getDebugLoc());
550 if (I->getType()->isVoidTy())
551 B.SetInsertPoint(I->getNextNode());
552 else
553 B.SetInsertPoint(*I->getInsertionPointAfterDef());
554}
555
561
562static inline void reportFatalOnTokenType(const Instruction *I) {
563 if (I->getType()->isTokenTy())
564 report_fatal_error("A token is encountered but SPIR-V without extensions "
565 "does not support token type",
566 false);
567}
568
569static void emitAssignName(const SPIRVOptions &CLOpts, Instruction *I,
570 IRBuilder<> &B) {
571 if (!I->hasName() || I->getType()->isAggregateType() ||
572 expectIgnoredInIRTranslation(I))
573 return;
574
575 // We want to be conservative when adding the names because they can interfere
576 // with later optimizations.
577 bool KeepName = CLOpts.emit_op_names;
578 if (!KeepName) {
579 if (isa<AllocaInst>(I)) {
580 KeepName = true;
581 } else if (auto *CI = dyn_cast<CallBase>(I)) {
582 Function *F = CI->getCalledFunction();
583 if (F && F->getName().starts_with("llvm.spv.alloca"))
584 KeepName = true;
585 }
586 }
587
588 if (!KeepName)
589 return;
590
593 LLVMContext &Ctx = I->getContext();
594 std::vector<Value *> Args = {
596 Ctx, MDNode::get(Ctx, MDString::get(Ctx, I->getName())))};
597 B.CreateIntrinsic(Intrinsic::spv_assign_name, {I->getType()}, Args);
598}
599
600void SPIRVEmitIntrinsicsImpl::replaceAllUsesWith(Value *Src, Value *Dest,
601 bool DeleteOld) {
602 GR->replaceAllUsesWith(Src, Dest, DeleteOld);
603 // Update uncomplete type records if any
604 if (isTodoType(Src)) {
605 if (DeleteOld)
606 eraseTodoType(Src);
607 insertTodoType(Dest);
608 }
609}
610
611void SPIRVEmitIntrinsicsImpl::replaceAllUsesWithAndErase(IRBuilder<> &B,
612 Instruction *Src,
613 Instruction *Dest,
614 bool DeleteOld) {
615 replaceAllUsesWith(Src, Dest, DeleteOld);
616 std::string Name = Src->hasName() ? Src->getName().str() : "";
617 Src->eraseFromParent();
618 if (!Name.empty()) {
619 Dest->setName(Name);
620 if (Named.insert(Dest).second)
621 emitAssignName(TM.getCLOpts(), Dest, B);
622 }
623}
624
626 return SI && F->getCallingConv() == CallingConv::SPIR_KERNEL &&
627 isPointerTy(SI->getValueOperand()->getType()) &&
628 isa<Argument>(SI->getValueOperand());
629}
630
631// A pointer-typed local holds a pointer, so its deduced pointee must stay a
632// pointer.
634 using namespace PatternMatch;
635 V = V->stripPointerCasts();
636 if (auto *AI = dyn_cast<AllocaInst>(V))
637 return isUntypedPointerTy(AI->getAllocatedType());
638 return match(
640}
641
642// Maybe restore original function return type.
644 Type *Ty) {
646 if (!CI || CI->isIndirectCall() || CI->isInlineAsm() ||
648 return Ty;
649 if (Type *OriginalTy = GR->findMutated(CI->getCalledFunction()))
650 return OriginalTy;
651 return Ty;
652}
653
654// Return the pointee type of the pointer member of AggrTy selected by Indices.
655// Untyped pointer members are lowered as pointers to i8.
657 Type *MemberTy = ExtractValueInst::getIndexedType(AggrTy, Indices);
658 if (Type *ElemTy = getPointeeType(MemberTy))
659 return ElemTy;
660 return IntegerType::getInt8Ty(AggrTy->getContext());
661}
662
663// Reconstruct type with nested element types according to deduced type info.
664// Return nullptr if no detailed type info is available.
665Type *SPIRVEmitIntrinsicsImpl::reconstructType(Value *Op,
666 bool UnknownElemTypeI8,
667 bool IsPostprocessing) {
668 Type *Ty = Op->getType();
669 if (auto *OpI = dyn_cast<Instruction>(Op)) {
670 Ty = restoreMutatedType(GR, OpI, Ty);
671 if (auto It = AggrConstTypes.find(OpI); It != AggrConstTypes.end())
672 Ty = It->second;
673 }
674 if (!isUntypedPointerTy(Ty))
675 return Ty;
676 // try to find the pointee type
677 if (Type *NestedTy = GR->findDeducedElementType(Op))
679 // not a pointer according to the type info (e.g., Event object)
680 CallInst *CI = GR->findAssignPtrTypeInstr(Op);
681 if (CI) {
682 MetadataAsValue *MD = cast<MetadataAsValue>(CI->getArgOperand(1));
683 return cast<ConstantAsMetadata>(MD->getMetadata())->getType();
684 }
685 if (UnknownElemTypeI8) {
686 if (!IsPostprocessing)
687 insertTodoType(Op);
688 return getTypedPointerWrapper(IntegerType::getInt8Ty(Op->getContext()),
690 }
691 return nullptr;
692}
693
694CallInst *SPIRVEmitIntrinsicsImpl::buildSpvPtrcast(Function *F, Value *Op,
695 Type *ElemTy) {
696 IRBuilder<> B(*F->getParent());
697 if (auto *OpI = dyn_cast<Instruction>(Op)) {
698 // spv_ptrcast's argument Op denotes an instruction that generates
699 // a value, and we may use getInsertionPointAfterDef()
701 } else if (auto *OpA = dyn_cast<Argument>(Op)) {
702 B.SetInsertPointPastAllocas(OpA->getParent());
703 B.SetCurrentDebugLocation(DebugLoc());
704 } else {
705 B.SetInsertPoint(F->getEntryBlock().getFirstNonPHIOrAlloca());
706 }
707 Type *OpTy = Op->getType();
708 SmallVector<Type *, 2> Types = {OpTy, OpTy};
709 SmallVector<Value *, 2> Args = {
710 Op, buildMD(getNormalizedPoisonValue(ElemTy, CanUseAnyVectorRank)),
711 B.getInt32(getPointerAddressSpace(OpTy))};
712 CallInst *PtrCasted =
713 B.CreateIntrinsicWithoutFolding(Intrinsic::spv_ptrcast, {Types}, Args);
714 GR->buildAssignPtr(B, ElemTy, PtrCasted);
715 return PtrCasted;
716}
717
718void SPIRVEmitIntrinsicsImpl::replaceUsesOfWithSpvPtrcast(
719 Value *Op, Type *ElemTy, Instruction *I,
720 DenseMap<Function *, CallInst *> Ptrcasts) {
721 Function *F = I->getParent()->getParent();
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;
727 } else {
728 PtrCastedI = It->second;
729 }
730 I->replaceUsesOfWith(Op, PtrCastedI);
731}
732
733void SPIRVEmitIntrinsicsImpl::propagateElemType(
734 Value *Op, Type *ElemTy,
735 DenseSet<std::pair<Value *, Value *>> &VisitedSubst) {
736 DenseMap<Function *, CallInst *> Ptrcasts;
737 SmallVector<User *> Users(Op->users());
738 for (auto *U : Users) {
739 if (!isa<Instruction>(U) || isSpvIntrinsic(U))
740 continue;
741 if (!VisitedSubst.insert(std::make_pair(U, Op)).second)
742 continue;
744 // If the instruction was validated already, we need to keep it valid by
745 // keeping current Op type.
746 if (isaGEP(UI) || TypeValidated.find(UI) != TypeValidated.end())
747 replaceUsesOfWithSpvPtrcast(Op, ElemTy, UI, Ptrcasts);
748 }
749}
750
751void SPIRVEmitIntrinsicsImpl::propagateElemTypeRec(
752 Value *Op, Type *PtrElemTy, Type *CastElemTy,
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));
758}
759
760void SPIRVEmitIntrinsicsImpl::propagateElemTypeRec(
761 Value *Op, Type *PtrElemTy, Type *CastElemTy,
762 DenseSet<std::pair<Value *, Value *>> &VisitedSubst,
763 SmallPtrSetImpl<Value *> &Visited,
764 DenseMap<Function *, CallInst *> Ptrcasts) {
765 if (!Visited.insert(Op).second)
766 return;
767 SmallVector<User *> Users(Op->users());
768 for (auto *U : Users) {
769 if (!isa<Instruction>(U) || isSpvIntrinsic(U))
770 continue;
771 if (!VisitedSubst.insert(std::make_pair(U, Op)).second)
772 continue;
774 // If the instruction was validated already, we need to keep it valid by
775 // keeping current Op type.
776 if (isaGEP(UI) || TypeValidated.find(UI) != TypeValidated.end())
777 replaceUsesOfWithSpvPtrcast(Op, CastElemTy, UI, Ptrcasts);
778 }
779}
780
781// Set element pointer type to the given value of ValueTy and tries to
782// specify this type further (recursively) by Operand value, if needed.
783
784Type *SPIRVEmitIntrinsicsImpl::deduceElementTypeByValueDeep(
785 Type *ValueTy, Value *Operand, bool UnknownElemTypeI8) {
786 SmallPtrSet<Value *, 0> Visited;
787 return deduceElementTypeByValueDeep(ValueTy, Operand, Visited,
788 UnknownElemTypeI8);
789}
790
791Type *SPIRVEmitIntrinsicsImpl::deduceElementTypeByValueDeep(
792 Type *ValueTy, Value *Operand, SmallPtrSetImpl<Value *> &Visited,
793 bool UnknownElemTypeI8, std::optional<unsigned> AddrSpace) {
794 Type *Ty = ValueTy;
795 if (Operand) {
796 if (auto *PtrTy = dyn_cast<PointerType>(Ty)) {
797 if (Type *NestedTy =
798 deduceElementTypeHelper(Operand, Visited, UnknownElemTypeI8))
800 NestedTy, AddrSpace.value_or(PtrTy->getAddressSpace()));
801 } else {
802 Ty = deduceNestedTypeHelper(dyn_cast<User>(Operand), Ty, Visited,
803 UnknownElemTypeI8);
804 }
805 }
806 return Ty;
807}
808
809// Traverse User instructions to deduce an element pointer type of the operand.
810Type *SPIRVEmitIntrinsicsImpl::deduceElementTypeByUsersDeep(
811 Value *Op, SmallPtrSetImpl<Value *> &Visited, bool UnknownElemTypeI8) {
812 if (!Op || !isPointerTy(Op->getType()) || isa<ConstantPointerNull>(Op) ||
814 return nullptr;
815
816 if (auto ElemTy = getPointeeType(Op->getType()))
817 return ElemTy;
818
819 // maybe we already know operand's element type
820 if (Type *KnownTy = GR->findDeducedElementType(Op))
821 return KnownTy;
822
823 for (User *OpU : Op->users()) {
824 if (Instruction *Inst = dyn_cast<Instruction>(OpU)) {
825 if (Type *Ty = deduceElementTypeHelper(Inst, Visited, UnknownElemTypeI8))
826 return Ty;
827 }
828 }
829 return nullptr;
830}
831
832// Implements what we know in advance about intrinsics and builtin calls
833// TODO: consider feasibility of this particular case to be generalized by
834// encoding knowledge about intrinsics and builtin calls by corresponding
835// specification rules
837 Function *CalledF, unsigned OpIdx) {
838 // OpenCL.std printf takes its format string as a pointer to i8. Match the
839 // bare builtin name, as lowering does, to also cover unmangled `printf`.
840 std::string Name = SPIRV::lookupBuiltinNameHelper(DemangledName);
841 // OpenCL get_fence only has void* overloads.
842 if (OpIdx == 0 && (Name == "printf" || Name == "get_fence"))
843 return IntegerType::getInt8Ty(CalledF->getContext());
844 // OpCaptureEventProfilingInfo requires Value to point to an 8-bit integer.
845 if (OpIdx == 2 && (Name == "capture_event_profiling_info" ||
846 Name == "__spirv_CaptureEventProfilingInfo"))
847 return IntegerType::getInt8Ty(CalledF->getContext());
848 return nullptr;
849}
850
851// Deduce and return a successfully deduced Type of the Instruction,
852// or nullptr otherwise.
853Type *SPIRVEmitIntrinsicsImpl::deduceElementTypeHelper(Value *I,
854 bool UnknownElemTypeI8) {
855 SmallPtrSet<Value *, 0> Visited;
856 return deduceElementTypeHelper(I, Visited, UnknownElemTypeI8);
857}
858
859void SPIRVEmitIntrinsicsImpl::maybeAssignPtrType(Type *&Ty, Value *Op,
860 Type *RefTy,
861 bool UnknownElemTypeI8) {
862 if (isUntypedPointerTy(RefTy)) {
863 if (!UnknownElemTypeI8)
864 return;
865 insertTodoType(Op);
867 return;
868 }
869 Ty = RefTy;
870}
871
872bool SPIRVEmitIntrinsicsImpl::walkLogicalAccessChainDynamic(
873 Type *CurType, Value *Operand, uint64_t Multiplier,
874 const std::function<void(Type *, uint64_t)> &OnLiteralIndexing,
875 const std::function<void(Type *, Value *, uint64_t)> &OnDynamicIndexing) {
876 // Dynamic indexing into a struct is not possible.
877 // We know that we must be accessing the first element
878 // of the struct if the current type is a struct.
879 // Try to find the first array type that is at offset 0 in the struct.
880 while (auto *ST = dyn_cast<StructType>(CurType)) {
881 if (ST->getNumElements() == 0)
882 break;
883 CurType = ST->getElementType(0);
884 OnLiteralIndexing(CurType, 0);
885 }
886
887 assert(CurType);
888 ArrayType *AT = dyn_cast<ArrayType>(CurType);
889 // Operand is not constant. Either we have an array and accept it, or we
890 // give up.
891 if (AT)
892 OnDynamicIndexing(AT->getElementType(), Operand, Multiplier);
893 return AT == nullptr;
894}
895
896Expected<bool> SPIRVEmitIntrinsicsImpl::walkLogicalAccessChainConstant(
897 Type *CurType, uint64_t Offset,
898 const std::function<void(Type *, uint64_t)> &OnLiteralIndexing) {
899 auto &DL = CurrF->getDataLayout();
900 Type *BaseType = CurType;
901
902 do {
903 if (ArrayType *AT = dyn_cast<ArrayType>(CurType)) {
904 uint64_t EltTypeSize = DL.getTypeAllocSize(AT->getElementType());
905 assert(Offset < AT->getNumElements() * EltTypeSize);
906 uint64_t Index = Offset / EltTypeSize;
907 Offset = Offset - (Index * EltTypeSize);
908 CurType = AT->getElementType();
909 OnLiteralIndexing(CurType, Index);
910 } else if (StructType *ST = dyn_cast<StructType>(CurType)) {
911 uint32_t StructSize = DL.getTypeSizeInBits(ST) / 8;
912 assert(Offset < StructSize);
913 (void)StructSize;
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);
919 } else if (auto *VT = dyn_cast<FixedVectorType>(CurType)) {
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)
926 return createStringError(
927 "Cannot lower an access to vector padding for Logical SPIR-V");
928 uint64_t Index = Offset / EltTypeSize;
929 Offset -= Index * EltTypeSize;
930 CurType = EltTy;
931 OnLiteralIndexing(CurType, Index);
932 } else {
933 if (CurType == BaseType && Offset >= DL.getTypeAllocSize(CurType))
934 return true;
935 return createStringError(
936 "Cannot lower a byte offset within a scalar or padding for "
937 "Logical SPIR-V");
938 }
939 } while (Offset > 0);
940
941 return false;
942}
943
944Expected<bool> SPIRVEmitIntrinsicsImpl::walkLogicalAccessChain(
945 GetElementPtrInst &GEP,
946 const std::function<void(Type *, uint64_t)> &OnLiteralIndexing,
947 const std::function<void(Type *, Value *, uint64_t)> &OnDynamicIndexing) {
948 // We only rewrite byte-addressing GEP. Other should be left as-is.
949 // Valid byte-addressing GEP must always have a single index.
950 std::optional<uint64_t> MultiplierOpt =
951 getByteAddressingMultiplier(GEP.getSourceElementType());
952 assert(MultiplierOpt && "We only rewrite byte-addressing GEP");
953 uint64_t Multiplier = *MultiplierOpt;
954 assert(GEP.getNumIndices() == 1);
955
956 Value *Src = getPointerRoot(GEP.getPointerOperand());
957 Type *CurType = deduceElementType(Src, true);
958 if (!CurType->isSized())
959 return createStringError(
960 "Cannot lower byte addressing with an unsized type for Logical SPIR-V");
961
962 Value *Operand = *GEP.idx_begin();
963 if (isa<ConstantInt>(Operand)) {
964 // The byte offset wraps at the width of the GEP index type.
965 const DataLayout &DL = CurrF->getDataLayout();
966 APInt Offset(DL.getIndexSizeInBits(GEP.getPointerAddressSpace()), 0);
967 [[maybe_unused]] bool IsConstant = GEP.accumulateConstantOffset(DL, Offset);
968 assert(IsConstant && "a constant index must give a constant offset");
969 return walkLogicalAccessChainConstant(CurType, Offset.getZExtValue(),
970 OnLiteralIndexing);
971 }
972
973 return walkLogicalAccessChainDynamic(CurType, Operand, Multiplier,
974 OnLiteralIndexing, OnDynamicIndexing);
975}
976
977void SPIRVEmitIntrinsicsImpl::recordAccessChainError(GetElementPtrInst &GEP,
978 Error Err) {
979 InvalidGEPs.insert(&GEP);
980 AccessChainErrors = joinErrors(
981 std::move(AccessChainErrors),
982 createStringError(Twine(toString(std::move(Err))) + " (in function '" +
983 GEP.getFunction()->getName() + "')"));
984}
985
986// Returns Idx truncated to IdxTy, the GEP index type, if Idx is wider. A GEP
987// uses only the low bits of a wider index, while an access chain uses all of
988// them. Both sign-extend a narrower index, so this returns Idx unchanged when
989// it is not wider.
990Value *SPIRVEmitIntrinsicsImpl::truncateGEPIndex(Value *Idx, Type *IdxTy,
991 IRBuilder<> &B) {
992 if (Idx->getType()->getScalarSizeInBits() <= IdxTy->getScalarSizeInBits())
993 return Idx;
994 Value *Trunc = B.CreateTrunc(Idx, IdxTy);
995 if (auto *TruncI = dyn_cast<Instruction>(Trunc))
996 insertAssignTypeIntrs(TruncI, B);
997 return Trunc;
998}
999
1000Instruction *SPIRVEmitIntrinsicsImpl::buildLogicalAccessChainFromGEP(
1001 GetElementPtrInst &GEP) {
1002 if (InvalidGEPs.contains(&GEP))
1003 return nullptr;
1004
1005 auto &DL = CurrF->getDataLayout();
1006 IRBuilder<> B(GEP.getParent());
1007 B.SetInsertPoint(&GEP);
1008
1009 std::vector<Value *> Indices;
1010 Indices.push_back(ConstantInt::get(
1011 IntegerType::getInt32Ty(CurrF->getContext()), 0, /* Signed= */ false));
1012 Type *IdxTy = DL.getIndexType(GEP.getPointerOperandType());
1013 auto Result = walkLogicalAccessChain(
1014 GEP,
1015 [&Indices, IdxTy](Type *EltType, uint64_t Index) {
1016 Indices.push_back(ConstantInt::get(IdxTy, Index, /* Signed= */ false));
1017 },
1018 [&Indices, &B, &DL, IdxTy, this](Type *EltType, Value *Offset,
1019 uint64_t Multiplier) {
1020 Offset = truncateGEPIndex(Offset, IdxTy, B);
1021 Value *Index = nullptr;
1022 uint32_t EltTypeSize = DL.getTypeSizeInBits(EltType) / 8;
1023 assert(Multiplier != 0);
1024 if (Multiplier == EltTypeSize) {
1025 Index = Offset;
1026 } else if (EltTypeSize % Multiplier == 0) {
1027 Index =
1028 B.CreateUDiv(Offset, ConstantInt::get(Offset->getType(),
1029 EltTypeSize / Multiplier,
1030 /* Signed= */ false));
1031 } else {
1032 Index = B.CreateMul(Offset,
1033 ConstantInt::get(Offset->getType(), Multiplier,
1034 /* Signed= */ false));
1035 insertAssignTypeIntrs(cast<Instruction>(Index), B);
1036 Index = B.CreateUDiv(Index,
1037 ConstantInt::get(Offset->getType(), EltTypeSize,
1038 /* Signed= */ false));
1039 }
1040 insertAssignTypeIntrs(cast<Instruction>(Index), B);
1041 Indices.push_back(Index);
1042 });
1043 if (!Result) {
1044 recordAccessChainError(GEP, Result.takeError());
1045 return nullptr;
1046 }
1047
1048 B.SetInsertPoint(&GEP);
1049 SmallVector<Type *, 2> Types = {GEP.getType(), GEP.getOperand(0)->getType()};
1050 SmallVector<Value *, 4> Args;
1051 Args.push_back(B.getInt1(GEP.isInBounds()));
1052 Args.push_back(GEP.getOperand(0));
1053 llvm::append_range(Args, Indices);
1054 Instruction *NewI =
1055 B.CreateIntrinsicWithoutFolding(Intrinsic::spv_gep, {Types}, {Args});
1056 replaceAllUsesWithAndErase(B, &GEP, NewI);
1057 return NewI;
1058}
1059
1060Type *SPIRVEmitIntrinsicsImpl::getGEPTypeLogical(GetElementPtrInst *GEP) {
1061 if (InvalidGEPs.contains(GEP))
1062 return nullptr;
1063
1064 Type *CurType = GEP->getResultElementType();
1065
1066 auto Result = walkLogicalAccessChain(
1067 *GEP, [&CurType](Type *EltType, uint64_t Index) { CurType = EltType; },
1068 [&CurType](Type *EltType, Value *Index, uint64_t) { CurType = EltType; });
1069 if (!Result) {
1070 recordAccessChainError(*GEP, Result.takeError());
1071 return nullptr;
1072 }
1073
1074 return *Result ? GEP->getResultElementType() : CurType;
1075}
1076
1077Type *SPIRVEmitIntrinsicsImpl::getGEPType(GetElementPtrInst *Ref) {
1078 if (getByteAddressingMultiplier(Ref->getSourceElementType()) &&
1080 return getGEPTypeLogical(Ref);
1081 }
1082
1083 Type *Ty = nullptr;
1084 // TODO: not sure if GetElementPtrInst::getTypeAtIndex() does anything
1085 // useful here
1086 if (isNestedPointer(Ref->getSourceElementType())) {
1087 Ty = Ref->getSourceElementType();
1088 for (Use &U : drop_begin(Ref->indices()))
1089 Ty = GetElementPtrInst::getTypeAtIndex(Ty, U.get());
1090 } else {
1091 Ty = Ref->getResultElementType();
1092 }
1093 return Ty;
1094}
1095
1096Type *SPIRVEmitIntrinsicsImpl::deduceElementTypeHelper(
1097 Value *I, SmallPtrSetImpl<Value *> &Visited, bool UnknownElemTypeI8,
1098 bool IgnoreKnownType) {
1099 // allow to pass nullptr as an argument
1100 if (!I)
1101 return nullptr;
1102
1103 // maybe already known
1104 if (!IgnoreKnownType)
1105 if (Type *KnownTy = GR->findDeducedElementType(I))
1106 return KnownTy;
1107
1108 // maybe a cycle
1109 if (!Visited.insert(I).second)
1110 return nullptr;
1111
1112 // fallback value in case when we fail to deduce a type
1113 Type *Ty = nullptr;
1114 // look for known basic patterns of type inference
1115 if (auto *Ref = dyn_cast<AllocaInst>(I)) {
1116 maybeAssignPtrType(Ty, I, Ref->getAllocatedType(), UnknownElemTypeI8);
1117 } else if (auto *Ref = dyn_cast<GetElementPtrInst>(I)) {
1118 Ty = getGEPType(Ref);
1119 } else if (auto *SGEP = dyn_cast<StructuredGEPInst>(I)) {
1120 Ty = SGEP->getResultElementType();
1121 } else if (auto *Ref = dyn_cast<LoadInst>(I)) {
1122 Value *Op = Ref->getPointerOperand();
1123 Type *KnownTy = GR->findDeducedElementType(Op);
1124 if (!KnownTy)
1125 KnownTy = Op->getType();
1126 if (Type *ElemTy = getPointeeType(KnownTy))
1127 maybeAssignPtrType(Ty, I, ElemTy, UnknownElemTypeI8);
1128 } else if (auto *Ref = dyn_cast<GlobalValue>(I)) {
1129 if (auto *Fn = dyn_cast<Function>(Ref)) {
1130 Ty = SPIRV::getOriginalFunctionType(*Fn);
1131 GR->addDeducedElementType(I, Ty);
1132 } else {
1133 Value *Op = Ref->getNumOperands() > 0 ? Ref->getOperand(0) : nullptr;
1134 // Code lives in the program address space, not in the address space of
1135 // the global. For known SPIR-V targets, program address space 0 maps
1136 // to Function/Private, which cannot hold code, so treat it as unset.
1137 std::optional<unsigned> ProgramAS;
1139 if (unsigned AS = CurrF->getDataLayout().getProgramAddressSpace())
1140 ProgramAS = AS;
1141 else if (TM.getSubtargetImpl()->canUseExtension(
1142 SPIRV::Extension::SPV_INTEL_function_pointers))
1143 ProgramAS =
1144 storageClassToAddressSpace(SPIRV::StorageClass::CodeSectionINTEL);
1145 }
1146 Ty = deduceElementTypeByValueDeep(Ref->getValueType(), Op, Visited,
1147 UnknownElemTypeI8, ProgramAS);
1148 }
1149 } else if (auto *Ref = dyn_cast<AddrSpaceCastInst>(I)) {
1150 Type *RefTy = deduceElementTypeHelper(Ref->getPointerOperand(), Visited,
1151 UnknownElemTypeI8);
1152 maybeAssignPtrType(Ty, I, RefTy, UnknownElemTypeI8);
1153 } else if (auto *Ref = dyn_cast<IntToPtrInst>(I)) {
1154 maybeAssignPtrType(Ty, I, Ref->getDestTy(), UnknownElemTypeI8);
1155 } else if (auto *Ref = dyn_cast<BitCastInst>(I)) {
1156 if (Type *Src = Ref->getSrcTy(), *Dest = Ref->getDestTy();
1157 isPointerTy(Src) && isPointerTy(Dest))
1158 Ty = deduceElementTypeHelper(Ref->getOperand(0), Visited,
1159 UnknownElemTypeI8);
1160 } else if (auto *Ref = dyn_cast<ExtractValueInst>(I)) {
1161 // An extracted pointer has the type of its aggregate member.
1162 if (isPointerTy(I->getType()))
1164 reconstructType(Ref->getAggregateOperand(), false, false),
1165 Ref->getIndices());
1166 } else if (auto *Ref = dyn_cast<AtomicCmpXchgInst>(I)) {
1167 Value *Op = Ref->getNewValOperand();
1168 if (isPointerTy(Op->getType()))
1169 Ty = deduceElementTypeHelper(Op, Visited, UnknownElemTypeI8);
1170 } else if (auto *Ref = dyn_cast<AtomicRMWInst>(I)) {
1171 Value *Op = Ref->getValOperand();
1172 if (isPointerTy(Op->getType()))
1173 Ty = deduceElementTypeHelper(Op, Visited, UnknownElemTypeI8);
1174 } else if (auto *Ref = dyn_cast<PHINode>(I)) {
1175 Type *BestTy = nullptr;
1176 unsigned MaxN = 1;
1177 DenseMap<Type *, unsigned> PhiTys;
1178 for (int i = Ref->getNumIncomingValues() - 1; i >= 0; --i) {
1179 Ty = deduceElementTypeByUsersDeep(Ref->getIncomingValue(i), Visited,
1180 UnknownElemTypeI8);
1181 if (!Ty)
1182 continue;
1183 auto It = PhiTys.try_emplace(Ty, 1);
1184 if (!It.second) {
1185 ++It.first->second;
1186 if (It.first->second > MaxN) {
1187 MaxN = It.first->second;
1188 BestTy = Ty;
1189 }
1190 }
1191 }
1192 if (BestTy)
1193 Ty = BestTy;
1194 } else if (auto *Ref = dyn_cast<SelectInst>(I)) {
1195 for (Value *Op : {Ref->getTrueValue(), Ref->getFalseValue()}) {
1196 // A function pointer operand carries its function type directly. Other
1197 // operands are deduced from their uses.
1198 Ty = isa<Function>(Op)
1199 ? deduceElementTypeHelper(Op, Visited, UnknownElemTypeI8)
1200 : deduceElementTypeByUsersDeep(Op, Visited, UnknownElemTypeI8);
1201 if (Ty)
1202 break;
1203 }
1204 } else if (auto *CI = dyn_cast<CallInst>(I)) {
1205 static StringMap<unsigned> ResTypeByArg = {
1206 {"to_global", 0},
1207 {"to_local", 0},
1208 {"to_private", 0},
1209 {"__to_global", 0},
1210 {"__to_local", 0},
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}};
1218 // TODO: maybe improve performance by caching demangled names
1219
1220 auto *II = dyn_cast<IntrinsicInst>(I);
1221 if (II && (II->getIntrinsicID() == Intrinsic::spv_resource_getbasepointer ||
1222 II->getIntrinsicID() == Intrinsic::spv_resource_getpointer)) {
1223 auto *HandleType = cast<TargetExtType>(II->getOperand(0)->getType());
1224 if (HandleType->getTargetExtName() == "spirv.Image" ||
1225 HandleType->getTargetExtName() == "spirv.SignedImage") {
1226 for (User *U : II->users()) {
1227 Ty = cast<Instruction>(U)->getAccessType();
1228 if (Ty)
1229 break;
1230 }
1231 } else if (HandleType->getTargetExtName() == "spirv.VulkanBuffer") {
1232 // This call is supposed to index into an array
1233 Ty = HandleType->getTypeParameter(0);
1234 if (II->getIntrinsicID() == Intrinsic::spv_resource_getpointer) {
1235 if (Ty->isArrayTy())
1236 Ty = Ty->getArrayElementType();
1237 else {
1238 assert(Ty && Ty->isStructTy());
1239 uint32_t Index =
1240 cast<ConstantInt>(II->getOperand(1))->getZExtValue();
1241 Ty = cast<StructType>(Ty)->getElementType(Index);
1242 }
1243 }
1245 } else {
1246 llvm_unreachable("Unknown handle type for spv_resource_getpointer.");
1247 }
1248 } else if (II && II->getIntrinsicID() ==
1249 Intrinsic::spv_generic_cast_to_ptr_explicit) {
1250 Ty = deduceElementTypeHelper(CI->getArgOperand(0), Visited,
1251 UnknownElemTypeI8);
1252 } else if (Function *CalledF = CI->getCalledFunction()) {
1253 std::string DemangledName =
1254 getOclOrSpirvBuiltinDemangledName(CalledF->getName());
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);
1261 else if (Type *KnownRetTy = GR->findDeducedElementType(CalledF))
1262 Ty = KnownRetTy;
1263 }
1264 }
1265
1266 // remember the found relationship
1267 if (Ty && !IgnoreKnownType) {
1268 // specify nested types if needed, otherwise return unchanged
1269 GR->addDeducedElementType(I, normalizeType(Ty, CanUseAnyVectorRank));
1270 }
1271
1272 return Ty;
1273}
1274
1275// Re-create a type of the value if it has untyped pointer fields, also nested.
1276// Return the original value type if no corrections of untyped pointer
1277// information is found or needed.
1278Type *SPIRVEmitIntrinsicsImpl::deduceNestedTypeHelper(User *U,
1279 bool UnknownElemTypeI8) {
1280 SmallPtrSet<Value *, 0> Visited;
1281 return deduceNestedTypeHelper(U, U->getType(), Visited, UnknownElemTypeI8);
1282}
1283
1284Type *SPIRVEmitIntrinsicsImpl::deduceNestedTypeHelper(
1285 User *U, Type *OrigTy, SmallPtrSetImpl<Value *> &Visited,
1286 bool UnknownElemTypeI8) {
1287 // Only constant aggregate operands map to aggregate elements.
1289 return OrigTy;
1290
1291 // maybe already known
1292 if (Type *KnownTy = GR->findDeducedCompositeType(U))
1293 return KnownTy;
1294
1295 // maybe a cycle
1296 if (!Visited.insert(U).second)
1297 return OrigTy;
1298
1299 auto DeduceOpTy = [&](Value *Op, Type *OpTy) -> Type * {
1300 auto *PtrTy = dyn_cast<PointerType>(OpTy);
1301 if (!PtrTy)
1302 return deduceNestedTypeHelper(dyn_cast<User>(Op), OpTy, Visited,
1303 UnknownElemTypeI8);
1304 // A uniqued null carries the pointee an earlier user gave it.
1306 return OpTy;
1307 if (Type *NestedTy =
1308 deduceElementTypeHelper(Op, Visited, UnknownElemTypeI8))
1309 return getTypedPointerWrapper(NestedTy, PtrTy->getAddressSpace());
1310 return OpTy;
1311 };
1312
1313 if (auto *OrigStructTy = dyn_cast<StructType>(OrigTy)) {
1315 bool Change = false;
1316 for (unsigned i = 0; i < U->getNumOperands(); ++i) {
1317 Value *Op = U->getOperand(i);
1318 assert(Op && "Operands should not be null.");
1319 Type *OpTy = Op->getType();
1320 Type *Ty = DeduceOpTy(Op, OpTy);
1321 Tys.push_back(Ty);
1322 Change |= Ty != OpTy;
1323 }
1324 if (Change) {
1325 Type *NewTy = StructType::create(
1326 Tys, OrigStructTy->isLiteral() ? "" : OrigStructTy->getName(),
1327 OrigStructTy->isPacked());
1328 GR->addDeducedCompositeType(U, NewTy);
1329 return NewTy;
1330 }
1331 } else if (auto *ArrTy = dyn_cast<ArrayType>(OrigTy)) {
1332 for (Value *Op : U->operands()) {
1333 Type *OpTy = ArrTy->getElementType();
1334 Type *Ty = DeduceOpTy(Op, OpTy);
1335 if (Ty != OpTy) {
1336 Type *NewTy = ArrayType::get(Ty, ArrTy->getNumElements());
1337 GR->addDeducedCompositeType(U, NewTy);
1338 return NewTy;
1339 }
1340 }
1341 } else if (auto *VecTy = dyn_cast<VectorType>(OrigTy)) {
1342 for (Value *Op : U->operands()) {
1343 Type *OpTy = VecTy->getElementType();
1344 Type *Ty = DeduceOpTy(Op, OpTy);
1345 if (Ty != OpTy) {
1346 Type *NewTy = VectorType::get(Ty, VecTy->getElementCount());
1348 normalizeType(NewTy, CanUseAnyVectorRank));
1349 return NewTy;
1350 }
1351 }
1352 }
1353
1354 return OrigTy;
1355}
1356
1357Type *SPIRVEmitIntrinsicsImpl::deduceElementType(Value *I,
1358 bool UnknownElemTypeI8) {
1359 if (Type *Ty = deduceElementTypeHelper(I, UnknownElemTypeI8))
1360 return Ty;
1361 if (!UnknownElemTypeI8)
1362 return nullptr;
1363 insertTodoType(I);
1364 return IntegerType::getInt8Ty(I->getContext());
1365}
1366
1368 Value *PointerOperand) {
1369 Type *PointeeTy = GR->findDeducedElementType(PointerOperand);
1370 if (PointeeTy && !isUntypedPointerTy(PointeeTy))
1371 return nullptr;
1372 auto *PtrTy = dyn_cast<PointerType>(I->getType());
1373 if (!PtrTy)
1374 return I->getType();
1375 if (Type *NestedTy = GR->findDeducedElementType(I))
1376 return getTypedPointerWrapper(NestedTy, PtrTy->getAddressSpace());
1377 return nullptr;
1378}
1379
1380// Try to deduce element type for a call base. Returns false if this is an
1381// indirect function invocation, and true otherwise.
1382bool SPIRVEmitIntrinsicsImpl::deduceOperandElementTypeCalledFunction(
1383 CallInst *CI, SmallVector<std::pair<Value *, unsigned>> &Ops,
1384 Type *&KnownElemTy, bool &Incomplete) {
1385 Function *CalledF = CI->getCalledFunction();
1386 if (!CalledF)
1387 return false;
1388 std::string DemangledName =
1390 if (DemangledName.length() > 0 &&
1391 !StringRef(DemangledName).starts_with("llvm.")) {
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) {
1397 Value *Op = CI->getArgOperand(i);
1398 if (!isPointerTy(Op->getType()))
1399 continue;
1400 ++PtrCnt;
1401 if (Type *ElemTy = GR->findDeducedElementType(Op))
1402 KnownElemTy = ElemTy; // src will rewrite dest if both are defined
1403 Ops.push_back(std::make_pair(Op, i));
1404 }
1405 } else if (Grp == SPIRV::Atomic || Grp == SPIRV::AtomicFloating) {
1406 if (CI->arg_size() == 0)
1407 return true;
1408 Value *Op = CI->getArgOperand(0);
1409 if (!isPointerTy(Op->getType()))
1410 return true;
1411 switch (Opcode) {
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: {
1428 KnownElemTy = isPointerTy(CI->getType()) ? getAtomicElemTy(GR, CI, Op)
1429 : CI->getType();
1430 if (!KnownElemTy)
1431 return true;
1432 Incomplete = isTodoType(Op);
1433 Ops.push_back(std::make_pair(Op, 0));
1434 } break;
1435 case SPIRV::OpAtomicStore: {
1436 if (CI->arg_size() < 4)
1437 return true;
1438 Value *ValOp = CI->getArgOperand(3);
1439 KnownElemTy = isPointerTy(ValOp->getType())
1440 ? getAtomicElemTy(GR, CI, Op)
1441 : ValOp->getType();
1442 if (!KnownElemTy)
1443 return true;
1444 Incomplete = isTodoType(Op);
1445 Ops.push_back(std::make_pair(Op, 0));
1446 } break;
1447 }
1448 }
1449 }
1450 return true;
1451}
1452
1453// Try to deduce element type for a function pointer.
1454void SPIRVEmitIntrinsicsImpl::deduceOperandElementTypeFunctionPointer(
1455 CallInst *CI, SmallVector<std::pair<Value *, unsigned>> &Ops,
1456 Type *&KnownElemTy, bool IsPostprocessing) {
1457 Value *Op = CI->getCalledOperand();
1458 if (!Op || !isPointerTy(Op->getType()))
1459 return;
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;
1464 for (auto &&[ParmIdx, Arg] : llvm::enumerate(CI->args())) {
1465 Type *ArgTy = Arg->getType();
1466 if (ArgTy->isPointerTy()) {
1467 if (Type *ElemTy = GR->findDeducedElementType(Arg)) {
1468 IsNewFTy = true;
1469 ArgTy = getTypedPointerWrapper(ElemTy, getPointerAddressSpace(ArgTy));
1470 if (isTodoType(Arg))
1471 IsIncomplete = true;
1472 } else {
1473 IsIncomplete = true;
1474 }
1475 } else {
1476 ArgTy = FTy->getFunctionParamType(ParmIdx);
1477 }
1478 ArgTys.push_back(ArgTy);
1479 }
1480 Type *RetTy = FTy->getReturnType();
1481 if (CI->getType()->isPointerTy()) {
1482 if (Type *ElemTy = GR->findDeducedElementType(CI)) {
1483 IsNewFTy = true;
1484 RetTy =
1486 if (isTodoType(CI))
1487 IsIncomplete = true;
1488 } else {
1489 IsIncomplete = true;
1490 }
1491 }
1492 if (!IsPostprocessing && IsIncomplete)
1493 insertTodoType(Op);
1494 KnownElemTy =
1495 IsNewFTy ? FunctionType::get(RetTy, ArgTys, FTy->isVarArg()) : FTy;
1496}
1497
1498bool SPIRVEmitIntrinsicsImpl::deduceOperandElementTypeFunctionRet(
1499 Instruction *I, SmallPtrSetImpl<Instruction *> *IncompleteRets,
1500 const SmallPtrSetImpl<Value *> *AskOps, bool IsPostprocessing,
1501 Type *&KnownElemTy, Value *Op, Function *F) {
1502 KnownElemTy = GR->findDeducedElementType(F);
1503 if (KnownElemTy)
1504 return false;
1505 if (Type *OpElemTy = GR->findDeducedElementType(Op)) {
1506 OpElemTy = normalizeType(OpElemTy, CanUseAnyVectorRank);
1507 GR->addDeducedElementType(F, OpElemTy);
1508 GR->addReturnType(
1509 F, TypedPointerType::get(OpElemTy,
1510 getPointerAddressSpace(F->getReturnType())));
1511 // non-recursive update of types in function uses
1512 DenseSet<std::pair<Value *, Value *>> VisitedSubst{std::make_pair(I, Op)};
1513 for (User *U : F->users()) {
1514 CallInst *CI = dyn_cast<CallInst>(U);
1515 if (!CI || CI->getCalledFunction() != F)
1516 continue;
1517 if (CallInst *AssignCI = GR->findAssignPtrTypeInstr(CI)) {
1518 if (Type *PrevElemTy = GR->findDeducedElementType(CI)) {
1519 GR->updateAssignType(
1520 AssignCI, CI,
1521 getNormalizedPoisonValue(OpElemTy, CanUseAnyVectorRank));
1522 propagateElemType(CI, PrevElemTy, VisitedSubst);
1523 }
1524 }
1525 }
1526 // Non-recursive update of types in the function uncomplete returns.
1527 // This may happen just once per a function, the latch is a pair of
1528 // findDeducedElementType(F) / addDeducedElementType(F, ...).
1529 // With or without the latch it is a non-recursive call due to
1530 // IncompleteRets set to nullptr in this call.
1531 if (IncompleteRets)
1532 for (Instruction *IncompleteRetI : *IncompleteRets)
1533 deduceOperandElementType(IncompleteRetI, nullptr, AskOps,
1534 IsPostprocessing);
1535 } else if (IncompleteRets) {
1536 IncompleteRets->insert(I);
1537 }
1538 TypeValidated.insert(I);
1539 return true;
1540}
1541
1542// If the Instruction has Pointer operands with unresolved types, this function
1543// tries to deduce them. If the Instruction has Pointer operands with known
1544// types which differ from expected, this function tries to insert a bitcast to
1545// resolve the issue.
1546void SPIRVEmitIntrinsicsImpl::deduceOperandElementType(
1547 Instruction *I, SmallPtrSetImpl<Instruction *> *IncompleteRets,
1548 const SmallPtrSetImpl<Value *> *AskOps, bool IsPostprocessing) {
1550 Type *KnownElemTy = nullptr;
1551 bool Incomplete = false;
1552 // look for known basic patterns of type inference
1553 if (auto *Ref = dyn_cast<PHINode>(I)) {
1554 if (!isPointerTy(I->getType()) ||
1555 !(KnownElemTy = GR->findDeducedElementType(I)))
1556 return;
1557 Incomplete = isTodoType(I);
1558 for (unsigned i = 0; i < Ref->getNumIncomingValues(); i++) {
1559 Value *Op = Ref->getIncomingValue(i);
1560 if (isPointerTy(Op->getType()))
1561 Ops.push_back(std::make_pair(Op, i));
1562 }
1563 } else if (auto *Ref = dyn_cast<AddrSpaceCastInst>(I)) {
1564 KnownElemTy = GR->findDeducedElementType(I);
1565 if (!KnownElemTy)
1566 return;
1567 Incomplete = isTodoType(I);
1568 Ops.push_back(std::make_pair(Ref->getPointerOperand(), 0));
1569 } else if (auto *Ref = dyn_cast<BitCastInst>(I)) {
1570 if (!isPointerTy(I->getType()))
1571 return;
1572 KnownElemTy = GR->findDeducedElementType(I);
1573 if (!KnownElemTy)
1574 return;
1575 Incomplete = isTodoType(I);
1576 Ops.push_back(std::make_pair(Ref->getOperand(0), 0));
1577 } else if (auto *Ref = dyn_cast<GetElementPtrInst>(I)) {
1578 if (GR->findDeducedElementType(Ref->getPointerOperand()))
1579 return;
1580 KnownElemTy = Ref->getSourceElementType();
1581 Ops.push_back(std::make_pair(Ref->getPointerOperand(),
1583 } else if (auto *Ref = dyn_cast<StructuredGEPInst>(I)) {
1584 if (GR->findDeducedElementType(Ref->getPointerOperand()))
1585 return;
1586 KnownElemTy = Ref->getBaseType();
1587 Ops.push_back(std::make_pair(Ref->getPointerOperand(),
1589 } else if (auto *Ref = dyn_cast<LoadInst>(I)) {
1590 KnownElemTy = I->getType();
1591 if (isUntypedPointerTy(KnownElemTy)) {
1592 // A T** loaded back from its alloca comes out opaque, dropping type info.
1593 // When the load is a pointer-to-pointer, type the alloca as that pointer.
1594 Type *LoadedElemTy = GR->findDeducedElementType(I);
1595 if (!LoadedElemTy || !isPointerTyOrWrapper(LoadedElemTy))
1596 return;
1597 Value *Root = Ref->getPointerOperand()->stripPointerCasts();
1598 if (!isa<AllocaInst>(Root))
1599 return;
1600 KnownElemTy = getTypedPointerWrapper(LoadedElemTy,
1601 getPointerAddressSpace(KnownElemTy));
1602 }
1603 Type *PointeeTy = GR->findDeducedElementType(Ref->getPointerOperand());
1604 if (PointeeTy && !isUntypedPointerTy(PointeeTy))
1605 return;
1606 Ops.push_back(std::make_pair(Ref->getPointerOperand(),
1608 } else if (auto *Ref = dyn_cast<StoreInst>(I)) {
1609 if (!(KnownElemTy =
1610 reconstructType(Ref->getValueOperand(), false, IsPostprocessing)))
1611 return;
1612 Type *PointeeTy = GR->findDeducedElementType(Ref->getPointerOperand());
1613 if (PointeeTy && !isUntypedPointerTy(PointeeTy))
1614 return;
1615 Ops.push_back(std::make_pair(Ref->getPointerOperand(),
1617 } else if (auto *Ref = dyn_cast<AtomicCmpXchgInst>(I)) {
1618 KnownElemTy = isPointerTy(I->getType())
1619 ? getAtomicElemTy(GR, I, Ref->getPointerOperand())
1620 : I->getType();
1621 if (!KnownElemTy)
1622 return;
1623 Incomplete = isTodoType(Ref->getPointerOperand());
1624 Ops.push_back(std::make_pair(Ref->getPointerOperand(),
1626 } else if (auto *Ref = dyn_cast<AtomicRMWInst>(I)) {
1627 KnownElemTy = isPointerTy(I->getType())
1628 ? getAtomicElemTy(GR, I, Ref->getPointerOperand())
1629 : I->getType();
1630 if (!KnownElemTy)
1631 return;
1632 Incomplete = isTodoType(Ref->getPointerOperand());
1633 Ops.push_back(std::make_pair(Ref->getPointerOperand(),
1635 } else if (auto *Ref = dyn_cast<SelectInst>(I)) {
1636 if (!isPointerTy(I->getType()) ||
1637 !(KnownElemTy = GR->findDeducedElementType(I)))
1638 return;
1639 Incomplete = isTodoType(I);
1640 for (unsigned i = 0; i < Ref->getNumOperands(); i++) {
1641 Value *Op = Ref->getOperand(i);
1642 if (isPointerTy(Op->getType()))
1643 Ops.push_back(std::make_pair(Op, i));
1644 }
1645 } else if (auto *Ref = dyn_cast<ReturnInst>(I)) {
1646 if (!isPointerTy(CurrF->getReturnType()))
1647 return;
1648 Value *Op = Ref->getReturnValue();
1649 if (!Op)
1650 return;
1651 if (deduceOperandElementTypeFunctionRet(I, IncompleteRets, AskOps,
1652 IsPostprocessing, KnownElemTy, Op,
1653 CurrF))
1654 return;
1655 Incomplete = isTodoType(CurrF);
1656 Ops.push_back(std::make_pair(Op, 0));
1657 } else if (auto *Ref = dyn_cast<ICmpInst>(I)) {
1658 if (!isPointerTy(Ref->getOperand(0)->getType()))
1659 return;
1660 Value *Op0 = Ref->getOperand(0);
1661 Value *Op1 = Ref->getOperand(1);
1662 bool Incomplete0 = isTodoType(Op0);
1663 bool Incomplete1 = isTodoType(Op1);
1664 Type *ElemTy1 = GR->findDeducedElementType(Op1);
1665 Type *ElemTy0 = (Incomplete0 && !Incomplete1 && ElemTy1)
1666 ? nullptr
1667 : GR->findDeducedElementType(Op0);
1668 if (ElemTy0) {
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));
1676 }
1677 } else if (CallInst *CI = dyn_cast<CallInst>(I)) {
1678 if (!CI->isIndirectCall())
1679 deduceOperandElementTypeCalledFunction(CI, Ops, KnownElemTy, Incomplete);
1680 else if (HaveFunPtrs)
1681 deduceOperandElementTypeFunctionPointer(CI, Ops, KnownElemTy,
1682 IsPostprocessing);
1683 }
1684
1685 // There is no enough info to deduce types or all is valid.
1686 if (!KnownElemTy || Ops.size() == 0)
1687 return;
1688
1689 IRBuilder<> B(*CurrF->getParent());
1690 for (auto &OpIt : Ops) {
1691 Value *Op = OpIt.first;
1692 if (AskOps && !AskOps->contains(Op))
1693 continue;
1694 Type *AskTy = nullptr;
1695 CallInst *AskCI = nullptr;
1696 if (IsPostprocessing && AskOps) {
1697 AskTy = GR->findDeducedElementType(Op);
1698 AskCI = GR->findAssignPtrTypeInstr(Op);
1699 assert(AskTy && AskCI);
1700 }
1701 Type *Ty = AskTy ? AskTy : GR->findDeducedElementType(Op);
1702 if (Ty == KnownElemTy)
1703 continue;
1704 Value *OpTyVal = getNormalizedPoisonValue(KnownElemTy, CanUseAnyVectorRank);
1705 Type *OpTy = Op->getType();
1706 // Do not let a non-pointer element type clobber an already-deduced pointer
1707 // element type for the same operand.
1708 bool WouldClobberPtrWithNonPtr = Ty && isPointerTyOrWrapper(Ty) &&
1709 !isPointerTyOrWrapper(KnownElemTy) &&
1711 if (Op->hasUseList() && !WouldClobberPtrWithNonPtr &&
1712 (!Ty || AskTy || isUntypedPointerTy(Ty) || isTodoType(Op))) {
1713 Type *PrevElemTy = GR->findDeducedElementType(Op);
1715 Op, normalizeType(KnownElemTy, CanUseAnyVectorRank));
1716 // check if KnownElemTy is complete
1717 if (!Incomplete)
1718 eraseTodoType(Op);
1719 else if (!IsPostprocessing)
1720 insertTodoType(Op);
1721 // check if there is existing Intrinsic::spv_assign_ptr_type instruction
1722 CallInst *AssignCI = AskCI ? AskCI : GR->findAssignPtrTypeInstr(Op);
1723 if (AssignCI == nullptr) {
1724 Instruction *User = dyn_cast<Instruction>(Op->use_begin()->get());
1725 setInsertPointSkippingPhis(B, User ? User->getNextNode() : I);
1726 CallInst *CI =
1727 buildIntrWithMD(Intrinsic::spv_assign_ptr_type, {OpTy}, OpTyVal, Op,
1728 {B.getInt32(getPointerAddressSpace(OpTy))}, B);
1729 GR->addAssignPtrTypeInstr(Op, CI);
1730 } else {
1731 GR->updateAssignType(AssignCI, Op, OpTyVal);
1732 DenseSet<std::pair<Value *, Value *>> VisitedSubst{
1733 std::make_pair(I, Op)};
1734 propagateElemTypeRec(Op, KnownElemTy, PrevElemTy, VisitedSubst);
1735 // A PHI or select validated its operands against its previous element
1736 // type. Null constants have no use list and are not revisited by
1737 // postprocessing, so validate the operands against the new type.
1738 if (auto *OpI = dyn_cast<Instruction>(Op);
1739 OpI && (isa<PHINode>(OpI) || isa<SelectInst>(OpI)) &&
1740 TypeValidated.contains(OpI))
1741 RetypedToRevalidate.push_back(OpI);
1742 }
1743 } else {
1744 eraseTodoType(Op);
1745 CallInst *PtrCastI =
1746 buildSpvPtrcast(I->getParent()->getParent(), Op, KnownElemTy);
1747 if (OpIt.second == std::numeric_limits<unsigned>::max())
1748 dyn_cast<CallInst>(I)->setCalledOperand(PtrCastI);
1749 else
1750 I->setOperand(OpIt.second, PtrCastI);
1751 }
1752 }
1753 TypeValidated.insert(I);
1754
1755 // Revalidating one PHI can retype the next one in a chain. Use a worklist
1756 // rather than recursion, as such chains can be long.
1757 if (RevalidatingRetyped)
1758 return;
1759 RevalidatingRetyped = true;
1760 while (!RetypedToRevalidate.empty())
1761 deduceOperandElementType(RetypedToRevalidate.pop_back_val(), nullptr,
1762 nullptr, IsPostprocessing);
1763 RevalidatingRetyped = false;
1764}
1765
1766void SPIRVEmitIntrinsicsImpl::replaceMemInstrUses(Instruction *Old,
1767 Instruction *New,
1768 IRBuilder<> &B) {
1769 while (!Old->user_empty()) {
1770 auto *U = Old->user_back();
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);
1776 GR->addAssignPtrTypeInstr(New, AssignCI);
1777 U->eraseFromParent();
1778 } else if (isMemInstrToReplace(U) || isa<ReturnInst>(U) ||
1779 isa<CallInst>(U)) {
1780 U->replaceUsesOfWith(Old, New);
1781 // For a `llvm.spv.abort` call whose composite message argument was
1782 // rewritten to a value-id (i32), also retarget the call to a matching
1783 // intrinsic declaration so the IR verifier is satisfied. The SPIR-V
1784 // type of the value is tracked via the GlobalRegistry, so the selector
1785 // still emits OpAbortKHR with the original composite type.
1786 if (auto *CI = dyn_cast<CallInst>(U);
1787 CI && CI->getIntrinsicID() == Intrinsic::spv_abort) {
1788 Type *NewArgTy = New->getType();
1789 Type *ExpectedArgTy = CI->getFunctionType()->getParamType(0);
1790 if (NewArgTy != ExpectedArgTy) {
1791 Module *M = CI->getModule();
1793 M, Intrinsic::spv_abort, {NewArgTy});
1794 CI->setCalledFunction(NewF);
1795 }
1796 }
1797 } else if (isa<PHINode>(U) || isa<SelectInst>(U) || isa<FreezeInst>(U)) {
1798 // Aggregate-typed PHIs, selects and freezes have already been mutated to
1799 // the i32 value-id type up front in runOnFunction, so only the operand
1800 // needs replacing here; their extractvalue users are lowered to
1801 // spv_extractv by visitExtractValueInst.
1802 assert(U->getType() == New->getType() &&
1803 "aggregate PHI/select/freeze should have been mutated to value-id "
1804 "type");
1805 U->replaceUsesOfWith(Old, New);
1806 } else {
1807 llvm_unreachable("illegal aggregate intrinsic user");
1808 }
1809 }
1810 New->copyMetadata(*Old);
1811 GR->removeAssignPtrTypeInstr(Old); // Old's address could be re-used.
1812 TypeValidated.erase(Old);
1813 Old->eraseFromParent();
1814}
1815
1816// Lower a poison or undef Op to its placeholder intrinsic.
1817Value *SPIRVEmitIntrinsicsImpl::lowerUndefOrPoison(Value *Op, IRBuilder<> &B,
1818 bool HasPoisonExt) {
1819 auto *UV = dyn_cast<UndefValue>(Op);
1820 if (!UV)
1821 return nullptr;
1822
1823 bool AsPoison = HasPoisonExt && isa<PoisonValue>(UV);
1824 if (isa<PoisonValue>(UV) && !HasPoisonExt)
1825 LLVM_DEBUG(dbgs() << "SPV_KHR_poison_freeze is not enabled. Poison is "
1826 "lowered as undef\n");
1827
1828 Intrinsic::ID IID = AsPoison ? Intrinsic::spv_poison : Intrinsic::spv_undef;
1829 Type *Ty = UV->getType();
1830
1831 // Aggregates use an i32-result placeholder with the real type kept in
1832 // AggrConstTypes and scalar poison uses a type-overloaded one.
1833 if (Ty->isAggregateType()) {
1834 auto *Call =
1835 AsPoison ? B.CreateIntrinsicWithoutFolding(IID, {B.getInt32Ty()}, {})
1836 : B.CreateIntrinsicWithoutFolding(IID, {});
1837 AggrConsts[Call] = UV;
1838 AggrConstTypes[Call] = Ty;
1839 return Call;
1840 }
1841
1842 if (AsPoison)
1843 return B.CreateIntrinsic(IID, {Ty}, {});
1844 return nullptr;
1845}
1846
1847// Replace aggregate undef or poison operands and extension-enabled scalar
1848// poison operands with placeholder intrinsics. Scalar undef is left as is. See
1849// lowerUndefOrPoison.
1850void SPIRVEmitIntrinsicsImpl::preprocessUndefsAndPoisons(IRBuilder<> &B) {
1851 const SPIRVSubtarget *STI = TM.getSubtargetImpl(*CurrF);
1852 bool HasPoisonExt =
1853 STI->canUseExtension(SPIRV::Extension::SPV_KHR_poison_freeze);
1854
1855 SmallVector<Instruction *, 16> Insts;
1856 for (auto &I : instructions(CurrF))
1857 Insts.push_back(&I);
1858
1859 for (Instruction *I : Insts) {
1860 bool BPrepared = false;
1861 auto *Phi = dyn_cast<PHINode>(I);
1862 for (unsigned Idx = 0; Idx < I->getNumOperands(); ++Idx) {
1863 Value *Op = I->getOperand(Idx);
1864 if (!isa<UndefValue>(Op) || Op->getType()->isMetadataTy())
1865 continue;
1866 bool IsScalar = !Op->getType()->isAggregateType();
1867 bool AsPoison = HasPoisonExt && isa<PoisonValue>(Op);
1868 // Scalar undef or extensionless scalar poison is directly translatable.
1869 if (IsScalar && !AsPoison)
1870 continue;
1871 // Scalar poison in a phi materializes in the incoming block. Everything
1872 // else materializes right before I.
1873 if (IsScalar && Phi)
1874 B.SetInsertPoint(Phi->getIncomingBlock(Idx)->getTerminator());
1875 else if (!BPrepared) {
1877 BPrepared = true;
1878 }
1879 if (Value *Repl = lowerUndefOrPoison(Op, B, HasPoisonExt))
1880 I->setOperand(Idx, Repl);
1881 }
1882 }
1883}
1884
1885// Simplify addrspacecast(null) instructions to ConstantPointerNull of the
1886// target type. Casting null always yields null, and this avoids SPIR-V
1887// lowering issues where the null gets typed as an integer instead of a
1888// pointer.
1889void SPIRVEmitIntrinsicsImpl::simplifyNullAddrSpaceCasts() {
1890 for (Instruction &I : make_early_inc_range(instructions(CurrF)))
1891 if (auto *ASC = dyn_cast<AddrSpaceCastInst>(&I))
1892 if (isa<ConstantPointerNull>(ASC->getPointerOperand())) {
1893 ASC->replaceAllUsesWith(
1895 ASC->eraseFromParent();
1896 }
1897}
1898
1899// True for an aggregate value the legalizer splits into a multi-result op
1900// (with.overflow -> G_UADDO, frexp/sincos/modf -> G_FFREXP/...). These keep a
1901// genuine multi-register result; all other aggregates become a single value-id.
1903 if (!V->getType()->isAggregateType())
1904 return false;
1905 return isa<IntrinsicInst>(V) && !isSpvIntrinsic(V);
1906}
1907
1908// True for an aggregate PHI/select/freeze, which is lowered to a single
1909// value-id.
1911 return (isa<PHINode>(I) || isa<SelectInst>(I) || isa<FreezeInst>(I)) &&
1912 I.getType()->isAggregateType();
1913}
1914
1915// Give each multi-register aggregate arm of an aggregate PHI/select/freeze a
1916// single value-id by reassembling it with extractvalue + insertvalue, so the
1917// arm matches the result once it is mutated to a value-id.
1918void SPIRVEmitIntrinsicsImpl::insertCompositeAggregateArms(Instruction *I,
1919 IRBuilder<> &B) {
1920 auto *Phi = dyn_cast<PHINode>(I);
1921 // A switch can list an incoming block twice, and both entries need the same
1922 // value, so build one chain per block.
1923 SmallDenseMap<BasicBlock *, Value *> PhiArms;
1924 for (Use &U : I->operands()) {
1925 Value *Op = U.get();
1927 continue;
1928 if (Value *Arm = Phi ? PhiArms.lookup(Phi->getIncomingBlock(U)) : nullptr) {
1929 U.set(Arm);
1930 continue;
1931 }
1932 // A PHI arm materializes in its incoming block, everything else after the
1933 // producer.
1934 if (Phi)
1935 B.SetInsertPoint(Phi->getIncomingBlock(U)->getTerminator());
1936 else
1938 auto *AggrTy = cast<StructType>(Op->getType());
1939 Value *Composite = PoisonValue::get(AggrTy);
1940 for (unsigned Idx = 0, E = AggrTy->getNumElements(); Idx != E; ++Idx) {
1941 Value *Field = B.CreateExtractValue(Op, Idx);
1942 Composite = B.CreateInsertValue(Composite, Field, Idx);
1943 }
1944 U.set(Composite);
1945 if (Phi)
1946 PhiArms[Phi->getIncomingBlock(U)] = Composite;
1947 }
1948}
1949
1950// Lower a constant aggregate member to null in the target address space
1951// if it's `addrspacecast(null)`, and nested `undef/poison` because they're
1952// missed in `preprocessUndefsAndPoisons()`.
1953Value *SPIRVEmitIntrinsicsImpl::lowerCompositeMember(Value *Op, IRBuilder<> &B,
1954 bool HasPoisonExt) {
1955 if (auto *CE = dyn_cast<ConstantExpr>(Op);
1956 CE && CE->getOpcode() == Instruction::AddrSpaceCast &&
1957 isa<ConstantPointerNull>(CE->getOperand(0)))
1958 return ConstantPointerNull::get(cast<PointerType>(CE->getType()));
1959 if (isa<UndefValue>(Op))
1960 if (Value *Repl = lowerUndefOrPoison(Op, B, HasPoisonExt))
1961 return Repl;
1962 return Op;
1963}
1964
1965void SPIRVEmitIntrinsicsImpl::preprocessCompositeConstants(IRBuilder<> &B) {
1966 const SPIRVSubtarget *STI = TM.getSubtargetImpl(*CurrF);
1967 bool HasPoisonExt =
1968 STI->canUseExtension(SPIRV::Extension::SPV_KHR_poison_freeze);
1969 std::queue<Instruction *> Worklist;
1970 for (auto &I : instructions(CurrF))
1971 Worklist.push(&I);
1972
1973 while (!Worklist.empty()) {
1974 auto *I = Worklist.front();
1975 bool IsPhi = isa<PHINode>(I), BPrepared = false;
1976 assert(I);
1977 bool KeepInst = false;
1978 for (const auto &Op : I->operands()) {
1979 Constant *AggrConst = nullptr;
1980 Type *ResTy = nullptr;
1981 if (auto *COp = dyn_cast<ConstantVector>(Op)) {
1982 AggrConst = COp;
1983 ResTy = COp->getType();
1984 } else if (auto *COp = dyn_cast<ConstantArray>(Op)) {
1985 AggrConst = COp;
1986 ResTy = B.getInt32Ty();
1987 } else if (auto *COp = dyn_cast<ConstantStruct>(Op)) {
1988 AggrConst = COp;
1989 ResTy = B.getInt32Ty();
1990 } else if (auto *COp = dyn_cast<ConstantDataArray>(Op)) {
1991 AggrConst = COp;
1992 ResTy = B.getInt32Ty();
1993 } else if (auto *COp = dyn_cast<ConstantAggregateZero>(Op)) {
1994 AggrConst = COp;
1995 ResTy = Op->getType()->isVectorTy() ? COp->getType() : B.getInt32Ty();
1996 }
1997 if (AggrConst) {
1998 auto PrepareInsert = [&]() {
1999 if (BPrepared)
2000 return;
2001 IsPhi ? B.SetInsertPointPastAllocas(I->getParent()->getParent())
2002 : B.SetInsertPoint(I);
2003 BPrepared = true;
2004 };
2005 PrepareInsert();
2006 Type *DeducedTy = deduceNestedTypeHelper(AggrConst, false);
2007 // Users other than an intrinsic or extractvalue expect the LLVM type.
2008 // Rebuild the constant as an insert chain, which casts each member
2009 // to it.
2010 if (DeducedTy != AggrConst->getType() &&
2012 bool IsVector = AggrConst->getType()->isVectorTy();
2013 Value *Composite = PoisonValue::get(AggrConst->getType());
2014 for (unsigned Idx = 0, E = AggrConst->getNumOperands(); Idx != E;
2015 ++Idx) {
2016 Value *Member = AggrConst->getOperand(Idx);
2017 // Lowered undef/poison is an i32 placeholder, so it is set after
2018 // Create, which checks the types.
2019 Value *LoweredBase =
2020 lowerCompositeMember(Composite, B, HasPoisonExt);
2021 Value *LoweredMember =
2022 lowerCompositeMember(Member, B, HasPoisonExt);
2024 if (IsVector)
2026 Composite, Member, B.getInt32(Idx), "", B.GetInsertPoint());
2027 else
2028 Insert = InsertValueInst::Create(Composite, Member, Idx, "",
2029 B.GetInsertPoint());
2030 Insert->setOperand(0, LoweredBase);
2031 Insert->setOperand(1, LoweredMember);
2032 Worklist.push(Insert);
2033 Composite = Insert;
2034 }
2035 I->replaceUsesOfWith(Op, Composite);
2036 KeepInst = true;
2037 continue;
2038 }
2040 if (auto *COp = dyn_cast<ConstantDataSequential>(Op))
2041 for (unsigned i = 0; i < COp->getNumElements(); ++i)
2042 Args.push_back(COp->getElementAsConstant(i));
2043 else
2044 for (Value *Op : AggrConst->operands())
2045 Args.push_back(lowerCompositeMember(Op, B, HasPoisonExt));
2046 auto *CI = B.CreateIntrinsicWithoutFolding(
2047 Intrinsic::spv_const_composite, {ResTy}, {Args});
2048 Worklist.push(CI);
2049 I->replaceUsesOfWith(Op, CI);
2050 KeepInst = true;
2051 AggrConsts[CI] = AggrConst;
2052 AggrConstTypes[CI] = DeducedTy;
2053 }
2054 }
2055 if (!KeepInst)
2056 Worklist.pop();
2057 }
2058}
2059
2061 IRBuilder<> &B) {
2062 LLVMContext &Ctx = I->getContext();
2064 B.CreateIntrinsic(Intrinsic::spv_assign_decoration, {I->getType()},
2065 {I, MetadataAsValue::get(Ctx, MDNode::get(Ctx, {Node}))});
2066}
2067
2069 unsigned RoundingModeDeco,
2070 IRBuilder<> &B) {
2071 LLVMContext &Ctx = I->getContext();
2072 Type *Int32Ty = Type::getInt32Ty(Ctx);
2073 MDNode *RoundingModeNode = MDNode::get(
2074 Ctx,
2076 ConstantInt::get(Int32Ty, SPIRV::Decoration::FPRoundingMode)),
2077 ConstantAsMetadata::get(ConstantInt::get(Int32Ty, RoundingModeDeco))});
2078 createDecorationIntrinsic(I, RoundingModeNode, B);
2079}
2080
2082 IRBuilder<> &B) {
2083 LLVMContext &Ctx = I->getContext();
2084 Type *Int32Ty = Type::getInt32Ty(Ctx);
2085 MDNode *SaturatedConversionNode =
2086 MDNode::get(Ctx, {ConstantAsMetadata::get(ConstantInt::get(
2087 Int32Ty, SPIRV::Decoration::SaturatedConversion))});
2088 createDecorationIntrinsic(I, SaturatedConversionNode, B);
2089}
2090
2095
2096Instruction *SPIRVEmitIntrinsicsImpl::visitCallInst(CallInst &Call) {
2097 if (!Call.isInlineAsm())
2098 return &Call;
2099
2100 LLVMContext &Ctx = CurrF->getContext();
2101 // TODO: this does not retain elementtype info for memory constraints, which
2102 // in turn means that we lower them into pointers to i8, rather than
2103 // pointers to elementtype; this can be fixed during reverse translation
2104 // but we should correct it here, possibly by tweaking the function
2105 // type to take TypedPointerType args.
2106 Constant *TyC = UndefValue::get(SPIRV::getOriginalFunctionType(Call));
2107 MDString *ConstraintString =
2108 MDString::get(Ctx, SPIRV::getOriginalAsmConstraints(Call));
2110 buildMD(TyC),
2111 MetadataAsValue::get(Ctx, MDNode::get(Ctx, ConstraintString))};
2112 for (unsigned OpIdx = 0; OpIdx < Call.arg_size(); OpIdx++)
2113 Args.push_back(Call.getArgOperand(OpIdx));
2114
2116 B.SetInsertPoint(&Call);
2117 B.CreateIntrinsic(Intrinsic::spv_inline_asm, {Args});
2118 return &Call;
2119}
2120
2121// Use a tip about rounding mode to create a decoration.
2122void SPIRVEmitIntrinsicsImpl::useRoundingMode(ConstrainedFPIntrinsic *FPI,
2123 IRBuilder<> &B) {
2124 std::optional<RoundingMode> RM = FPI->getRoundingMode();
2125 if (!RM.has_value())
2126 return;
2127 unsigned RoundingModeDeco = std::numeric_limits<unsigned>::max();
2128 switch (RM.value()) {
2129 default:
2130 // ignore unknown rounding modes
2131 break;
2132 case RoundingMode::NearestTiesToEven:
2133 RoundingModeDeco = SPIRV::FPRoundingMode::FPRoundingMode::RTE;
2134 break;
2135 case RoundingMode::TowardNegative:
2136 RoundingModeDeco = SPIRV::FPRoundingMode::FPRoundingMode::RTN;
2137 break;
2138 case RoundingMode::TowardPositive:
2139 RoundingModeDeco = SPIRV::FPRoundingMode::FPRoundingMode::RTP;
2140 break;
2141 case RoundingMode::TowardZero:
2142 RoundingModeDeco = SPIRV::FPRoundingMode::FPRoundingMode::RTZ;
2143 break;
2144 case RoundingMode::Dynamic:
2145 case RoundingMode::NearestTiesToAway:
2146 // TODO: check if supported
2147 break;
2148 }
2149 if (RoundingModeDeco == std::numeric_limits<unsigned>::max())
2150 return;
2151 // Convert the tip about rounding mode into a decoration record.
2152 createRoundingModeDecoration(FPI, RoundingModeDeco, B);
2153}
2154
2155Instruction *SPIRVEmitIntrinsicsImpl::visitSwitchInst(SwitchInst &I) {
2156 BasicBlock *ParentBB = I.getParent();
2157 Function *F = ParentBB->getParent();
2158 IRBuilder<> B(ParentBB);
2159 B.SetInsertPoint(&I);
2160 SmallVector<Value *, 4> Args;
2162 Args.push_back(I.getCondition());
2163 BBCases.push_back(I.getDefaultDest());
2164 Args.push_back(BlockAddress::get(F, I.getDefaultDest()));
2165 for (auto &Case : I.cases()) {
2166 Args.push_back(Case.getCaseValue());
2167 BBCases.push_back(Case.getCaseSuccessor());
2168 Args.push_back(BlockAddress::get(F, Case.getCaseSuccessor()));
2169 }
2170 CallInst *NewI = B.CreateIntrinsicWithoutFolding(
2171 Intrinsic::spv_switch, {I.getOperand(0)->getType()}, {Args});
2172 // remove switch to avoid its unneeded and undesirable unwrap into branches
2173 // and conditions
2174 replaceAllUsesWith(&I, NewI);
2175 I.eraseFromParent();
2176 // insert artificial and temporary instruction to preserve valid CFG,
2177 // it will be removed after IR translation pass
2178 B.SetInsertPoint(ParentBB);
2179 IndirectBrInst *BrI = B.CreateIndirectBr(
2180 Constant::getNullValue(PointerType::getUnqual(ParentBB->getContext())),
2181 BBCases.size());
2182 for (BasicBlock *BBCase : BBCases)
2183 BrI->addDestination(BBCase);
2184 return BrI;
2185}
2186
2188 return GEP->getNumIndices() > 0 && match(GEP->getOperand(1), m_Zero());
2189}
2190
2191Instruction *SPIRVEmitIntrinsicsImpl::visitIntrinsicInst(IntrinsicInst &I) {
2192 auto *SGEP = dyn_cast<StructuredGEPInst>(&I);
2193 if (!SGEP)
2194 return &I;
2195
2196 IRBuilder<> B(I.getParent());
2197 B.SetInsertPoint(&I);
2198 SmallVector<Type *, 2> Types = {I.getType(), I.getOperand(0)->getType()};
2199 SmallVector<Value *, 4> Args;
2200 Args.push_back(/* inBounds= */ B.getInt1(true));
2201 Args.push_back(I.getOperand(0));
2202 Args.push_back(/* zero index */ B.getInt32(0));
2203 for (unsigned J = 0; J < SGEP->getNumIndices(); ++J)
2204 Args.push_back(SGEP->getIndexOperand(J));
2205
2206 Instruction *NewI =
2207 B.CreateIntrinsicWithoutFolding(Intrinsic::spv_gep, Types, Args);
2208 replaceAllUsesWithAndErase(B, &I, NewI);
2209 return NewI;
2210}
2211
2213SPIRVEmitIntrinsicsImpl::visitGetElementPtrInst(GetElementPtrInst &I) {
2214 IRBuilder<> B(I.getParent());
2215 B.SetInsertPoint(&I);
2216
2217 // OpPtrAccessChain requires a scalar pointer result; scalarize per-lane
2218 // GEPs that return <N x ptr> and rebuild the vector via insertelement.
2219 if (auto *RetVTy = dyn_cast<FixedVectorType>(I.getType())) {
2220 unsigned N = RetVTy->getNumElements();
2221 Value *PtrOp = I.getPointerOperand();
2222 bool PtrIsVec = isa<VectorType>(PtrOp->getType());
2223 Type *ResultPtrTy = RetVTy->getElementType();
2224 Type *ScalarPtrTy = PtrOp->getType()->getScalarType();
2225 SmallVector<Type *, 2> GepTypes = {ResultPtrTy, ScalarPtrTy};
2226 Value *InBounds = B.getInt1(I.isInBounds());
2227 Type *LanePointeeTy = getGEPType(&I);
2228 if (!LanePointeeTy)
2229 return nullptr;
2230 Type *SrcElemTy = I.getSourceElementType();
2231
2232 // Pin the lane pointee type on the vector operand and on each extracted
2233 // lane so the prelegalizer wraps them as OpTypeVector/OpTypePointer of
2234 // the right element type instead of defaulting to i8.
2235 if (PtrIsVec)
2236 GR->buildAssignPtr(B, SrcElemTy, PtrOp);
2237
2238 Value *VecResult = PoisonValue::get(RetVTy);
2239 for (unsigned Lane = 0; Lane < N; ++Lane) {
2240 Value *LaneIdx = B.getInt32(Lane);
2241 Value *ScalarPtr = PtrOp;
2242 if (PtrIsVec) {
2243 SmallVector<Type *, 3> ExtractTypes = {ScalarPtrTy, PtrOp->getType(),
2244 LaneIdx->getType()};
2245 ScalarPtr = B.CreateIntrinsic(Intrinsic::spv_extractelt, {ExtractTypes},
2246 {PtrOp, LaneIdx});
2247 GR->buildAssignPtr(B, SrcElemTy, ScalarPtr);
2248 }
2249 SmallVector<Value *, 4> Args;
2250 Args.push_back(InBounds);
2251 Args.push_back(ScalarPtr);
2252 for (Value *Idx : I.indices()) {
2253 if (isa<VectorType>(Idx->getType())) {
2254 // We cannot use the builder here as for splat-ed / constant vectors
2255 // it will fold to the scalar, and then it becomes impossible to
2256 // retrieve / retain the vectorness.
2257 auto *EI =
2258 ExtractElementInst::Create(Idx, LaneIdx, "", B.GetInsertPoint());
2259 if (isVector1(Idx->getType())) // IRTranslator clobbers <1 x T>.
2260 Args.push_back(visitExtractElementInst(*EI));
2261 else
2262 Args.push_back(EI);
2263 } else {
2264 Args.push_back(Idx);
2265 }
2266 }
2267 Value *ScalarGep = B.CreateIntrinsic(Intrinsic::spv_gep, GepTypes, Args);
2268 GR->buildAssignPtr(B, LanePointeeTy, ScalarGep);
2269 VecResult = B.CreateInsertElement(VecResult, ScalarGep, LaneIdx);
2270 }
2271
2272 auto *NewI = cast<Instruction>(VecResult);
2273 replaceAllUsesWithAndErase(B, &I, NewI);
2274
2275 if (CallInst *Old = GR->findAssignPtrTypeInstr(NewI)) {
2276 Old->eraseFromParent();
2277 GR->addAssignPtrTypeInstr(NewI, nullptr);
2278 }
2280 GR->buildAssignPtr(B, LanePointeeTy, NewI);
2281
2282 return NewI;
2283 }
2284
2286 Type *IdxTy = CurrF->getDataLayout().getIndexType(I.getPointerOperandType());
2287 if (IsLogical && !isFirstIndexZero(&I)) {
2288 // Logical SPIR-V cannot use the OpPtrAccessChain instruction. If the first
2289 // index of the GEP is not 0, then we need to try to adjust it.
2290 //
2291 // If the GEP is doing byte addressing, try to rebuild the full access chain
2292 // from the type of the pointer.
2293 if (getByteAddressingMultiplier(I.getSourceElementType())) {
2294 return buildLogicalAccessChainFromGEP(I);
2295 }
2296
2297 // Look for the array-to-pointer decay. If this is the pattern
2298 // we can adjust the types, and prepend a 0 to the indices.
2299 Value *PtrOp = I.getPointerOperand();
2300 Type *SrcElemTy = I.getSourceElementType();
2301 Type *DeducedPointeeTy = deduceElementType(PtrOp, true);
2302
2303 if (auto *ArrTy = dyn_cast<ArrayType>(DeducedPointeeTy)) {
2304 if (ArrTy->getElementType() == SrcElemTy) {
2305 SmallVector<Value *> NewIndices;
2306 for (Value *Idx : I.indices())
2307 NewIndices.push_back(truncateGEPIndex(Idx, IdxTy, B));
2308 NewIndices.insert(NewIndices.begin(),
2309 ConstantInt::get(NewIndices.front()->getType(), 0));
2310
2311 SmallVector<Type *, 2> Types = {I.getType(), I.getPointerOperandType()};
2312 SmallVector<Value *, 4> Args;
2313 Args.push_back(B.getInt1(I.isInBounds()));
2314 Args.push_back(I.getPointerOperand());
2315 Args.append(NewIndices.begin(), NewIndices.end());
2316
2317 Instruction *NewI = B.CreateIntrinsicWithoutFolding(Intrinsic::spv_gep,
2318 {Types}, {Args});
2319 replaceAllUsesWithAndErase(B, &I, NewI);
2320 return NewI;
2321 }
2322 }
2323 }
2324
2325 SmallVector<Type *, 2> Types = {I.getType(), I.getOperand(0)->getType()};
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);
2331 Instruction *NewI =
2332 B.CreateIntrinsicWithoutFolding(Intrinsic::spv_gep, {Types}, {Args});
2333 replaceAllUsesWithAndErase(B, &I, NewI);
2334 return NewI;
2335}
2336
2337Instruction *SPIRVEmitIntrinsicsImpl::visitBitCastInst(BitCastInst &I) {
2338 IRBuilder<> B(I.getParent());
2339 B.SetInsertPoint(&I);
2340 Value *Source = I.getOperand(0);
2341
2342 // SPIR-V, contrary to LLVM 17+ IR, supports bitcasts between pointers of
2343 // varying element types. In case of IR coming from older versions of LLVM
2344 // such bitcasts do not provide sufficient information, should be just skipped
2345 // here, and handled in insertPtrCastOrAssignTypeInstr.
2346 if (isPointerTy(I.getType())) {
2347 replaceAllUsesWith(&I, Source);
2348 I.eraseFromParent();
2349 return nullptr;
2350 }
2351
2352 SmallVector<Type *, 2> Types = {I.getType(), Source->getType()};
2353 SmallVector<Value *> Args(I.op_begin(), I.op_end());
2354 Instruction *NewI =
2355 B.CreateIntrinsicWithoutFolding(Intrinsic::spv_bitcast, {Types}, {Args});
2356 replaceAllUsesWithAndErase(B, &I, NewI);
2357 return NewI;
2358}
2359
2360void SPIRVEmitIntrinsicsImpl::insertAssignPtrTypeTargetExt(
2361 TargetExtType *AssignedType, Value *V, IRBuilder<> &B) {
2362 Type *VTy = V->getType();
2363
2364 // A couple of sanity checks.
2365 assert((isPointerTy(VTy)) && "Expect a pointer type!");
2366 if (Type *ElemTy = getPointeeType(VTy))
2367 if (ElemTy != AssignedType)
2368 report_fatal_error("Unexpected pointer element type!");
2369
2370 CallInst *AssignCI = GR->findAssignPtrTypeInstr(V);
2371 if (!AssignCI) {
2372 GR->buildAssignType(B, AssignedType, V, CanUseAnyVectorRank);
2373 return;
2374 }
2375
2376 Type *CurrentType =
2378 cast<MetadataAsValue>(AssignCI->getOperand(1))->getMetadata())
2379 ->getType();
2380 if (CurrentType == AssignedType)
2381 return;
2382
2383 // Builtin types cannot be redeclared or casted.
2384 if (CurrentType->isTargetExtTy())
2385 report_fatal_error("Type mismatch " + CurrentType->getTargetExtName() +
2386 "/" + AssignedType->getTargetExtName() +
2387 " for value " + V->getName(),
2388 false);
2389
2390 // Our previous guess about the type seems to be wrong, let's update
2391 // inferred type according to a new, more precise type information.
2392 GR->updateAssignType(
2393 AssignCI, V, getNormalizedPoisonValue(AssignedType, CanUseAnyVectorRank));
2394}
2395
2396void SPIRVEmitIntrinsicsImpl::replacePointerOperandWithPtrCast(
2397 Instruction *I, Value *Pointer, Type *ExpectedElementType,
2398 unsigned OperandToReplace, IRBuilder<> &B) {
2399 TypeValidated.insert(I);
2400
2401 // Do not emit spv_ptrcast if Pointer's element type is ExpectedElementType
2402 Type *PointerElemTy = deduceElementTypeHelper(Pointer, false);
2403 if (PointerElemTy == ExpectedElementType ||
2404 isEquivalentTypes(PointerElemTy, ExpectedElementType))
2405 return;
2406
2408 Value *ExpectedElementVal =
2409 getNormalizedPoisonValue(ExpectedElementType, CanUseAnyVectorRank);
2410 MetadataAsValue *VMD = buildMD(ExpectedElementVal);
2411 unsigned AddressSpace = getPointerAddressSpace(Pointer->getType());
2412 bool FirstPtrCastOrAssignPtrType = true;
2413
2414 // Do not emit new spv_ptrcast if equivalent one already exists or when
2415 // spv_assign_ptr_type already targets this pointer with the same element
2416 // type.
2417 if (Pointer->hasUseList()) {
2418 for (auto User : Pointer->users()) {
2419 auto *II = dyn_cast<IntrinsicInst>(User);
2420 if (!II ||
2421 (II->getIntrinsicID() != Intrinsic::spv_assign_ptr_type &&
2422 II->getIntrinsicID() != Intrinsic::spv_ptrcast) ||
2423 II->getOperand(0) != Pointer)
2424 continue;
2425
2426 // There is some spv_ptrcast/spv_assign_ptr_type already targeting this
2427 // pointer.
2428 FirstPtrCastOrAssignPtrType = false;
2429 if (II->getOperand(1) != VMD ||
2430 dyn_cast<ConstantInt>(II->getOperand(2))->getSExtValue() !=
2432 continue;
2433
2434 // The spv_ptrcast/spv_assign_ptr_type targeting this pointer is of the
2435 // same element type and address space.
2436 if (II->getIntrinsicID() != Intrinsic::spv_ptrcast)
2437 return;
2438
2439 // This must be a spv_ptrcast, do not emit new if this one has the same BB
2440 // as I. Otherwise, search for other spv_ptrcast/spv_assign_ptr_type.
2441 if (II->getParent() != I->getParent())
2442 continue;
2443
2444 I->setOperand(OperandToReplace, II);
2445 return;
2446 }
2447 }
2448
2449 // Never replace an already-deduced pointer element type with a non-pointer
2450 // one. The conflicting use comes from a mis-deduced expected type. Leave the
2451 // operand untouched rather than emitting a ptrcast that re-introduces the
2452 // collapsed type at the use site.
2453 if (PointerElemTy && isPointerTyOrWrapper(PointerElemTy) &&
2454 !isPointerTyOrWrapper(ExpectedElementType) &&
2455 tracesToPointerAlloca(Pointer))
2456 return;
2457
2458 if (isa<Instruction>(Pointer) || isa<Argument>(Pointer)) {
2459 if (FirstPtrCastOrAssignPtrType) {
2460 // If this would be the first spv_ptrcast, do not emit spv_ptrcast and
2461 // emit spv_assign_ptr_type instead.
2462 GR->buildAssignPtr(B, ExpectedElementType, Pointer);
2463 return;
2464 } else if (isTodoType(Pointer)) {
2465 eraseTodoType(Pointer);
2466 if (!isa<CallInst>(Pointer) && !isaGEP(Pointer) &&
2467 !isa<AllocaInst>(Pointer)) {
2468 // If this wouldn't be the first spv_ptrcast but existing type info is
2469 // uncomplete, update spv_assign_ptr_type arguments.
2470 if (CallInst *AssignCI = GR->findAssignPtrTypeInstr(Pointer)) {
2471 Type *PrevElemTy = GR->findDeducedElementType(Pointer);
2472 assert(PrevElemTy);
2473 DenseSet<std::pair<Value *, Value *>> VisitedSubst{
2474 std::make_pair(I, Pointer)};
2475 GR->updateAssignType(AssignCI, Pointer, ExpectedElementVal);
2476 propagateElemType(Pointer, PrevElemTy, VisitedSubst);
2477 } else {
2478 GR->buildAssignPtr(B, ExpectedElementType, Pointer);
2479 }
2480 return;
2481 }
2482 }
2483 }
2484
2485 // Emit spv_ptrcast
2486 SmallVector<Type *, 2> Types = {Pointer->getType(), Pointer->getType()};
2487 SmallVector<Value *, 2> Args = {Pointer, VMD, B.getInt32(AddressSpace)};
2488 auto *PtrCastI =
2489 B.CreateIntrinsicWithoutFolding(Intrinsic::spv_ptrcast, {Types}, Args);
2490 I->setOperand(OperandToReplace, PtrCastI);
2491 // We need to set up a pointee type for the newly created spv_ptrcast.
2492 GR->buildAssignPtr(B, ExpectedElementType, PtrCastI);
2493}
2494
2495void SPIRVEmitIntrinsicsImpl::insertPtrCastOrAssignTypeInstr(Instruction *I,
2496 IRBuilder<> &B) {
2497 // Handle basic instructions:
2498 StoreInst *SI = dyn_cast<StoreInst>(I);
2499 if (IsKernelArgInt8(CurrF, SI)) {
2500 replacePointerOperandWithPtrCast(
2501 I, SI->getValueOperand(), IntegerType::getInt8Ty(CurrF->getContext()),
2502 0, B);
2503 }
2504 if (SI) {
2505 Value *Op = SI->getValueOperand();
2506 Value *Pointer = SI->getPointerOperand();
2507 Type *OpTy = Op->getType();
2508 if (auto *OpI = dyn_cast<Instruction>(Op)) {
2509 OpTy = restoreMutatedType(GR, OpI, OpTy);
2510 if (auto It = AggrConstTypes.find(OpI); It != AggrConstTypes.end())
2511 OpTy = It->second;
2512 }
2513 if (OpTy == Op->getType())
2514 OpTy = deduceElementTypeByValueDeep(OpTy, Op, false);
2515 replacePointerOperandWithPtrCast(I, Pointer, OpTy, 1, B);
2516 return;
2517 }
2518 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
2519 Value *Pointer = LI->getPointerOperand();
2520 Type *OpTy = LI->getType();
2521 // If the loaded from pointer carries byref/byval, the dominant type is the
2522 // pointee type specified therein, and we should retain it.
2523 if (Argument *Arg;
2524 (Arg = dyn_cast<Argument>(Pointer)) && hasPointeeTypeAttr(Arg))
2525 OpTy = getPointeeTypeByAttr(Arg);
2526
2527 if (auto *PtrTy = dyn_cast<PointerType>(OpTy)) {
2528 if (Type *ElemTy = GR->findDeducedElementType(LI)) {
2529 OpTy = getTypedPointerWrapper(ElemTy, PtrTy->getAddressSpace());
2530 } else {
2531 Type *NewOpTy = OpTy;
2532 OpTy = deduceElementTypeByValueDeep(OpTy, LI, false);
2533 if (OpTy == NewOpTy)
2534 insertTodoType(Pointer);
2535 }
2536 }
2537 replacePointerOperandWithPtrCast(I, Pointer, OpTy, 0, B);
2538 return;
2539 }
2540 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
2541 Value *Pointer = GEPI->getPointerOperand();
2542 Type *OpTy = nullptr;
2543
2544 // Logical SPIR-V is not allowed to use Op*PtrAccessChain instructions. If
2545 // the first index is 0, then we can trivially lower to OpAccessChain. If
2546 // not we need to try to rewrite the GEP. We avoid adding a pointer cast at
2547 // this time, and will rewrite the GEP when visiting it.
2548 if (TM.getSubtargetImpl()->isLogicalSPIRV() && !isFirstIndexZero(GEPI)) {
2549 return;
2550 }
2551
2552 // In all cases, fall back to the GEP type if type scavenging failed.
2553 if (!OpTy)
2554 OpTy = GEPI->getSourceElementType();
2555
2556 replacePointerOperandWithPtrCast(I, Pointer, OpTy, 0, B);
2557 if (isNestedPointer(OpTy))
2558 insertTodoType(Pointer);
2559 return;
2560 }
2561
2562 // An inserted pointer must have the type of its aggregate member.
2563 if (auto *IVI = dyn_cast<InsertValueInst>(I)) {
2564 Value *Op = IVI->getInsertedValueOperand();
2565 if (isPointerTy(Op->getType()))
2566 replacePointerOperandWithPtrCast(
2567 I, Op, getMemberPointeeType(IVI->getType(), IVI->getIndices()),
2569 return;
2570 }
2571 // So must a pointer inserted into a vector, whose elements are untyped
2572 // pointers and so pointers to i8.
2573 if (auto *IEI = dyn_cast<InsertElementInst>(I)) {
2574 Value *Op = IEI->getOperand(1);
2575 if (isPointerTy(Op->getType()))
2576 replacePointerOperandWithPtrCast(
2577 I, Op, IntegerType::getInt8Ty(I->getContext()), 1, B);
2578 return;
2579 }
2580
2581 // TODO: review and merge with existing logics:
2582 // Handle calls to builtins (non-intrinsics):
2583 CallInst *CI = dyn_cast<CallInst>(I);
2584 if (!CI || CI->isIndirectCall() || CI->isInlineAsm() ||
2586 return;
2587
2588 // collect information about formal parameter types
2589 std::string DemangledName =
2591 Function *CalledF = CI->getCalledFunction();
2592 SmallVector<Type *, 4> CalledArgTys;
2593 bool HaveTypes = false;
2594 for (unsigned OpIdx = 0; OpIdx < CalledF->arg_size(); ++OpIdx) {
2595 Argument *CalledArg = CalledF->getArg(OpIdx);
2596 Type *ArgType = CalledArg->getType();
2597 if (!isPointerTy(ArgType)) {
2598 CalledArgTys.push_back(nullptr);
2599 } else if (Type *ArgTypeElem = getPointeeType(ArgType)) {
2600 CalledArgTys.push_back(ArgTypeElem);
2601 HaveTypes = true;
2602 } else {
2603 Type *ElemTy = GR->findDeducedElementType(CalledArg);
2604 if (!ElemTy && hasPointeeTypeAttr(CalledArg))
2605 ElemTy = getPointeeTypeByAttr(CalledArg);
2606 if (!ElemTy) {
2607 ElemTy = getPointeeTypeByCallInst(DemangledName, CalledF, OpIdx);
2608 if (ElemTy) {
2609 GR->addDeducedElementType(CalledArg,
2610 normalizeType(ElemTy, CanUseAnyVectorRank));
2611 } else {
2612 for (User *U : CalledArg->users()) {
2613 if (Instruction *Inst = dyn_cast<Instruction>(U)) {
2614 if ((ElemTy = deduceElementTypeHelper(Inst, false)) != nullptr)
2615 break;
2616 }
2617 }
2618 }
2619 }
2620 HaveTypes |= ElemTy != nullptr;
2621 CalledArgTys.push_back(ElemTy);
2622 }
2623 }
2624
2625 if (DemangledName.empty() && !HaveTypes)
2626 return;
2627
2628 auto Set =
2629 TM.getSubtarget<SPIRVSubtarget>(*CalledF).getPreferredInstructionSet();
2630 // Do not reparse rejected declaration types with the builtin parser.
2631 bool ParseBuiltinTypes =
2632 !DemangledName.empty() &&
2633 (!CalledF->isDeclaration() || SPIRV::isBuiltin(DemangledName, Set));
2634 for (unsigned OpIdx = 0; OpIdx < CI->arg_size(); OpIdx++) {
2635 Value *ArgOperand = CI->getArgOperand(OpIdx);
2636 if (!isPointerTy(ArgOperand->getType()))
2637 continue;
2638
2639 // Constants (nulls/undefs) are handled in insertAssignPtrTypeIntrs()
2640 if (!isa<Instruction>(ArgOperand) && !isa<Argument>(ArgOperand)) {
2641 // However, we may have assumptions about the formal argument's type and
2642 // may have a need to insert a ptr cast for the actual parameter of this
2643 // call.
2644 Argument *CalledArg = CalledF->getArg(OpIdx);
2645 if (!GR->findDeducedElementType(CalledArg))
2646 continue;
2647 }
2648
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())
2655 continue;
2656
2657 if (ExpectedType->isTargetExtTy() &&
2659 insertAssignPtrTypeTargetExt(cast<TargetExtType>(ExpectedType),
2660 ArgOperand, B);
2661 else
2662 replacePointerOperandWithPtrCast(CI, ArgOperand, ExpectedType, OpIdx, B);
2663 }
2664}
2665
2667SPIRVEmitIntrinsicsImpl::visitInsertElementInst(InsertElementInst &I) {
2668 // If it's a <1 x Type> vector type, don't modify it. It's not a legal vector
2669 // type in LLT and IRTranslator will replace it by the scalar.
2670 if (isVector1(I.getType()) && !CanUseAnyVectorRank)
2671 return &I;
2672
2673 SmallVector<Type *, 4> Types = {I.getType(), I.getOperand(0)->getType(),
2674 I.getOperand(1)->getType(),
2675 I.getOperand(2)->getType()};
2676 IRBuilder<> B(I.getParent());
2677 B.SetInsertPoint(&I);
2678 SmallVector<Value *> Args(I.op_begin(), I.op_end());
2679 Instruction *NewI = B.CreateIntrinsicWithoutFolding(Intrinsic::spv_insertelt,
2680 {Types}, {Args});
2681 replaceAllUsesWithAndErase(B, &I, NewI);
2682 return NewI;
2683}
2684
2686SPIRVEmitIntrinsicsImpl::visitExtractElementInst(ExtractElementInst &I) {
2687 // If it's a <1 x Type> vector type, don't modify it. It's not a legal vector
2688 // type in LLT and IRTranslator will replace it by the scalar.
2689 if (isVector1(I.getVectorOperandType()) && !CanUseAnyVectorRank)
2690 return &I;
2691
2692 IRBuilder<> B(I.getParent());
2693 B.SetInsertPoint(&I);
2694 SmallVector<Type *, 3> Types = {I.getType(), I.getVectorOperandType(),
2695 I.getIndexOperand()->getType()};
2696 SmallVector<Value *, 2> Args = {I.getVectorOperand(), I.getIndexOperand()};
2697 Instruction *NewI = B.CreateIntrinsicWithoutFolding(Intrinsic::spv_extractelt,
2698 {Types}, {Args});
2699 replaceAllUsesWithAndErase(B, &I, NewI);
2700 return NewI;
2701}
2702
2703// Scalarize ptrtoint and inttoptr instructions operating on vectors of
2704// pointers, since SPIR-V does not support vectors of pointers without
2705// extensions. Run before preprocessCompositeConstants so that
2706// findScalarElement still sees constant vectors.
2707void SPIRVEmitIntrinsicsImpl::scalarizeVectorPtrCasts(Function &F) {
2708 // If the extension for vector-of-pointers is available, no scalarization
2709 // is needed - the backend can handle them natively.
2710 const SPIRVSubtarget &ST = TM.getSubtarget<SPIRVSubtarget>(F);
2711 if (ST.canUseExtension(SPIRV::Extension::SPV_INTEL_masked_gather_scatter))
2712 return;
2713
2714 SmallVector<Instruction *, 8> ToErase;
2715
2716 for (Instruction &I : make_early_inc_range(instructions(F))) {
2717 if (auto *PTI = dyn_cast<PtrToIntInst>(&I)) {
2718 auto *VecTy = dyn_cast<FixedVectorType>(PTI->getOperand(0)->getType());
2719 if (!VecTy || !VecTy->getElementType()->isPointerTy())
2720 continue;
2721
2722 IRBuilder<> B(PTI);
2723 unsigned NumElems = VecTy->getNumElements();
2724 Type *ElemIntTy = cast<VectorType>(PTI->getType())->getElementType();
2725 Value *Result = PoisonValue::get(PTI->getType());
2726
2727 for (unsigned Idx = 0; Idx < NumElems; ++Idx) {
2728 Value *ElemPtr = findScalarElement(PTI->getOperand(0), Idx);
2729 if (!ElemPtr)
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));
2733 }
2734
2735 PTI->replaceAllUsesWith(Result);
2736 ToErase.push_back(PTI);
2737 } else if (auto *ITP = dyn_cast<IntToPtrInst>(&I)) {
2738 auto *VecTy = dyn_cast<FixedVectorType>(ITP->getType());
2739 if (!VecTy || !VecTy->getElementType()->isPointerTy())
2740 continue;
2741
2742 // Only scalarize if all users are extractelement with constant index.
2743 // Other uses (e.g. masked.gather) need the vector-of-pointers and
2744 // should be handled by extension-specific lowering.
2745 bool AllUsersExtract = llvm::all_of(ITP->users(), [&](User *U) {
2746 auto *EE = dyn_cast<ExtractElementInst>(U);
2747 return EE && isa<ConstantInt>(EE->getIndexOperand());
2748 });
2749 if (!AllUsersExtract)
2750 continue;
2751
2752 IRBuilder<> B(ITP);
2753 Type *ElemPtrTy = VecTy->getElementType();
2754
2755 // Replace extractelement users with scalar inttoptr.
2756 for (User *U : make_early_inc_range(ITP->users())) {
2757 auto *EE = cast<ExtractElementInst>(U);
2758 unsigned Idx = cast<ConstantInt>(EE->getIndexOperand())->getZExtValue();
2759 B.SetInsertPoint(EE);
2760 Value *Elem =
2761 B.CreateExtractElement(ITP->getOperand(0), B.getInt32(Idx));
2762 Value *Conv = B.CreateIntToPtr(Elem, ElemPtrTy);
2763 EE->replaceAllUsesWith(Conv);
2764 ToErase.push_back(EE);
2765 }
2766
2767 ToErase.push_back(ITP);
2768 }
2769 }
2770
2771 if (ToErase.empty())
2772 return;
2774 for (Instruction *I : ToErase) {
2775 for (Value *Op : I->operand_values())
2776 MaybeDead.push_back(Op);
2777 I->eraseFromParent();
2778 }
2780}
2781
2782Instruction *SPIRVEmitIntrinsicsImpl::visitInsertValueInst(InsertValueInst &I) {
2783 IRBuilder<> B(I.getParent());
2784 B.SetInsertPoint(&I);
2785 SmallVector<Type *, 1> Types = {I.getInsertedValueOperand()->getType()};
2787 Value *AggregateOp = I.getAggregateOperand();
2788 if (isa<UndefValue>(AggregateOp))
2789 Args.push_back(UndefValue::get(B.getInt32Ty()));
2790 else
2791 Args.push_back(AggregateOp);
2792 Args.push_back(I.getInsertedValueOperand());
2793 for (auto &Op : I.indices())
2794 Args.push_back(B.getInt32(Op));
2795 Instruction *NewI =
2796 B.CreateIntrinsicWithoutFolding(Intrinsic::spv_insertv, {Types}, {Args});
2797 replaceMemInstrUses(&I, NewI, B);
2798 return NewI;
2799}
2800
2802SPIRVEmitIntrinsicsImpl::visitExtractValueInst(ExtractValueInst &I) {
2803 IRBuilder<> B(I.getParent());
2804 B.SetInsertPoint(&I);
2805 if (I.getAggregateOperand()->getType()->isAggregateType()) {
2806 // Mutate an aggregate-returning spv_extractv producer to i32 so
2807 // IRTranslator does not see a multi-register value.
2808 CallBase *CB = dyn_cast<CallBase>(I.getAggregateOperand());
2809 if (!CB || CB->getIntrinsicID() != Intrinsic::spv_extractv)
2810 return &I;
2811 CB->mutateType(B.getInt32Ty());
2812 }
2813 SmallVector<Value *> Args(I.operands());
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});
2818 // An aggregate extract is a SPIR-V value-id like an aggregate PHI, select or
2819 // freeze: keep the real aggregate type in metadata, but expose the value
2820 // itself as i32 so the intrinsic signature and its users stay valid.
2821 if (NewI->getType()->isAggregateType()) {
2822 Type *AggrTy = I.getType();
2823 AggrConstTypes[NewI] = AggrTy;
2824 NewI->mutateType(B.getInt32Ty());
2825 replaceMemInstrUses(&I, NewI, B);
2826 // The aggregate extractvalue only carried a name record; unlike a PHI, a
2827 // select or freeze does not pass its type down to an untyped operand.
2829 GR->buildAssignType(B, AggrTy, NewI, CanUseAnyVectorRank);
2830 return NewI;
2831 }
2832 replaceAllUsesWithAndErase(B, &I, NewI);
2833 return NewI;
2834}
2835
2836Instruction *SPIRVEmitIntrinsicsImpl::visitLoadInst(LoadInst &I) {
2837 if (!I.getType()->isAggregateType())
2838 return &I;
2839 IRBuilder<> B(I.getParent());
2840 B.SetInsertPoint(&I);
2841 TrackConstants = false;
2842 const auto *TLI = TM.getSubtargetImpl()->getTargetLowering();
2845
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()));
2851 } else {
2852 IntrinsicId = Intrinsic::spv_atomic_load;
2853 Args.push_back(B.getInt8(static_cast<uint8_t>(I.getOrdering())));
2854 }
2855 CallInst *NewI = B.CreateIntrinsicWithoutFolding(
2856 IntrinsicId, {I.getOperand(0)->getType()}, Args);
2857
2858 replaceMemInstrUses(&I, NewI, B);
2859 return NewI;
2860}
2861
2862Instruction *SPIRVEmitIntrinsicsImpl::visitStoreInst(StoreInst &I) {
2863 if (!AggrStores.contains(&I))
2864 return &I;
2865 IRBuilder<> B(I.getParent());
2866 B.SetInsertPoint(&I);
2867 TrackConstants = false;
2868 const auto *TLI = TM.getSubtargetImpl()->getTargetLowering();
2871 auto *PtrOp = I.getPointerOperand();
2872
2873 if (I.getValueOperand()->getType()->isAggregateType()) {
2874 // It is possible that what used to be an ExtractValueInst has been replaced
2875 // with a call to the spv_extractv intrinsic, and that said call hasn't
2876 // had its return type replaced with i32 during the dedicated pass (because
2877 // it was emitted later); we have to handle this here, because IRTranslator
2878 // cannot deal with multi-register types at the moment.
2879 CallBase *CB = dyn_cast<CallBase>(I.getValueOperand());
2880 assert(CB && CB->getIntrinsicID() == Intrinsic::spv_extractv &&
2881 "Unexpected argument of aggregate type, should be spv_extractv!");
2882 CB->mutateType(B.getInt32Ty());
2883 }
2884
2885 unsigned IntrinsicId;
2886 SmallVector<Value *, 4> Args = {I.getValueOperand(), PtrOp,
2887 B.getInt16(Flags)};
2888 if (!I.isAtomic()) {
2889 IntrinsicId = Intrinsic::spv_store;
2890 Args.push_back(B.getInt32(I.getAlign().value()));
2891 } else {
2892 IntrinsicId = Intrinsic::spv_atomic_store;
2893 Args.push_back(B.getInt8(static_cast<uint8_t>(I.getOrdering())));
2894 }
2895 Instruction *NewI = B.CreateIntrinsicWithoutFolding(
2896 IntrinsicId, {I.getValueOperand()->getType(), PtrOp->getType()}, Args);
2897 NewI->copyMetadata(I);
2898 I.eraseFromParent();
2899 return NewI;
2900}
2901
2902Instruction *SPIRVEmitIntrinsicsImpl::visitAllocaInst(AllocaInst &I) {
2903 Value *ArraySize = nullptr;
2904 if (I.isArrayAllocation()) {
2905 const SPIRVSubtarget *STI = TM.getSubtargetImpl(*I.getFunction());
2906 if (!STI->canUseExtension(
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",
2911 false);
2912 ArraySize = I.getArraySize();
2913 }
2914 IRBuilder<> B(I.getParent());
2915 B.SetInsertPoint(&I);
2916 TrackConstants = false;
2917 Type *PtrTy = I.getType();
2918 Instruction *NewI =
2919 ArraySize
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);
2926 return NewI;
2927}
2928
2930SPIRVEmitIntrinsicsImpl::visitAtomicCmpXchgInst(AtomicCmpXchgInst &I) {
2931 assert(I.getType()->isAggregateType() && "Aggregate result is expected");
2932 IRBuilder<> B(I.getParent());
2933 B.SetInsertPoint(&I);
2934 SmallVector<Value *> Args(I.operands());
2935 const Triple &TT = TM.getTargetTriple();
2936 Args.push_back(B.getInt32(static_cast<uint32_t>(
2937 getMemScope(TT, I.getContext(), I.getSyncScopeID()))));
2938 // Per SPIR-V spec atomic ops must combine the ordering bits with the
2939 // storage-class bit.
2940 const SPIRVSubtarget &ST = TM.getSubtarget<SPIRVSubtarget>(*I.getFunction());
2941 unsigned AS = I.getPointerOperand()->getType()->getPointerAddressSpace();
2942 uint32_t ScSem = static_cast<uint32_t>(
2944 Args.push_back(B.getInt32(getMemSemanticsWithStorageClass(
2945 TT, static_cast<uint32_t>(getMemSemantics(I.getSuccessOrdering())),
2946 ScSem)));
2947 Args.push_back(B.getInt32(getMemSemanticsWithStorageClass(
2948 TT, static_cast<uint32_t>(getMemSemantics(I.getFailureOrdering())),
2949 ScSem)));
2950 Instruction *NewI = B.CreateIntrinsicWithoutFolding(
2951 Intrinsic::spv_cmpxchg, {I.getPointerOperand()->getType()}, {Args});
2952 replaceMemInstrUses(&I, NewI, B);
2953 return NewI;
2954}
2955
2956Instruction *SPIRVEmitIntrinsicsImpl::visitAtomicRMWInst(AtomicRMWInst &I) {
2957 auto Op = I.getOperation();
2959 return &I;
2960
2961 // No SPIR-V opcode exists for these, so lowering to an imported helper is an
2962 // AMD extension. Other targets keep the generic expansion.
2964 return &I;
2965
2966 Module *M = I.getModule();
2967 IRBuilder<> B(I.getParent());
2968 B.SetInsertPoint(&I);
2969
2970 const SPIRVSubtarget &ST = TM.getSubtarget<SPIRVSubtarget>(*I.getFunction());
2971 unsigned AS = I.getPointerOperand()->getType()->getPointerAddressSpace();
2972
2973 uint32_t Scope = static_cast<uint32_t>(
2974 getMemScope(M->getTargetTriple(), I.getContext(), I.getSyncScopeID()));
2975 uint32_t ScSem = static_cast<uint32_t>(
2977 uint32_t MemSem = getMemSemanticsWithStorageClass(
2978 M->getTargetTriple(),
2979 static_cast<uint32_t>(getMemSemantics(I.getOrdering())), ScSem);
2980
2981 SmallString<64> FuncName(Op == AtomicRMWInst::UIncWrap
2982 ? "__translate_spirv_atomic_uinc_wrap"
2983 : "__translate_spirv_atomic_udec_wrap");
2984
2985 Type *ValTy = I.getValOperand()->getType();
2986 Type *PtrTy = I.getPointerOperand()->getType();
2987 // Encode the address space and value type in the name for overload.
2988 raw_svector_ostream OS(FuncName);
2989 OS << "_p" << AS << "_";
2990 if (auto *VecTy = dyn_cast<FixedVectorType>(ValTy))
2991 OS << "v" << VecTy->getNumElements();
2992 OS << "i" << ValTy->getScalarSizeInBits();
2993
2994 Type *Int32Ty = B.getInt32Ty();
2995 Type *BoolTy = B.getInt1Ty();
2996 SmallVector<Type *, 6> ArgTys = {PtrTy, Int32Ty, Int32Ty,
2997 ValTy, BoolTy, BoolTy};
2998 FunctionType *FT = FunctionType::get(ValTy, ArgTys, false);
2999 FunctionCallee FC = M->getOrInsertFunction(FuncName, FT);
3000 cast<Function>(FC.getCallee())->setCallingConv(CallingConv::SPIR_FUNC);
3001
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);
3007 CI->setCallingConv(CallingConv::SPIR_FUNC);
3008 // SPIRVCallLowering reads alias.scope/noalias off the call to build the
3009 // aliasing decorations and runs after this pass, so preserve the metadata.
3010 CI->copyMetadata(I);
3011
3012 replaceAllUsesWithAndErase(B, &I, CI);
3013 return CI;
3014}
3015
3016static bool isAbortCall(const Instruction &I, const SPIRVSubtarget &ST) {
3017 auto *CI = dyn_cast<CallInst>(&I);
3018 if (!CI)
3019 return false;
3020 switch (CI->getIntrinsicID()) {
3021 case Intrinsic::spv_abort:
3022 return true;
3023 case Intrinsic::trap:
3024 case Intrinsic::ubsantrap:
3025 // When the extension is enabled, selection lowers these to OpAbortKHR.
3026 return ST.canUseExtension(SPIRV::Extension::SPV_KHR_abort);
3027 default:
3028 return false;
3029 }
3030}
3031
3032// The OpAbortKHR instruction itself is a block terminator, so we don't need to
3033// emit an extra OpUnreachable instruction.
3035 const SPIRVSubtarget &ST) {
3036 const Instruction *Prev = I.getPrevNode();
3037 if (Prev && isAbortCall(*Prev, ST))
3038 return true;
3039
3041 *I.getParent(),
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");
3045 return false;
3046}
3047
3048Instruction *SPIRVEmitIntrinsicsImpl::visitUnreachableInst(UnreachableInst &I) {
3049 const SPIRVSubtarget &ST = TM.getSubtarget<SPIRVSubtarget>(*I.getFunction());
3050 if (precededByAbortIntrinsic(I, ST))
3051 return &I;
3052 IRBuilder<> B(&I);
3053 B.CreateIntrinsic(Intrinsic::spv_unreachable, {});
3054 return &I;
3055}
3056
3057// llvm.compiler.used and llvm.used hold use-list entries that protect their
3058// referenced globals from DCE without participating in code generation.
3059static bool isUseListGlobal(StringRef Name) {
3060 return Name == "llvm.compiler.used" || Name == "llvm.used";
3061}
3062
3063// Returns true for module-level globals that should not have SPIR-V intrinsics
3064// emitted (use-list globals plus llvm.global.annotations).
3066 return isUseListGlobal(Name) || Name == "llvm.global.annotations";
3067}
3068
3069// Returns true if every use of GV traces back to llvm.compiler.used or
3070// llvm.used.
3074 while (!Stack.empty()) {
3075 const Value *V = Stack.pop_back_val();
3076 if (!Visited.insert(V).second)
3077 continue;
3078 if (const auto *GVUser = dyn_cast<GlobalVariable>(V)) {
3079 if (!isUseListGlobal(GVUser->getName()))
3080 return false;
3081 continue;
3082 }
3083 if (const auto *C = dyn_cast<Constant>(V)) {
3084 Stack.append(C->user_begin(), C->user_end());
3085 continue;
3086 }
3087 return false;
3088 }
3089 return true;
3090}
3091
3092static bool
3093shouldEmitIntrinsicsForGlobalValue(const GlobalVariableUsers &GVUsers,
3094 const GlobalVariable &GV,
3095 const Function *F) {
3096 // Skip special artificial variables.
3097 if (isArtificialGlobal(GV.getName()))
3098 return false;
3099
3100 auto &UserFunctions = GVUsers.getTransitiveUserFunctions(GV);
3101 if (UserFunctions.contains(F))
3102 return true;
3103
3104 // Do not emit the intrinsics in this function, it's going to be emitted on
3105 // the functions that reference it.
3106 if (!UserFunctions.empty())
3107 return false;
3108
3109 // Emit definitions for globals that are not referenced by any function on the
3110 // first function definition.
3111 const Module &M = *F->getParent();
3112 const Function &FirstDefinition = *M.getFunctionDefs().begin();
3113 return F == &FirstDefinition;
3114}
3115
3116Value *SPIRVEmitIntrinsicsImpl::buildSpvUndefComposite(Type *AggrTy,
3117 IRBuilder<> &B) {
3118 auto MakeLeaf = [&](Type *ElemTy) -> Instruction * {
3119 CallInst *Leaf = B.CreateIntrinsicWithoutFolding(Intrinsic::spv_undef, {});
3120 AggrConsts[Leaf] = PoisonValue::get(ElemTy);
3121 AggrConstTypes[Leaf] = ElemTy;
3122 return Leaf;
3123 };
3124 SmallVector<Value *, 4> Elems;
3125 if (auto *ArrTy = dyn_cast<ArrayType>(AggrTy)) {
3126 Elems.assign(ArrTy->getNumElements(), MakeLeaf(ArrTy->getElementType()));
3127 } else {
3128 auto *StructTy = cast<StructType>(AggrTy);
3129 DenseMap<Type *, Instruction *> LeafByType;
3130 for (unsigned I = 0; I < StructTy->getNumElements(); ++I) {
3131 Type *ElemTy = StructTy->getContainedType(I);
3132 auto &Entry = LeafByType[ElemTy];
3133 if (!Entry)
3134 Entry = MakeLeaf(ElemTy);
3135 Elems.push_back(Entry);
3136 }
3137 }
3138 CallInst *Composite = B.CreateIntrinsicWithoutFolding(
3139 Intrinsic::spv_const_composite, {B.getInt32Ty()}, Elems);
3140 AggrConsts[Composite] = PoisonValue::get(AggrTy);
3141 AggrConstTypes[Composite] = AggrTy;
3142 return Composite;
3143}
3144
3145// If a function directly returns an aggregate-typed call result,
3146// the ReturnInst carries an aggregate while the function signature
3147// was rewritten to i32 by SPIRVPrepareFunctions. Rebuild the return value
3148// via extractvalue/insertvalue so the regular spv_extractv/spv_insertv
3149// lowering produces a valid OpReturnValue.
3150void SPIRVEmitIntrinsicsImpl::reconstructAggregateReturns(Function &Func,
3151 IRBuilder<> &B) {
3152 Type *OrigRetTy = GR->findMutated(&Func);
3153 if (!OrigRetTy || !OrigRetTy->isAggregateType())
3154 return;
3155 for (BasicBlock &BB : Func) {
3156 auto *RI = dyn_cast<ReturnInst>(BB.getTerminator());
3157 if (!RI)
3158 continue;
3159 Value *RetVal = RI->getReturnValue();
3160 if (!RetVal || RetVal->getType() != OrigRetTy || !isa<CallBase>(RetVal))
3161 continue;
3162 Type *AggrTy = RetVal->getType();
3163 uint64_t NumElts = isa<StructType>(AggrTy)
3164 ? cast<StructType>(AggrTy)->getNumElements()
3165 : cast<ArrayType>(AggrTy)->getNumElements();
3166 B.SetInsertPoint(RI);
3167 Value *Rebuilt = PoisonValue::get(AggrTy);
3168 for (uint64_t I = 0; I < NumElts; ++I) {
3169 Value *Elt = B.CreateExtractValue(RetVal, I);
3170 Rebuilt = B.CreateInsertValue(Rebuilt, Elt, I);
3171 }
3172 RI->setOperand(0, Rebuilt);
3173 }
3174}
3175
3176void SPIRVEmitIntrinsicsImpl::processGlobalValue(GlobalVariable &GV,
3177 IRBuilder<> &B) {
3178
3179 if (!shouldEmitIntrinsicsForGlobalValue(GVUsers, GV, CurrF))
3180 return;
3181
3182 // Record the pointee type for every global, not only initialized ones, so an
3183 // undef non-constant aggregate global is not later collapsed to its element
3184 // type. Result is ignored, because TypedPointerType is not supported
3185 // by llvm IR general logic.
3186 deduceElementTypeHelper(&GV, false);
3187
3188 Constant *Init = nullptr;
3189 if (hasInitializer(&GV)) {
3190 Init = GV.getInitializer();
3191 Value *InitOp = Init;
3192 if (isa<UndefValue>(Init) && Init->getType()->isAggregateType()) {
3193 const SPIRVSubtarget *STI = TM.getSubtargetImpl();
3194 bool UsePoison =
3195 isa<PoisonValue>(Init) &&
3196 STI->canUseExtension(SPIRV::Extension::SPV_KHR_poison_freeze);
3197 if (UsePoison) {
3198 CallInst *Call = B.CreateIntrinsicWithoutFolding(Intrinsic::spv_poison,
3199 {B.getInt32Ty()}, {});
3200 AggrConsts[Call] = cast<PoisonValue>(Init);
3201 AggrConstTypes[Call] = Init->getType();
3202 InitOp = Call;
3203 } else {
3204 InitOp = buildSpvUndefComposite(Init->getType(), B);
3205 }
3206 }
3207 Type *Ty = isAggrConstForceInt32(Init) ? B.getInt32Ty() : Init->getType();
3208 Constant *Const = isAggrConstForceInt32(Init) ? B.getInt32(1) : Init;
3209 CallInst *InitInst = B.CreateIntrinsicWithoutFolding(
3210 Intrinsic::spv_init_global, {GV.getType(), Ty}, {&GV, Const});
3211 InitInst->setArgOperand(1, InitOp);
3212 }
3213 // Globals with only use-list references have no real function uses. Emit
3214 // spv_unref_global so buildGlobalVariable is called for them.
3215 if (!Init && hasOnlyArtificialUses(GV))
3216 B.CreateIntrinsic(Intrinsic::spv_unref_global, GV.getType(), &GV);
3217}
3218
3219// Return true, if we can't decide what is the pointee type now and will get
3220// back to the question later. Return false is spv_assign_ptr_type is not needed
3221// or can be inserted immediately.
3222bool SPIRVEmitIntrinsicsImpl::insertAssignPtrTypeIntrs(Instruction *I,
3223 IRBuilder<> &B,
3224 bool UnknownElemTypeI8) {
3226 if (!isPointerTy(I->getType()) || !requireAssignType(I))
3227 return false;
3228
3230 if (Type *ElemTy = deduceElementType(I, UnknownElemTypeI8)) {
3231 GR->buildAssignPtr(B, ElemTy, I);
3232 return false;
3233 }
3234 return true;
3235}
3236
3237void SPIRVEmitIntrinsicsImpl::insertAssignTypeIntrs(Instruction *I,
3238 IRBuilder<> &B) {
3239 // TODO: extend the list of functions with known result types
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}};
3244
3246
3247 bool IsKnown = false;
3248 if (auto *CI = dyn_cast<CallInst>(I)) {
3249 if (!CI->isIndirectCall() && !CI->isInlineAsm() &&
3250 CI->getCalledFunction() && !CI->getCalledFunction()->isIntrinsic()) {
3251 Function *CalledF = CI->getCalledFunction();
3252 std::string DemangledName =
3254 FPDecorationId DecorationId = FPDecorationId::NONE;
3255 if (DemangledName.length() > 0)
3256 DemangledName =
3257 SPIRV::lookupBuiltinNameHelper(DemangledName, &DecorationId);
3258 auto ResIt = ResTypeWellKnown.find(DemangledName);
3259 if (ResIt != ResTypeWellKnown.end()) {
3260 IsKnown = true;
3262 switch (ResIt->second) {
3263 case WellKnownTypes::Event:
3264 GR->buildAssignType(
3265 B, TargetExtType::get(I->getContext(), "spirv.Event"), I,
3266 CanUseAnyVectorRank);
3267 break;
3268 }
3269 }
3270 // check if a floating rounding mode or saturation info is present
3271 switch (DecorationId) {
3272 default:
3273 break;
3274 case FPDecorationId::SAT:
3276 break;
3277 case FPDecorationId::RTE:
3279 CI, SPIRV::FPRoundingMode::FPRoundingMode::RTE, B);
3280 break;
3281 case FPDecorationId::RTZ:
3283 CI, SPIRV::FPRoundingMode::FPRoundingMode::RTZ, B);
3284 break;
3285 case FPDecorationId::RTP:
3287 CI, SPIRV::FPRoundingMode::FPRoundingMode::RTP, B);
3288 break;
3289 case FPDecorationId::RTN:
3291 CI, SPIRV::FPRoundingMode::FPRoundingMode::RTN, B);
3292 break;
3293 }
3294 }
3295 }
3296
3297 Type *Ty = I->getType();
3298 if (!IsKnown && !Ty->isVoidTy() && !isPointerTy(Ty) && requireAssignType(I)) {
3300 Type *TypeToAssign = Ty;
3301 if (auto *II = dyn_cast<IntrinsicInst>(I)) {
3302 if (isSpvAggrPlaceholder(II)) {
3303 auto It = AggrConstTypes.find(II);
3304 if (It == AggrConstTypes.end())
3305 report_fatal_error("Unknown composite intrinsic type");
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;
3310 }
3311 } else if (auto It = AggrConstTypes.find(I); It != AggrConstTypes.end())
3312 TypeToAssign = It->second;
3313 TypeToAssign = restoreMutatedType(GR, I, TypeToAssign);
3314 GR->buildAssignType(B, TypeToAssign, I, CanUseAnyVectorRank);
3315 }
3316 for (const auto &Op : I->operands()) {
3318 isVector1(Op->getType()) || // <1 x T> gets clobbered ty IRTranslator.
3319 // Check GetElementPtrConstantExpr case.
3321 (isa<GEPOperator>(Op) ||
3322 (cast<ConstantExpr>(Op)->getOpcode() == CastInst::IntToPtr)))) {
3324 Type *OpTy = Op->getType();
3325 if (isa<UndefValue>(Op) && OpTy->isAggregateType()) {
3326 CallInst *AssignCI =
3327 buildIntrWithMD(Intrinsic::spv_assign_type, {B.getInt32Ty()}, Op,
3328 UndefValue::get(B.getInt32Ty()), {}, B);
3329 GR->addAssignPtrTypeInstr(Op, AssignCI);
3330 } else if (!isa<Instruction>(Op)) {
3331 Type *OpTy = Op->getType();
3332 Type *OpTyElem = getPointeeType(OpTy);
3333 if (OpTyElem) {
3334 GR->buildAssignPtr(B, OpTyElem, Op);
3335 } else if (isPointerTy(OpTy)) {
3336 Type *ElemTy = GR->findDeducedElementType(Op);
3337 GR->buildAssignPtr(B, ElemTy ? ElemTy : deduceElementType(Op, true),
3338 Op);
3339 } else {
3340 Value *OpTyVal = Op;
3341 if (OpTy->isTargetExtTy()) {
3342 // We need to do this in order to be consistent with how target ext
3343 // types are handled in `processInstrAfterVisit`
3344 OpTyVal = getNormalizedPoisonValue(OpTy, CanUseAnyVectorRank);
3345 }
3346 CallInst *AssignCI = buildIntrWithMD(
3347 Intrinsic::spv_assign_type, {OpTy},
3348 getNormalizedPoisonValue(OpTy, CanUseAnyVectorRank), OpTyVal, {},
3349 B);
3350 GR->addAssignPtrTypeInstr(OpTyVal, AssignCI);
3351 }
3352 }
3353 }
3354 }
3355}
3356
3357bool SPIRVEmitIntrinsicsImpl::shouldTryToAddMemAliasingDecoration(
3358 Instruction *Inst) {
3359 const SPIRVSubtarget *STI = TM.getSubtargetImpl(*Inst->getFunction());
3360 if (!STI->canUseExtension(SPIRV::Extension::SPV_INTEL_memory_access_aliasing))
3361 return false;
3362 // Add aliasing decorations to internal load and store intrinsics.
3363 // Do not attach them to store atomic or load atomic intrinsics / instructions
3364 // since the extension is inconsistent at the moment (we cannot add the
3365 // decoration to atomic stores because they do not have an id).
3366 return match(Inst,
3368}
3369
3370void SPIRVEmitIntrinsicsImpl::insertSpirvDecorations(Instruction *I,
3371 IRBuilder<> &B) {
3372 if (MDNode *MD = I->getMetadata("spirv.Decorations")) {
3374 B.CreateIntrinsic(Intrinsic::spv_assign_decoration, {I->getType()},
3375 {I, MetadataAsValue::get(I->getContext(), MD)});
3376 }
3377 // Lower alias.scope/noalias metadata
3378 {
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),
3387 MetadataAsValue::get(I->getContext(), AliasListMD)};
3389 B.CreateIntrinsic(Intrinsic::spv_assign_aliasing_decoration,
3390 {I->getType()}, {Args});
3391 }
3392 }
3393 };
3394 processMemAliasingDecoration(LLVMContext::MD_alias_scope);
3395 processMemAliasingDecoration(LLVMContext::MD_noalias);
3396 }
3397 // MD_fpmath
3398 if (MDNode *MD = I->getMetadata(LLVMContext::MD_fpmath)) {
3399 const SPIRVSubtarget *STI = TM.getSubtargetImpl(*I->getFunction());
3400 bool AllowFPMaxError =
3401 STI->canUseExtension(SPIRV::Extension::SPV_INTEL_fp_max_error);
3402 if (!AllowFPMaxError)
3403 return;
3404
3406 B.CreateIntrinsic(Intrinsic::spv_assign_fpmaxerror_decoration,
3407 {I->getType()},
3408 {I, MetadataAsValue::get(I->getContext(), MD)});
3409 }
3410 if (spirvPreserveAuxData(TM.getCLOpts(), I->getModule()->getTargetTriple()) &&
3412 LLVMContext &Ctx = B.getContext();
3413 auto *AuxMD = ConstantAsMetadata::get(ConstantInt::get(
3414 B.getInt32Ty(), SPIRV::Decoration::AuxDataInstructionMetadata));
3415
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")}));
3426 if (!MDs.empty()) {
3428 B.CreateIntrinsic(Intrinsic::spv_assign_decoration, {I->getType()},
3429 {I, MetadataAsValue::get(Ctx, MDNode::get(Ctx, MDs))});
3430 }
3431 }
3432}
3433
3435 const Module &M,
3437 &FPFastMathDefaultInfoMap,
3438 Function *F) {
3439 auto it = FPFastMathDefaultInfoMap.find(F);
3440 if (it != FPFastMathDefaultInfoMap.end())
3441 return it->second;
3442
3443 // If the map does not contain the entry, create a new one. Initialize it to
3444 // contain all 3 elements sorted by bit width of target type: {half, float,
3445 // double}.
3446 SPIRV::FPFastMathDefaultInfoVector FPFastMathDefaultInfoVec;
3447 FPFastMathDefaultInfoVec.emplace_back(Type::getHalfTy(M.getContext()),
3448 SPIRV::FPFastMathMode::None);
3449 FPFastMathDefaultInfoVec.emplace_back(Type::getFloatTy(M.getContext()),
3450 SPIRV::FPFastMathMode::None);
3451 FPFastMathDefaultInfoVec.emplace_back(Type::getDoubleTy(M.getContext()),
3452 SPIRV::FPFastMathMode::None);
3453 return FPFastMathDefaultInfoMap[F] = std::move(FPFastMathDefaultInfoVec);
3454}
3455
3457 SPIRV::FPFastMathDefaultInfoVector &FPFastMathDefaultInfoVec,
3458 const Type *Ty) {
3459 size_t BitWidth = Ty->getScalarSizeInBits();
3460 int Index =
3462 BitWidth);
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];
3468}
3469
3470void SPIRVEmitIntrinsicsImpl::insertConstantsForFPFastMathDefault(Module &M) {
3471 const SPIRVSubtarget *ST = TM.getSubtargetImpl();
3472 if (!ST->canUseExtension(SPIRV::Extension::SPV_KHR_float_controls2))
3473 return;
3474
3475 // Store the FPFastMathDefaultInfo in the FPFastMathDefaultInfoMap.
3476 // We need the entry point (function) as the key, and the target
3477 // type and flags as the value.
3478 // We also need to check ContractionOff and SignedZeroInfNanPreserve
3479 // execution modes, as they are now deprecated and must be replaced
3480 // with FPFastMathDefaultInfo.
3481 auto Node = M.getNamedMetadata("spirv.ExecutionMode");
3482 if (!Node) {
3483 if (!M.getNamedMetadata("opencl.enable.FP_CONTRACT")) {
3484 // This requires emitting ContractionOff. However, because
3485 // ContractionOff is now deprecated, we need to replace it with
3486 // FPFastMathDefaultInfo with FP Fast Math Mode bitmask set to all 0.
3487 // We need to create the constant for that.
3488
3489 // Create constant instruction with the bitmask flags.
3490 Constant *InitValue =
3491 ConstantInt::get(Type::getInt32Ty(M.getContext()), 0);
3492 // TODO: Reuse constant if there is one already with the required
3493 // value.
3494 [[maybe_unused]] GlobalVariable *GV =
3495 new GlobalVariable(M, // Module
3496 Type::getInt32Ty(M.getContext()), // Type
3497 true, // isConstant
3499 InitValue // Initializer
3500 );
3501 }
3502 return;
3503 }
3504
3505 // The table maps function pointers to their default FP fast math info. It
3506 // can be assumed that the SmallVector is sorted by the bit width of the
3507 // type. The first element is the smallest bit width, and the last element
3508 // is the largest bit width, therefore, we will have {half, float, double}
3509 // in the order of their bit widths.
3510 MapVector<Function *, SPIRV::FPFastMathDefaultInfoVector>
3511 FPFastMathDefaultInfoMap;
3512
3513 for (unsigned i = 0; i < Node->getNumOperands(); i++) {
3514 MDNode *MDN = cast<MDNode>(Node->getOperand(i));
3515 assert(MDN->getNumOperands() >= 2 && "Expected at least 2 operands");
3517 cast<ConstantAsMetadata>(MDN->getOperand(0))->getValue());
3518 const auto EM =
3520 cast<ConstantAsMetadata>(MDN->getOperand(1))->getValue())
3521 ->getZExtValue();
3522 if (EM == SPIRV::ExecutionMode::FPFastMathDefault) {
3523 assert(MDN->getNumOperands() == 4 &&
3524 "Expected 4 operands for FPFastMathDefault");
3525 const Type *T = cast<ValueAsMetadata>(MDN->getOperand(2))->getType();
3526 unsigned Flags =
3528 cast<ConstantAsMetadata>(MDN->getOperand(3))->getValue())
3529 ->getZExtValue();
3530 SPIRV::FPFastMathDefaultInfoVector &FPFastMathDefaultInfoVec =
3531 getOrCreateFPFastMathDefaultInfoVec(M, FPFastMathDefaultInfoMap, F);
3532 SPIRV::FPFastMathDefaultInfo &Info =
3533 getFPFastMathDefaultInfo(FPFastMathDefaultInfoVec, T);
3534 Info.FastMathFlags = Flags;
3535 Info.FPFastMathDefault = true;
3536 } else if (EM == SPIRV::ExecutionMode::ContractionOff) {
3537 assert(MDN->getNumOperands() == 2 &&
3538 "Expected no operands for ContractionOff");
3539
3540 // We need to save this info for every possible FP type, i.e. {half,
3541 // float, double, fp128}.
3542 SPIRV::FPFastMathDefaultInfoVector &FPFastMathDefaultInfoVec =
3543 getOrCreateFPFastMathDefaultInfoVec(M, FPFastMathDefaultInfoMap, F);
3544 for (SPIRV::FPFastMathDefaultInfo &Info : FPFastMathDefaultInfoVec) {
3545 Info.ContractionOff = true;
3546 }
3547 } else if (EM == SPIRV::ExecutionMode::SignedZeroInfNanPreserve) {
3548 assert(MDN->getNumOperands() == 3 &&
3549 "Expected 1 operand for SignedZeroInfNanPreserve");
3550 unsigned TargetWidth =
3552 cast<ConstantAsMetadata>(MDN->getOperand(2))->getValue())
3553 ->getZExtValue();
3554 // We need to save this info only for the FP type with TargetWidth.
3555 SPIRV::FPFastMathDefaultInfoVector &FPFastMathDefaultInfoVec =
3556 getOrCreateFPFastMathDefaultInfoVec(M, FPFastMathDefaultInfoMap, F);
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;
3564 }
3565 }
3566
3567 DenseMap<unsigned, GlobalVariable *> GlobalVars;
3568 for (auto &[Func, FPFastMathDefaultInfoVec] : FPFastMathDefaultInfoMap) {
3569 if (FPFastMathDefaultInfoVec.empty())
3570 continue;
3571
3572 for (const SPIRV::FPFastMathDefaultInfo &Info : FPFastMathDefaultInfoVec) {
3573 assert(Info.Ty && "Expected target type for FPFastMathDefaultInfo");
3574 // Skip if none of the execution modes was used.
3575 unsigned Flags = Info.FastMathFlags;
3576 if (Flags == SPIRV::FPFastMathMode::None && !Info.ContractionOff &&
3577 !Info.SignedZeroInfNanPreserve && !Info.FPFastMathDefault)
3578 continue;
3579
3580 // Check if flags are compatible.
3581 if (Info.ContractionOff && (Flags & SPIRV::FPFastMathMode::AllowContract))
3582 report_fatal_error("Conflicting FPFastMathFlags: ContractionOff "
3583 "and AllowContract");
3584
3585 if (Info.SignedZeroInfNanPreserve &&
3586 !(Flags &
3587 (SPIRV::FPFastMathMode::NotNaN | SPIRV::FPFastMathMode::NotInf |
3588 SPIRV::FPFastMathMode::NSZ))) {
3589 if (Info.FPFastMathDefault)
3590 report_fatal_error("Conflicting FPFastMathFlags: "
3591 "SignedZeroInfNanPreserve but at least one of "
3592 "NotNaN/NotInf/NSZ is enabled.");
3593 }
3594
3595 if ((Flags & SPIRV::FPFastMathMode::AllowTransform) &&
3596 !((Flags & SPIRV::FPFastMathMode::AllowReassoc) &&
3597 (Flags & SPIRV::FPFastMathMode::AllowContract))) {
3598 report_fatal_error("Conflicting FPFastMathFlags: "
3599 "AllowTransform requires AllowReassoc and "
3600 "AllowContract to be set.");
3601 }
3602
3603 auto it = GlobalVars.find(Flags);
3604 GlobalVariable *GV = nullptr;
3605 if (it != GlobalVars.end()) {
3606 // Reuse existing global variable.
3607 GV = it->second;
3608 } else {
3609 // Create constant instruction with the bitmask flags.
3610 Constant *InitValue =
3611 ConstantInt::get(Type::getInt32Ty(M.getContext()), Flags);
3612 // TODO: Reuse constant if there is one already with the required
3613 // value.
3614 GV = new GlobalVariable(M, // Module
3615 Type::getInt32Ty(M.getContext()), // Type
3616 true, // isConstant
3618 InitValue // Initializer
3619 );
3620 GlobalVars[Flags] = GV;
3621 }
3622 }
3623 }
3624}
3625
3626void SPIRVEmitIntrinsicsImpl::processInstrAfterVisit(Instruction *I,
3627 IRBuilder<> &B) {
3628 auto *II = dyn_cast<IntrinsicInst>(I);
3629 bool IsConstComposite =
3630 II && II->getIntrinsicID() == Intrinsic::spv_const_composite;
3631 if (IsConstComposite && TrackConstants) {
3633 auto t = AggrConsts.find(I);
3634 assert(t != AggrConsts.end());
3635 auto *NewOp =
3636 buildIntrWithMD(Intrinsic::spv_track_constant,
3637 {II->getType(), II->getType()}, t->second, I, {}, B);
3638 replaceAllUsesWith(I, NewOp, false);
3639 NewOp->setArgOperand(0, I);
3640 }
3641 bool IsPhi = isa<PHINode>(I), BPrepared = false;
3642 for (const auto &Op : I->operands()) {
3643 if (isa<PHINode>(I) || isa<SwitchInst>(I) ||
3645 continue;
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))))
3650 continue;
3651
3652 if (!BPrepared) {
3653 IsPhi ? B.SetInsertPointPastAllocas(I->getParent()->getParent())
3654 : B.SetInsertPoint(I);
3655 BPrepared = true;
3656 }
3657 Type *OpTy = Op->getType();
3658 Type *OpElemTy = GR->findDeducedElementType(Op);
3659 Value *NewOp = Op;
3660 if (OpTy->isTargetExtTy()) {
3661 // Since this value is replaced by poison, we need to do the same in
3662 // `insertAssignTypeIntrs`.
3663 Value *OpTyVal = getNormalizedPoisonValue(OpTy, CanUseAnyVectorRank);
3664 NewOp = buildIntrWithMD(Intrinsic::spv_track_constant,
3665 {OpTy, OpTyVal->getType()}, Op, OpTyVal, {}, B);
3666 }
3667 if (!IsConstComposite && isPointerTy(OpTy) && OpElemTy != nullptr &&
3668 OpElemTy != IntegerType::getInt8Ty(I->getContext())) {
3669 SmallVector<Type *, 2> Types = {OpTy, OpTy};
3670 SmallVector<Value *, 2> Args = {
3671 NewOp,
3672 buildMD(getNormalizedPoisonValue(OpElemTy, CanUseAnyVectorRank)),
3673 B.getInt32(getPointerAddressSpace(OpTy))};
3674 CallInst *PtrCasted = B.CreateIntrinsicWithoutFolding(
3675 Intrinsic::spv_ptrcast, {Types}, Args);
3676 GR->buildAssignPtr(B, OpElemTy, PtrCasted);
3677 NewOp = PtrCasted;
3678 }
3679 if (NewOp != Op)
3680 I->setOperand(OpNo, NewOp);
3681 }
3682 if (Named.insert(I).second)
3683 emitAssignName(TM.getCLOpts(), I, B);
3684}
3685
3686Type *SPIRVEmitIntrinsicsImpl::deduceFunParamElementType(Function *F,
3687 unsigned OpIdx) {
3688 SmallPtrSet<Function *, 0> FVisited;
3689 return deduceFunParamElementType(F, OpIdx, FVisited);
3690}
3691
3692Type *SPIRVEmitIntrinsicsImpl::deduceFunParamElementType(
3693 Function *F, unsigned OpIdx, SmallPtrSetImpl<Function *> &FVisited) {
3694 // maybe a cycle
3695 if (!FVisited.insert(F).second)
3696 return nullptr;
3697
3698 SmallPtrSet<Value *, 0> Visited;
3700 // search in function's call sites
3701 for (User *U : F->users()) {
3702 CallInst *CI = dyn_cast<CallInst>(U);
3703 if (!CI || OpIdx >= CI->arg_size())
3704 continue;
3705 Value *OpArg = CI->getArgOperand(OpIdx);
3706 if (!isPointerTy(OpArg->getType()))
3707 continue;
3708 // maybe we already know operand's element type
3709 if (Type *KnownTy = GR->findDeducedElementType(OpArg))
3710 return KnownTy;
3711 // try to deduce from the operand itself
3712 Visited.clear();
3713 if (Type *Ty = deduceElementTypeHelper(OpArg, Visited, false))
3714 return Ty;
3715 // search in actual parameter's users
3716 for (User *OpU : OpArg->users()) {
3718 if (!Inst || Inst == CI)
3719 continue;
3720 Visited.clear();
3721 if (Type *Ty = deduceElementTypeHelper(Inst, Visited, false))
3722 return Ty;
3723 }
3724 // check if it's a formal parameter of the outer function
3725 if (!CI->getParent() || !CI->getParent()->getParent())
3726 continue;
3727 Function *OuterF = CI->getParent()->getParent();
3728 if (FVisited.find(OuterF) != FVisited.end())
3729 continue;
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));
3733 break;
3734 }
3735 }
3736 }
3737
3738 // search in function parameters
3739 for (auto &Pair : Lookup) {
3740 if (Type *Ty = deduceFunParamElementType(Pair.first, Pair.second, FVisited))
3741 return Ty;
3742 }
3743
3744 return nullptr;
3745}
3746
3747void SPIRVEmitIntrinsicsImpl::processParamTypesByFunHeader(Function *F,
3748 IRBuilder<> &B) {
3749 B.SetInsertPointPastAllocas(F);
3750 for (unsigned OpIdx = 0; OpIdx < F->arg_size(); ++OpIdx) {
3751 Argument *Arg = F->getArg(OpIdx);
3752 // Vector-of-pointers arg: deduce pointee from a GEP user so the function
3753 // type isn't emitted with the default i8 pointee.
3754 if (isUntypedPointerVectorTy(Arg->getType()) &&
3755 !GR->findDeducedElementType(Arg)) {
3756 for (User *U : Arg->users()) {
3758 if (GEP && GEP->getPointerOperand() == Arg) {
3759 GR->buildAssignPtr(B, GEP->getSourceElementType(), Arg);
3760 break;
3761 }
3762 }
3763 continue;
3764 }
3765 if (!isUntypedPointerTy(Arg->getType()))
3766 continue;
3767 Type *ElemTy = GR->findDeducedElementType(Arg);
3768 if (ElemTy)
3769 continue;
3770 if (hasPointeeTypeAttr(Arg) &&
3771 (ElemTy = getPointeeTypeByAttr(Arg)) != nullptr) {
3772 GR->buildAssignPtr(B, ElemTy, Arg);
3773 continue;
3774 }
3775 // search in function's call sites
3776 for (User *U : F->users()) {
3777 CallInst *CI = dyn_cast<CallInst>(U);
3778 if (!CI || OpIdx >= CI->arg_size())
3779 continue;
3780 Value *OpArg = CI->getArgOperand(OpIdx);
3781 if (!isPointerTy(OpArg->getType()))
3782 continue;
3783 // maybe we already know operand's element type
3784 if ((ElemTy = GR->findDeducedElementType(OpArg)) != nullptr)
3785 break;
3786 }
3787 if (ElemTy) {
3788 GR->buildAssignPtr(B, ElemTy, Arg);
3789 continue;
3790 }
3791 if (HaveFunPtrs) {
3792 for (User *U : Arg->users()) {
3793 CallInst *CI = dyn_cast<CallInst>(U);
3794 if (CI && !isa<IntrinsicInst>(CI) && CI->isIndirectCall() &&
3795 CI->getCalledOperand() == Arg &&
3796 CI->getParent()->getParent() == CurrF) {
3798 deduceOperandElementTypeFunctionPointer(CI, Ops, ElemTy, false);
3799 if (ElemTy) {
3800 GR->buildAssignPtr(B, ElemTy, Arg);
3801 break;
3802 }
3803 }
3804 }
3805 }
3806 }
3807}
3808
3809void SPIRVEmitIntrinsicsImpl::processParamTypes(Function *F, IRBuilder<> &B) {
3810 B.SetInsertPointPastAllocas(F);
3811 for (unsigned OpIdx = 0; OpIdx < F->arg_size(); ++OpIdx) {
3812 Argument *Arg = F->getArg(OpIdx);
3813 if (!isUntypedPointerTy(Arg->getType()))
3814 continue;
3815 Type *ElemTy = GR->findDeducedElementType(Arg);
3816 if (!ElemTy && (ElemTy = deduceFunParamElementType(F, OpIdx)) != nullptr) {
3817 if (CallInst *AssignCI = GR->findAssignPtrTypeInstr(Arg)) {
3818 DenseSet<std::pair<Value *, Value *>> VisitedSubst;
3819 GR->updateAssignType(
3820 AssignCI, Arg,
3821 getNormalizedPoisonValue(ElemTy, CanUseAnyVectorRank));
3822 propagateElemType(Arg, IntegerType::getInt8Ty(F->getContext()),
3823 VisitedSubst);
3824 } else {
3825 GR->buildAssignPtr(B, ElemTy, Arg);
3826 }
3827 }
3828 }
3829}
3830
3832 SPIRVGlobalRegistry *GR) {
3833 FunctionType *FTy = F->getFunctionType();
3834 bool IsNewFTy = false;
3836 for (Argument &Arg : F->args()) {
3837 Type *ArgTy = Arg.getType();
3838 if (ArgTy->isPointerTy())
3839 if (Type *ElemTy = GR->findDeducedElementType(&Arg)) {
3840 IsNewFTy = true;
3842 }
3843 ArgTys.push_back(ArgTy);
3844 }
3845 return IsNewFTy
3846 ? FunctionType::get(FTy->getReturnType(), ArgTys, FTy->isVarArg())
3847 : FTy;
3848}
3849
3850bool SPIRVEmitIntrinsicsImpl::processFunctionPointers(Module &M) {
3851 SmallVector<Function *> Worklist;
3852 for (auto &F : M) {
3853 if (F.isIntrinsic())
3854 continue;
3855 if (F.isDeclaration()) {
3856 for (User *U : F.users()) {
3857 // SPIR-V has no personality, so it is not a function pointer use.
3858 if (auto *UF = dyn_cast<Function>(U);
3859 UF && UF->hasPersonalityFn() && UF->getPersonalityFn() == &F)
3860 continue;
3861 CallInst *CI = dyn_cast<CallInst>(U);
3862 if (!CI || CI->getCalledFunction() != &F) {
3863 Worklist.push_back(&F);
3864 break;
3865 }
3866 }
3867 } else {
3868 if (F.user_empty())
3869 continue;
3870 Type *FPElemTy = GR->findDeducedElementType(&F);
3871 if (!FPElemTy)
3872 FPElemTy = getFunctionPointerElemType(&F, GR);
3873 for (User *U : F.users()) {
3874 IntrinsicInst *II = dyn_cast<IntrinsicInst>(U);
3875 if (!II || II->arg_size() != 3 || II->getOperand(0) != &F)
3876 continue;
3877 if (II->getIntrinsicID() == Intrinsic::spv_assign_ptr_type ||
3878 II->getIntrinsicID() == Intrinsic::spv_ptrcast) {
3879 GR->updateAssignType(
3880 II, &F, getNormalizedPoisonValue(FPElemTy, CanUseAnyVectorRank));
3881 break;
3882 }
3883 }
3884 }
3885 }
3886 if (Worklist.empty())
3887 return false;
3888
3889 LLVMContext &Ctx = M.getContext();
3891 BasicBlock *BB = BasicBlock::Create(Ctx, "entry", SF);
3892 IRBuilder<> IRB(BB);
3893
3894 for (Function *F : Worklist) {
3896 for (const auto &Arg : F->args())
3897 Args.push_back(
3898 getNormalizedPoisonValue(Arg.getType(), CanUseAnyVectorRank));
3899 IRB.CreateCall(F, Args)->setTailCall(true);
3900 }
3901 IRB.CreateRetVoid();
3902
3903 return true;
3904}
3905
3906// Apply types parsed from demangled function declarations.
3907void SPIRVEmitIntrinsicsImpl::applyDemangledPtrArgTypes(IRBuilder<> &B) {
3908 DenseMap<Function *, CallInst *> Ptrcasts;
3909 for (auto It : FDeclPtrTys) {
3910 Function *F = It.first;
3911 for (auto *U : F->users()) {
3912 CallInst *CI = dyn_cast<CallInst>(U);
3913 if (!CI || CI->getCalledFunction() != F)
3914 continue;
3915 unsigned Sz = CI->arg_size();
3916 for (auto [Idx, ElemTy] : It.second) {
3917 if (Idx >= Sz)
3918 continue;
3919 Value *Param = CI->getArgOperand(Idx);
3920 if (GR->findDeducedElementType(Param) || isa<GlobalValue>(Param))
3921 continue;
3922 if (Argument *Arg = dyn_cast<Argument>(Param)) {
3923 if (!hasPointeeTypeAttr(Arg)) {
3924 B.SetInsertPointPastAllocas(Arg->getParent());
3925 B.SetCurrentDebugLocation(DebugLoc());
3926 GR->buildAssignPtr(B, ElemTy, Arg);
3927 }
3928 } else if (isaGEP(Param) || isa<AllocaInst>(Param)) {
3929 // The allocated type defines the size of an alloca, so cast at the
3930 // call instead of overriding its pointee type.
3931 replaceUsesOfWithSpvPtrcast(
3932 Param, normalizeType(ElemTy, CanUseAnyVectorRank), CI, Ptrcasts);
3933 } else if (isa<Instruction>(Param)) {
3934 GR->addDeducedElementType(Param,
3935 normalizeType(ElemTy, CanUseAnyVectorRank));
3936 // insertAssignTypeIntrs() will complete buildAssignPtr()
3937 } else {
3938 B.SetInsertPoint(CI->getParent()
3939 ->getParent()
3940 ->getEntryBlock()
3941 .getFirstNonPHIOrAlloca());
3942 GR->buildAssignPtr(B, ElemTy, Param);
3943 }
3944 CallInst *Ref = dyn_cast<CallInst>(Param);
3945 if (!Ref)
3946 continue;
3947 Function *RefF = Ref->getCalledFunction();
3948 if (!RefF || !isPointerTy(RefF->getReturnType()) ||
3949 GR->findDeducedElementType(RefF))
3950 continue;
3951 ElemTy = normalizeType(ElemTy, CanUseAnyVectorRank);
3952 GR->addDeducedElementType(RefF, ElemTy);
3953 GR->addReturnType(
3955 ElemTy, getPointerAddressSpace(RefF->getReturnType())));
3956 }
3957 }
3958 }
3959 FDeclPtrTys.clear();
3960}
3961
3962GetElementPtrInst *SPIRVEmitIntrinsicsImpl::simplifyZeroLengthArrayGepInst(
3963 GetElementPtrInst *GEP) {
3964 // getelementptr [0 x T], P, 0 (zero), I -> getelementptr T, P, I.
3965 // If type is 0-length array and first index is 0 (zero), drop both the
3966 // 0-length array type and the first index. This is a common pattern in
3967 // the IR, e.g. when using a zero-length array as a placeholder for a
3968 // flexible array such as unbound arrays.
3969 assert(GEP && "GEP is null");
3970 Type *SrcTy = GEP->getSourceElementType();
3971 SmallVector<Value *, 8> Indices(GEP->indices());
3972 ArrayType *ArrTy = dyn_cast<ArrayType>(SrcTy);
3973 if (ArrTy && ArrTy->getNumElements() == 0 && match(Indices[0], m_Zero())) {
3974 Indices.erase(Indices.begin());
3975 SrcTy = ArrTy->getElementType();
3976 return GetElementPtrInst::Create(SrcTy, GEP->getPointerOperand(), Indices,
3977 GEP->getNoWrapFlags(), "",
3978 GEP->getIterator());
3979 }
3980 return nullptr;
3981}
3982
3983void SPIRVEmitIntrinsicsImpl::emitUnstructuredLoopControls(Function &F,
3984 IRBuilder<> &B) {
3985 const SPIRVSubtarget *ST = TM.getSubtargetImpl(F);
3986 // Shaders use SPIRVStructurizer which emits OpLoopMerge via spv_loop_merge.
3987 if (ST->isShader())
3988 return;
3989
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);
3995 if (!LoopMD)
3996 continue;
3997
3998 SmallVector<unsigned, 1> Ops =
4000 unsigned LC = Ops[0];
4001 if (LC == SPIRV::LoopControl::None)
4002 continue;
4003
4004 // Emit intrinsic: loop control mask + optional parameters.
4005 B.SetInsertPoint(Term);
4006 SmallVector<Value *, 4> IntrArgs;
4007 for (unsigned Op : Ops)
4008 IntrArgs.push_back(B.getInt32(Op));
4009 B.CreateIntrinsic(Intrinsic::spv_loop_control_intel, IntrArgs);
4010 }
4011 return;
4012 }
4013
4014 // For non-shader targets without the Intel extension, emit OpLoopMerge
4015 // using spv_loop_merge intrinsics, mirroring the structurizer approach.
4016 LoopInfo LI;
4017 LI.analyze(&F);
4018 if (LI.empty())
4019 return;
4020
4021 SmallPtrSet<BasicBlock *, 8> UsedMergeBlocks;
4022 for (Loop *L : LI.getLoopsInPreorder()) {
4023 BasicBlock *Latch = L->getLoopLatch();
4024 if (!Latch)
4025 continue;
4026
4027 // Check for loop unroll metadata on the latch terminator.
4028 SmallVector<unsigned, 1> LoopControlOps =
4030 if (LoopControlOps[0] == SPIRV::LoopControl::None)
4031 continue;
4032
4033 BasicBlock *Header = L->getHeader();
4034 // OpLoopMerge must immediately precede an OpBranch or OpBranchConditional.
4035 // Switches are already lowered to spv_switch + indirectbr at this point.
4036 if (!isa<UncondBrInst, CondBrInst>(Header->getTerminator()))
4037 continue;
4038
4039 BasicBlock *MergeBlock = L->getUniqueExitBlock();
4040 // LoopSimplify does not guarantee a unique exit block. Try the normal exit
4041 // of a rotated loop (from the latch), then an unrotated loop (from the
4042 // header). A merge block cannot be shared by multiple loop headers.
4043 for (BasicBlock *BB : {Latch, Header}) {
4044 if (MergeBlock || !isa<CondBrInst>(BB->getTerminator()))
4045 continue;
4046 for (BasicBlock *Succ : successors(BB))
4047 if (!L->contains(Succ) && !UsedMergeBlocks.contains(Succ))
4048 MergeBlock = Succ;
4049 }
4050 if (!MergeBlock || !UsedMergeBlocks.insert(MergeBlock).second)
4051 continue;
4052
4053 B.SetInsertPoint(Header->getTerminator());
4054 auto *MergeAddress = BlockAddress::get(&F, MergeBlock);
4055 auto *ContinueAddress = BlockAddress::get(&F, Latch);
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});
4060 }
4061}
4062
4063bool SPIRVEmitIntrinsicsImpl::runOnFunction(Function &Func) {
4064 if (Func.isDeclaration())
4065 return false;
4066
4067 const SPIRVSubtarget &ST = TM.getSubtarget<SPIRVSubtarget>(Func);
4068 // LoopSimplify runs after SPIRVPrepareFunctions sorted the blocks, and the
4069 // preheaders/dedicated exits it creates can end up before their dominator,
4070 // which SPIR-V forbids.
4071 if (!ST.isShader())
4072 sortBlocks(Func);
4073 GR = ST.getSPIRVGlobalRegistry();
4074
4075 if (!CurrF)
4076 HaveFunPtrs =
4077 ST.canUseExtension(SPIRV::Extension::SPV_INTEL_function_pointers);
4078
4079 CanUseAnyVectorRank =
4080 ST.canUseExtension(SPIRV::Extension::SPV_EXT_long_vector);
4081 CurrF = &Func;
4082 IRBuilder<> B(*Func.getParent());
4083 AggrConsts.clear();
4084 AggrConstTypes.clear();
4085 AggrStores.clear();
4086
4087 scalarizeVectorPtrCasts(Func);
4088 processParamTypesByFunHeader(CurrF, B);
4089
4090 if (ST.isLogicalSPIRV())
4091 foldConstantOffsetIntoArrayIndex(Func);
4092
4093 // Fix GEP result types ahead of inference, and simplify if possible.
4094 // Data structure for dead instructions that were simplified and replaced.
4095 SmallPtrSet<Instruction *, 4> DeadInsts;
4096 for (auto &I : instructions(Func)) {
4097 if (StoreInst *SI = dyn_cast<StoreInst>(&I)) {
4098 Type *ElTy = SI->getValueOperand()->getType();
4099 if (ElTy->isAggregateType() || ElTy->isVectorTy())
4100 AggrStores.insert(&I);
4101 continue;
4102 }
4103
4105 auto *SGEP = dyn_cast<StructuredGEPInst>(&I);
4106
4107 if ((!GEP && !SGEP) || GR->findDeducedElementType(&I))
4108 continue;
4109
4110 if (SGEP) {
4112 SGEP,
4113 normalizeType(SGEP->getResultElementType(), CanUseAnyVectorRank));
4114 continue;
4115 }
4116
4117 GetElementPtrInst *NewGEP = simplifyZeroLengthArrayGepInst(GEP);
4118 if (NewGEP) {
4119 GEP->replaceAllUsesWith(NewGEP);
4120 DeadInsts.insert(GEP);
4121 GEP = NewGEP;
4122 }
4123 if (Type *GepTy = getGEPType(GEP))
4124 GR->addDeducedElementType(GEP, normalizeType(GepTy, CanUseAnyVectorRank));
4125 }
4126 // Remove dead instructions that were simplified and replaced.
4127 for (auto *I : DeadInsts) {
4128 assert(I->use_empty() && "Dead instruction should not have any uses left");
4129 I->eraseFromParent();
4130 }
4131 if (AccessChainErrors)
4132 return true;
4133
4134 B.SetInsertPoint(Func.getEntryBlock().begin());
4135 for (auto &GV : Func.getParent()->globals())
4136 processGlobalValue(GV, B);
4137
4138 reconstructAggregateReturns(Func, B);
4139 // Before preprocessUndefsAndPoisons, which gives the poison starting each
4140 // chain a typed placeholder.
4141 for (Instruction &I : instructions(Func))
4143 insertCompositeAggregateArms(&I, B);
4144 preprocessUndefsAndPoisons(B);
4145 simplifyNullAddrSpaceCasts();
4146 preprocessCompositeConstants(B);
4147
4148 // A PHINode, SelectInst or FreezeInst takes its result type from its
4149 // operands. Aggregate arms are lowered to i32 value-ids (composite constants
4150 // here, loads and other producers during the visitor pass below), so mutate
4151 // an aggregate PHI, select or freeze to match. The original type is tracked
4152 // in AggrConstTypes (used to assign the SPIR-V type) and its extractvalue
4153 // users are lowered to spv_extractv.
4154 Type *I32Ty = B.getInt32Ty();
4155 for (Instruction &I : instructions(Func)) {
4157 continue;
4158 AggrConstTypes[&I] = I.getType();
4159 I.mutateType(I32Ty);
4160 }
4161
4162 preprocessBoolVectorBitcasts(Func);
4163 SmallVector<Instruction *> Worklist(
4165
4166 applyDemangledPtrArgTypes(B);
4167
4168 // Pass forward: use operand to deduce instructions result.
4169 for (auto &I : Worklist) {
4170 // Don't emit intrinsincs for convergence intrinsics.
4171 if (isConvergenceIntrinsic(I))
4172 continue;
4173
4174 bool Postpone = insertAssignPtrTypeIntrs(I, B, false);
4175 // if Postpone is true, we can't decide on pointee type yet
4176 insertAssignTypeIntrs(I, B);
4177 insertPtrCastOrAssignTypeInstr(I, B);
4179 // if instruction requires a pointee type set, let's check if we know it
4180 // already, and force it to be i8 if not
4181 if (Postpone && !GR->findAssignPtrTypeInstr(I))
4182 insertAssignPtrTypeIntrs(I, B, true);
4183
4184 if (auto *FPI = dyn_cast<ConstrainedFPIntrinsic>(I))
4185 useRoundingMode(FPI, B);
4186 }
4187
4188 // Pass backward: use instructions results to specify/update/cast operands
4189 // where needed.
4190 SmallPtrSet<Instruction *, 4> IncompleteRets;
4191 for (auto &I : llvm::reverse(instructions(Func)))
4192 deduceOperandElementType(&I, &IncompleteRets);
4193
4194 // Pass forward for PHIs only, their operands are not preceed the
4195 // instruction in meaning of `instructions(Func)`.
4196 for (BasicBlock &BB : Func)
4197 for (PHINode &Phi : BB.phis())
4198 if (isPointerTy(Phi.getType()))
4199 deduceOperandElementType(&Phi, nullptr);
4200
4201 for (auto *I : Worklist) {
4202 TrackConstants = true;
4203 if (!I->getType()->isVoidTy() || isa<StoreInst>(I))
4205 // Visitors return either the original/newly created instruction for
4206 // further processing, nullptr otherwise.
4207 I = visit(*I);
4208 if (AccessChainErrors)
4209 return true;
4210 if (!I)
4211 continue;
4212
4213 // Don't emit intrinsics for convergence operations.
4214 if (isConvergenceIntrinsic(I))
4215 continue;
4216
4218 processInstrAfterVisit(I, B);
4219 }
4220
4221 emitUnstructuredLoopControls(Func, B);
4222
4223 return true;
4224}
4225
4226// Try to deduce a better type for pointers to untyped ptr.
4227bool SPIRVEmitIntrinsicsImpl::postprocessTypes(Module &M) {
4228 if (!GR || TodoTypeSz == 0)
4229 return false;
4230
4231 unsigned SzTodo = TodoTypeSz;
4232 DenseMap<Value *, SmallPtrSet<Value *, 4>> ToProcess;
4233 for (auto [Op, Enabled] : TodoType) {
4234 // TODO: add isa<CallInst>(Op) to continue
4235 if (!Enabled || isaGEP(Op))
4236 continue;
4237 CallInst *AssignCI = GR->findAssignPtrTypeInstr(Op);
4238 Type *KnownTy = GR->findDeducedElementType(Op);
4239 if (!KnownTy || !AssignCI)
4240 continue;
4241 assert(Op == AssignCI->getArgOperand(0));
4242 // Try to improve the type deduced after all Functions are processed.
4243 if (auto *CI = dyn_cast<Instruction>(Op)) {
4244 CurrF = CI->getParent()->getParent();
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);
4250 eraseTodoType(Op);
4251 continue;
4252 }
4253 }
4254 }
4255
4256 if (Op->hasUseList()) {
4257 for (User *U : Op->users()) {
4259 if (Inst && !isa<IntrinsicInst>(Inst))
4260 ToProcess[Inst].insert(Op);
4261 }
4262 }
4263 }
4264 if (TodoTypeSz == 0)
4265 return true;
4266
4267 for (auto &F : M) {
4268 CurrF = &F;
4269 SmallPtrSet<Instruction *, 4> IncompleteRets;
4270 for (auto &I : llvm::reverse(instructions(F))) {
4271 auto It = ToProcess.find(&I);
4272 if (It == ToProcess.end())
4273 continue;
4274 It->second.remove_if([this](Value *V) { return !isTodoType(V); });
4275 if (It->second.size() == 0)
4276 continue;
4277 deduceOperandElementType(&I, &IncompleteRets, &It->second, true);
4278 if (TodoTypeSz == 0)
4279 return true;
4280 }
4281 }
4282
4283 return SzTodo > TodoTypeSz;
4284}
4285
4286// Parse unambiguous scalar/vector pointees, e.g. "float vector[4] const*".
4288 if (!TypeStr.consume_back("*") && !TypeStr.consume_back("&"))
4289 return nullptr;
4290 StringRef ScalarName = TypeStr;
4291 Type *ElemTy = parseBasicTypeName(TypeStr, Ctx);
4292 if (!ElemTy || ElemTy->isVoidTy() || ElemTy->isIntegerTy(1))
4293 return nullptr;
4294 ScalarName = ScalarName.drop_back(TypeStr.size());
4295 // OpenCL aliases such as uint can also name C++ classes.
4296 if (!StringSwitch<bool>(ScalarName)
4297 .Cases({"char", "signed char", "unsigned char", "short",
4298 "unsigned short", "int", "unsigned int", "_Float16", "float",
4299 "double"},
4300 true)
4301 .Default(false) ||
4302 (!TypeStr.empty() && !TypeStr.starts_with(" ")))
4303 return nullptr;
4304 if (TypeStr.consume_front(" vector[")) {
4305 auto [Count, Rest] = TypeStr.split(']');
4306 unsigned NumElts = 0;
4307 if (Count.getAsInteger(10, NumElts) || NumElts == 0)
4308 return nullptr;
4310 TypeStr = Rest;
4311 }
4312 // Only cv and address space qualifiers may follow.
4314 TypeStr.split(Quals, ' ', -1, /*KeepEmpty=*/false);
4315 for (StringRef Qual : Quals) {
4316 unsigned AS;
4317 if (Qual != "const" && Qual != "volatile" && Qual != "restrict" &&
4318 !(Qual.consume_front("AS") && !Qual.getAsInteger(10, AS)))
4319 return nullptr;
4320 }
4321 return ElemTy;
4322}
4323
4324// Parse and store argument types of function declarations where needed.
4325void SPIRVEmitIntrinsicsImpl::parseFunDeclarations(Module &M) {
4326 for (auto &F : M) {
4327 if (!F.isDeclaration() || F.isIntrinsic())
4328 continue;
4329 std::string DemangledName = getOclOrSpirvBuiltinDemangledName(F.getName());
4330 if (DemangledName.empty())
4331 continue;
4332 const SPIRVSubtarget &ST = TM.getSubtarget<SPIRVSubtarget>(F);
4333 auto Set = ST.getPreferredInstructionSet();
4334 auto [Grp, Opcode, ExtNo] = SPIRV::mapBuiltinToOpcode(DemangledName, Set);
4335 // Some builtins have no opcode mapping.
4336 const bool IsBuiltin = Grp >= 0 || SPIRV::isBuiltin(DemangledName, Set);
4337 if (IsBuiltin && Opcode != SPIRV::OpGroupAsyncCopy)
4338 continue;
4339 SmallVector<unsigned> Idxs;
4340 for (Argument &Arg : F.args())
4341 if (isPointerTy(Arg.getType()) && !hasPointeeTypeAttr(&Arg))
4342 Idxs.push_back(Arg.getArgNo());
4343 if (Idxs.empty())
4344 continue;
4345 LLVMContext &Ctx = F.getContext();
4347 SPIRV::parseBuiltinTypeStr(TypeStrs, DemangledName, Ctx);
4348 if (TypeStrs.empty())
4349 continue;
4350 // Avoid nested signatures and hidden ABI arguments such as this and sret.
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()))
4356 continue;
4357 bool AllowLongVectors =
4358 ST.canUseExtension(SPIRV::Extension::SPV_EXT_long_vector);
4359 for (unsigned Idx : Idxs) {
4360 if (Idx >= TypeStrs.size())
4361 continue;
4362 StringRef TypeStr = TypeStrs[Idx].trim();
4363 Type *ElemTy = IsBuiltin
4364 ? SPIRV::parseBuiltinCallArgumentType(TypeStr, Ctx)
4365 : parseDeclPtrElemType(TypeStr, Ctx);
4366 if (!ElemTy || !TypedPointerType::isValidElementType(ElemTy) ||
4367 ElemTy->isTargetExtTy())
4368 continue;
4369 if (!IsBuiltin) {
4370 ElemTy = normalizeType(ElemTy, AllowLongVectors);
4371 if (!AllowLongVectors && isLongVectorEXT(ElemTy))
4372 continue;
4373 }
4374 FDeclPtrTys[&F].emplace_back(Idx, ElemTy);
4375 if (!IsBuiltin)
4376 ST.getSPIRVGlobalRegistry()->addDeducedElementType(F.getArg(Idx),
4377 ElemTy);
4378 }
4379 }
4380}
4381
4382bool SPIRVEmitIntrinsicsImpl::processMaskedMemIntrinsic(IntrinsicInst &I) {
4383 const SPIRVSubtarget &ST = TM.getSubtarget<SPIRVSubtarget>(*I.getFunction());
4384
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 "
4390 "extension");
4391 // Replace with poison to allow compilation to continue and report error.
4392 I.replaceAllUsesWith(PoisonValue::get(I.getType()));
4393 I.eraseFromParent();
4394 return true;
4395 }
4396
4397 IRBuilder<> B(&I);
4398
4399 Value *Ptrs = I.getArgOperand(0);
4400 Value *Mask = I.getArgOperand(1);
4401 Value *Passthru = I.getArgOperand(2);
4402
4403 // Alignment is stored as a parameter attribute, not as a regular parameter.
4404 uint32_t Alignment = I.getParamAlign(0).valueOrOne().value();
4405
4406 SmallVector<Value *, 4> Args = {Ptrs, B.getInt32(Alignment), Mask,
4407 Passthru};
4408 SmallVector<Type *, 4> Types = {I.getType(), Ptrs->getType(),
4409 Mask->getType(), Passthru->getType()};
4410
4411 auto *NewI = B.CreateIntrinsic(Intrinsic::spv_masked_gather, Types, Args);
4412 I.replaceAllUsesWith(NewI);
4413 I.eraseFromParent();
4414 return true;
4415 }
4416
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 "
4422 "extension");
4423 // Erase the intrinsic to allow compilation to continue and report error.
4424 I.eraseFromParent();
4425 return true;
4426 }
4427
4428 IRBuilder<> B(&I);
4429
4430 Value *Values = I.getArgOperand(0);
4431 Value *Ptrs = I.getArgOperand(1);
4432 Value *Mask = I.getArgOperand(2);
4433
4434 // Alignment is stored as a parameter attribute on the ptrs parameter (arg
4435 // 1).
4436 uint32_t Alignment = I.getParamAlign(1).valueOrOne().value();
4437
4438 SmallVector<Value *, 4> Args = {Values, Ptrs, B.getInt32(Alignment), Mask};
4439 SmallVector<Type *, 3> Types = {Values->getType(), Ptrs->getType(),
4440 Mask->getType()};
4441
4442 B.CreateIntrinsic(Intrinsic::spv_masked_scatter, Types, Args);
4443 I.eraseFromParent();
4444 return true;
4445 }
4446
4447 return false;
4448}
4449
4450// SPIR-V doesn't support bitcasts involving vector boolean type. Decompose such
4451// bitcasts into element-wise operations before building instructions
4452// worklist, so new instructions are properly visited and converted to
4453// SPIR-V intrinsics.
4454void SPIRVEmitIntrinsicsImpl::preprocessBoolVectorBitcasts(Function &F) {
4455 struct BoolVecBitcast {
4456 BitCastInst *BC;
4457 FixedVectorType *BoolVecTy;
4458 bool SrcIsBoolVec;
4459 };
4460
4461 auto getAsBoolVec = [](Type *Ty) -> FixedVectorType * {
4462 auto *VTy = dyn_cast<FixedVectorType>(Ty);
4463 return (VTy && VTy->getElementType()->isIntegerTy(1)) ? VTy : nullptr;
4464 };
4465
4467 for (auto &I : instructions(F)) {
4468 auto *BC = dyn_cast<BitCastInst>(&I);
4469 if (!BC)
4470 continue;
4471 if (auto *BVTy = getAsBoolVec(BC->getSrcTy()))
4472 ToReplace.push_back({BC, BVTy, true});
4473 else if (auto *BVTy = getAsBoolVec(BC->getDestTy()))
4474 ToReplace.push_back({BC, BVTy, false});
4475 }
4476
4477 for (auto &[BC, BoolVecTy, SrcIsBoolVec] : ToReplace) {
4478 IRBuilder<> B(BC);
4479 Value *Src = BC->getOperand(0);
4480 unsigned BoolVecN = BoolVecTy->getNumElements();
4481 // Convert per element of the other side, as iN can exceed the maximum
4482 // SPIR-V integer width.
4483 Type *OtherTy = SrcIsBoolVec ? BC->getDestTy() : Src->getType();
4484 unsigned NumElts = 1;
4485 if (auto *VTy = dyn_cast<FixedVectorType>(OtherTy))
4486 NumElts = VTy->getNumElements();
4487 unsigned EltBits = OtherTy->getScalarSizeInBits();
4488 Type *EltTy = B.getIntNTy(EltBits);
4489 Type *IntTy = NumElts > 1 ? FixedVectorType::get(EltTy, NumElts) : EltTy;
4490
4491 Value *Result;
4492 if (!SrcIsBoolVec) {
4493 Value *IntVal = B.CreateBitCast(Src, IntTy);
4494 // Lane I is bit I % EltBits of element I / EltBits.
4495 auto GetLane = [&](unsigned I) {
4496 Value *Elt = IntVal;
4497 if (NumElts > 1)
4498 Elt = B.CreateExtractElement(IntVal, B.getInt32(I / EltBits));
4499 Value *Mask =
4500 ConstantInt::get(EltTy, APInt::getOneBitSet(EltBits, I % EltBits));
4501 Value *And = B.CreateAnd(Elt, Mask);
4502 return B.CreateICmpNE(And, ConstantInt::get(EltTy, 0));
4503 };
4504
4505 // Compute constant-index extracts directly, as no later pass removes
4506 // the unused lanes.
4507 for (User *U : make_early_inc_range(BC->users())) {
4508 auto *EE = dyn_cast<ExtractElementInst>(U);
4509 auto *Idx = EE ? dyn_cast<ConstantInt>(EE->getIndexOperand()) : nullptr;
4510 if (!Idx || Idx->getValue().uge(BoolVecN))
4511 continue;
4512 B.SetInsertPoint(EE);
4513 EE->replaceAllUsesWith(GetLane(Idx->getZExtValue()));
4514 EE->eraseFromParent();
4515 }
4516 if (BC->use_empty()) {
4517 BC->eraseFromParent();
4518 continue;
4519 }
4520
4521 B.SetInsertPoint(BC);
4522 Result = PoisonValue::get(BoolVecTy);
4523 for (unsigned I = 0; I < BoolVecN; ++I)
4524 Result = B.CreateInsertElement(Result, GetLane(I), B.getInt32(I));
4525 } else {
4526 // Build each element from its lanes.
4527 Value *IntVal = PoisonValue::get(IntTy);
4528 for (unsigned J = 0; J < NumElts; ++J) {
4529 Value *Elt = ConstantInt::get(EltTy, 0);
4530 for (unsigned Bit = 0; Bit < EltBits; ++Bit) {
4531 Value *Lane =
4532 B.CreateExtractElement(Src, B.getInt32(J * EltBits + Bit));
4533 Value *Ext = B.CreateZExt(Lane, EltTy);
4534 if (Bit > 0)
4535 Ext = B.CreateShl(Ext, ConstantInt::get(EltTy, Bit));
4536 Elt = B.CreateOr(Elt, Ext);
4537 }
4538 IntVal = NumElts > 1 ? B.CreateInsertElement(IntVal, Elt, B.getInt32(J))
4539 : Elt;
4540 }
4541 Result = B.CreateBitCast(IntVal, BC->getDestTy());
4542 }
4543
4544 BC->replaceAllUsesWith(Result);
4545 BC->eraseFromParent();
4546 }
4547}
4548
4549bool SPIRVEmitIntrinsicsImpl::convertMaskedMemIntrinsics(Module &M) {
4550 bool Changed = false;
4551
4552 for (Function &F : make_early_inc_range(M)) {
4553 if (!F.isIntrinsic())
4554 continue;
4555 Intrinsic::ID IID = F.getIntrinsicID();
4556 if (IID != Intrinsic::masked_gather && IID != Intrinsic::masked_scatter)
4557 continue;
4558
4559 for (User *U : make_early_inc_range(F.users())) {
4560 if (auto *II = dyn_cast<IntrinsicInst>(U))
4561 Changed |= processMaskedMemIntrinsic(*II);
4562 }
4563
4564 if (F.use_empty())
4565 F.eraseFromParent();
4566 }
4567
4568 return Changed;
4569}
4570
4571bool SPIRVEmitIntrinsicsImpl::preprocessModule(Module &M) {
4572 bool Changed = false;
4575 Type *I32Ty = Type::getInt32Ty(M.getContext());
4576 for (Function &F : M) {
4577 if (F.isDeclaration())
4578 continue;
4579 for (Instruction &I : instructions(F)) {
4580 if (IsLogical)
4581 for (Value *Op : I.operands())
4582 if (auto *CE = dyn_cast<ConstantExpr>(Op);
4583 CE && CE->getOpcode() == Instruction::GetElementPtr)
4584 GEPs.push_back(CE);
4585
4586 // Only entry-block allocations execute once per call, so a single array
4587 // object has the same meaning as the counted allocation. Allocations in
4588 // other blocks keep their lowering.
4589 auto *AI = dyn_cast<AllocaInst>(&I);
4590 if (!AI || !AI->isStaticAlloca() || !AI->isArrayAllocation() ||
4591 AI->getAddressSpace() !=
4592 storageClassToAddressSpace(SPIRV::StorageClass::Function))
4593 continue;
4594 auto *Count = cast<ConstantInt>(AI->getArraySize());
4595 // Zero sizes are legalized earlier; array lengths must fit in 32 bits.
4596 if (Count->isZero() || !Count->getValue().isIntN(32))
4597 continue;
4598 AI->setAllocatedType(
4599 ArrayType::get(AI->getAllocatedType(), Count->getZExtValue()));
4600 AI->setOperand(0, ConstantInt::get(I32Ty, 1));
4601 Changed = true;
4602 }
4603 }
4604 Changed |= convertMaskedMemIntrinsics(M);
4605
4606 // Materialize GEPs before pointer type inference so logical targets use
4607 // the typed access-chain lowering. Physical targets keep the existing
4608 // constant-expression handling.
4609 if (IsLogical) {
4610 // The list can contain both a constant and its users.
4612 GEPs, nullptr, /*RemoveDeadConstants=*/false, /*IncludeSelf=*/true);
4613 }
4614 return Changed;
4615}
4616
4617bool SPIRVEmitIntrinsicsImpl::runOnModule(Module &M) {
4618 bool Changed = preprocessModule(M);
4619
4620 parseFunDeclarations(M);
4621 insertConstantsForFPFastMathDefault(M);
4622 GVUsers.init(M);
4623
4624 TodoType.clear();
4625 for (auto &F : M)
4627 if (AccessChainErrors)
4628 report_fatal_error(Twine(toString(std::move(AccessChainErrors))), false);
4629
4630 // Specify function parameters after all functions were processed.
4631 for (auto &F : M) {
4632 // check if function parameter types are set
4633 CurrF = &F;
4634 if (!F.isDeclaration() && !F.isIntrinsic()) {
4635 IRBuilder<> B(M);
4636 processParamTypes(&F, B);
4637 }
4638 }
4639
4640 CanTodoType = false;
4641 Changed |= postprocessTypes(M);
4642
4643 if (HaveFunPtrs)
4644 Changed |= processFunctionPointers(M);
4645
4646 return Changed;
4647}
4648
4649PreservedAnalyses
4651 if (SPIRVEmitIntrinsicsImpl(TM).runOnModule(M))
4652 return PreservedAnalyses::none();
4653 return PreservedAnalyses::all();
4654}
4655
4657 return new SPIRVEmitIntrinsicsLegacy(TM);
4658}
const TargetLowering & TLI
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
aarch64 promote const
uint64_t uint64_t
uint64_t Imm
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
always inline
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)
Hexagon Common GEP
iv Induction Variable Users
Definition IVUsers.cpp:48
const AbstractManglingParser< Derived, Alloc >::OperatorInfo AbstractManglingParser< Derived, Alloc >::Ops[]
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
Machine Check Debug Module
This file implements a map that provides insertion order iteration.
#define T
uint64_t IntrinsicInst * II
OptimizedStructLayoutField Field
if(PassOpts->AAPipeline)
#define INITIALIZE_PASS(passName, arg, name, cfg, analysis)
Definition PassSupport.h:56
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)
Definition Value.cpp:479
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...
DEMANGLE_NAMESPACE_BEGIN bool starts_with(std::string_view self, char C) noexcept
#define LLVM_DEBUG(...)
Definition Debug.h:119
static SymbolRef::Type getType(const Symbol *Sym)
Definition TapiFile.cpp:39
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.
Definition APInt.h:235
This class represents an incoming formal argument to a Function.
Definition Argument.h:32
const Function * getParent() const
Definition Argument.h:44
unsigned getArgNo() const
Return the index of this formal argument in its containing function.
Definition Argument.h:50
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
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.
Definition BasicBlock.h:509
const Function * getParent() const
Return the enclosing method, or null if none.
Definition BasicBlock.h:213
static BasicBlock * Create(LLVMContext &Context, const Twine &Name="", Function *Parent=nullptr, BasicBlock *InsertBefore=nullptr)
Creates a new BasicBlock.
Definition BasicBlock.h:206
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.
Definition BasicBlock.h:237
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 ConstantAsMetadata * get(Constant *C)
Definition Metadata.h:549
static ConstantInt * getSigned(IntegerType *Ty, int64_t V, bool ImplicitTrunc=false)
Return a ConstantInt with the specified value for the specified type.
Definition Constants.h:135
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
unsigned getProgramAddressSpace() const
Definition DataLayout.h:272
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)
Definition DenseMap.h:766
iterator end()
Definition DenseMap.h:686
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.
Definition DenseMap.h:793
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
Definition DenseMap.h:827
std::pair< iterator, bool > try_emplace(KeyT &&Key, Ts &&...Args)
Definition DenseMap.h:856
static ErrorSuccess success()
Create a success value.
Definition Error.h:336
static ExtractElementInst * Create(Value *Vec, Value *Idx, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
static LLVM_ABI Type * getIndexedType(Type *Agg, ArrayRef< unsigned > Idxs)
Returns the type of the element that would be extracted with an extractvalue instruction with the spe...
static LLVM_ABI FixedVectorType * get(Type *ElementType, unsigned NumElts)
Definition Type.cpp:838
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.
Definition Function.cpp:356
iterator begin()
Definition Function.h:847
bool isIntrinsic() const
isIntrinsic - Returns true if the function's name starts with "llvm.".
Definition Function.h:252
LLVMContext & getContext() const
getContext - Return a reference to the LLVMContext associated with this function.
Definition Function.cpp:352
size_t arg_size() const
Definition Function.h:895
Type * getReturnType() const
Returns the type of the ret val.
Definition Function.h:217
Argument * getArg(unsigned i) const
Definition Function.h:880
Represents flags for the getelementptr instruction/expression.
static GEPNoWrapFlags inBounds()
bool isInBounds() const
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...
Definition Globals.cpp:408
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).
Definition GlobalValue.h:60
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...
Definition IRBuilder.h:2990
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.
Definition InstVisitor.h:78
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.
Definition LLVMContext.h:76
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.
Metadata node.
Definition Metadata.h:1087
const MDOperand & getOperand(unsigned I) const
Definition Metadata.h:1443
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Definition Metadata.h:1588
unsigned getNumOperands() const
Return number of MDNode operands.
Definition Metadata.h:1449
static LLVM_ABI MDString * get(LLVMContext &Context, StringRef Str)
Definition Metadata.cpp:595
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.
Definition MapVector.h:39
iterator find(const KeyT &Key)
Definition MapVector.h:157
iterator end()
Definition MapVector.h:70
static LLVM_ABI MetadataAsValue * get(LLVMContext &Context, Metadata *MD)
Definition Metadata.cpp:105
Metadata * getMetadata() const
Definition Metadata.h:203
ModulePass class - This class is used to implement unstructured interprocedural optimizations and ana...
Definition Pass.h:253
A Module instance is used to store all the information related to an LLVM module.
Definition Module.h:68
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.
Definition Analysis.h:115
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition Analysis.h:118
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
iterator end() 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 end()
Definition StringMap.h:214
iterator find(StringRef Key)
Definition StringMap.h:227
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
std::pair< StringRef, StringRef > split(char Separator) const
Split into two substrings around the first occurrence of a separator character.
Definition StringRef.h:728
bool consume_back(StringRef Suffix)
Returns true if this StringRef has the given suffix and removes that suffix.
Definition StringRef.h:683
bool starts_with(StringRef Prefix) const
Check if this string starts with the given Prefix.
Definition StringRef.h:258
constexpr bool empty() const
Check if the string is empty.
Definition StringRef.h:141
constexpr size_t size() const
Get the string size.
Definition StringRef.h:144
bool consume_front(char Prefix)
Returns true if this StringRef has the given prefix and removes that prefix.
Definition StringRef.h:653
StringRef drop_back(size_t N=1) const
Return a StringRef equal to 'this' but with the last N elements dropped.
Definition StringRef.h:634
A switch()-like statement whose cases are string literals.
static LLVM_ABI StructType * create(LLVMContext &Context, StringRef Name)
This creates an identified struct.
Definition Type.cpp:657
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.
Definition Type.cpp:931
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.
Definition Triple.h:523
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:46
bool isVectorTy() const
True if this is an instance of VectorType.
Definition Type.h:283
bool isArrayTy() const
True if this is an instance of ArrayType.
Definition Type.h:274
static LLVM_ABI IntegerType * getInt32Ty(LLVMContext &C)
Definition Type.cpp:294
bool isPointerTy() const
True if this is an instance of PointerType.
Definition Type.h:277
Type * getArrayElementType() const
Definition Type.h:427
bool isSized() const
Return true if it makes sense to take the size of this type.
Definition Type.h:321
LLVM_ABI StringRef getTargetExtName() const
unsigned getScalarSizeInBits() const LLVM_READONLY
If this is a vector type, return the getPrimitiveSizeInBits value for the element type.
Definition Type.h:354
static LLVM_ABI IntegerType * getInt8Ty(LLVMContext &C)
Definition Type.cpp:292
Type * getScalarType() const
If this is a vector type, return the element type, otherwise return 'this'.
Definition Type.h:370
bool isStructTy() const
True if this is an instance of StructType.
Definition Type.h:271
bool isTargetExtTy() const
Return true if this is a target extension type.
Definition Type.h:205
bool isAggregateType() const
Return true if the type is an aggregate type.
Definition Type.h:314
LLVMContext & getContext() const
Return the LLVMContext in which this type was uniqued.
Definition Type.h:130
bool isIntegerTy() const
True if this is an instance of IntegerType.
Definition Type.h:252
static LLVM_ABI IntegerType * getIntNTy(LLVMContext &C, unsigned N)
Definition Type.cpp:298
static LLVM_ABI Type * getDoubleTy(LLVMContext &C)
Definition Type.cpp:272
Type * getContainedType(unsigned i) const
This method is used to implement the type iterator (defined at the end of the file).
Definition Type.h:399
static LLVM_ABI Type * getFloatTy(LLVMContext &C)
Definition Type.cpp:271
static LLVM_ABI Type * getHalfTy(LLVMContext &C)
Definition Type.cpp:269
bool isVoidTy() const
Return true if this is 'void'.
Definition Type.h:141
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.
op_range operands()
Definition User.h:267
void setOperand(unsigned i, Value *Val)
Definition User.h:212
LLVM_ABI bool replaceUsesOfWith(Value *From, Value *To)
Replace uses of one Value with another.
Definition User.cpp:25
Value * getOperand(unsigned i) const
Definition User.h:207
unsigned getNumOperands() const
Definition User.h:229
LLVM Value Representation.
Definition Value.h:75
Type * getType() const
All values are typed, get the type of this value.
Definition Value.h:257
user_iterator user_begin()
Definition Value.h:404
LLVM_ABI void setName(const Twine &Name)
Change the name of the value.
Definition Value.cpp:389
LLVM_ABI void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
Definition Value.cpp:548
iterator_range< user_iterator > users()
Definition Value.h:428
user_iterator user_end()
Definition Value.h:412
void mutateType(Type *Ty)
Mutate the type of this Value to be of the specified type.
Definition Value.h:809
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
Definition Value.cpp:314
LLVM_ABI void takeName(Value *V)
Transfer the name from V to this value.
Definition Value.cpp:395
bool user_empty() const
Definition Value.h:391
const ParentTy * getParent() const
Definition ilist_node.h:34
CallInst * Call
#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.
@ Entry
Definition COFF.h:862
@ SPIR_KERNEL
Used for SPIR kernel functions.
@ BasicBlock
Various leaf nodes.
Definition ISDOpcodes.h:83
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)
Definition MCAsmInfo.h:51
initializer< Ty > init(const Ty &Val)
@ User
could "use" a pointer
NodeAddr< PhiNode * > Phi
Definition RDFGraph.h:390
NodeAddr< NodeBase * > Node
Definition RDFGraph.h:381
NodeAddr< FuncNode * > Func
Definition RDFGraph.h:393
friend class Instruction
Iterator for Instructions in a `BasicBlock.
Definition BasicBlock.h:73
unsigned getNumElements(Type *Ty)
Definition SLPUtils.cpp:117
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.
Definition STLExtras.h:316
@ Offset
Definition DWP.cpp:577
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1755
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)
Definition SPIRVUtils.h:414
RelativeUniformCounterPtr Values
Definition InstrProf.h:91
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,...
Definition STLExtras.h:2575
unsigned getPointerAddressSpace(const Type *T)
Definition SPIRVUtils.h:385
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
auto successors(const MachineBasicBlock *BB)
constexpr T divideFloorSigned(U Numerator, V Denominator)
Returns the integer floor(Numerator / Denominator).
Definition MathExtras.h:428
CallInst * buildIntrWithMD(Intrinsic::ID IntrID, ArrayRef< Type * > Types, Value *Arg, Value *Arg2, ArrayRef< Constant * > Imms, IRBuilder<> &B)
bool isUntypedPointerVectorTy(const Type *T)
Definition SPIRVUtils.h:378
void append_range(Container &C, Range &&R)
Wrapper function to append range R to container C.
Definition STLExtras.h:2229
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...
Definition STLExtras.h:649
bool sortBlocks(Function &F)
FPDecorationId
Definition SPIRVUtils.h:580
bool isa_and_nonnull(const Y &Val)
Definition Casting.h:676
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.
Definition Error.h:1321
SPIRV::MemorySemantics::MemorySemantics getMemSemanticsForStorageClass(SPIRV::StorageClass::StorageClass SC)
constexpr unsigned storageClassToAddressSpace(SPIRV::StorageClass::StorageClass SC)
Definition SPIRVUtils.h:238
bool isNestedPointer(const Type *Ty)
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Value
Definition InstrProf.h:143
Function * getOrCreateBackendServiceFunction(Module &M)
MetadataAsValue * buildMD(Value *Arg)
Definition SPIRVUtils.h:546
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)
Definition SPIRVUtils.h:528
auto reverse(ContainerTy &&C)
Definition STLExtras.h:408
Type * getTypedPointerWrapper(Type *ElemTy, unsigned AS)
Definition SPIRVUtils.h:409
Error joinErrors(Error E1, Error E2)
Concatenate errors.
Definition Error.h:442
bool isVector1(Type *Ty)
Definition SPIRVUtils.h:502
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
bool isPointerTy(const Type *T)
Definition SPIRVUtils.h:373
bool none_of(R &&Range, UnaryPredicate P)
Provide wrappers to std::none_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1769
IRBuilder(LLVMContext &, FolderTy, InserterTy) -> IRBuilder< FolderTy, InserterTy >
LLVM_ABI void report_fatal_error(Error Err, bool gen_crash_diag=true)
Definition Error.cpp:163
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...
Definition Casting.h:547
SPIRV::StorageClass::StorageClass addressSpaceToStorageClass(unsigned AddrSpace, const SPIRVSubtarget &STI)
@ Ref
The access may reference the value stored in memory.
Definition ModRef.h:32
@ And
Bitwise or logical AND of integers.
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Count
Definition InstrProf.h:145
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...
Definition STLExtras.h:2028
bool isLongVectorEXT(const Type *Ty, bool CanUseVector16=true)
Definition SPIRVUtils.h:519
Type * parseBasicTypeName(StringRef &TypeName, LLVMContext &Ctx)
DWARFExpression::Operation Op
Type * getPointeeTypeByAttr(Argument *Arg)
Definition SPIRVUtils.h:398
std::string toString(const APInt &I, unsigned Radix, bool Signed, bool formatAsCLiteral=false, bool UpperCase=true, bool InsertSeparators=false)
bool hasPointeeTypeAttr(Argument *Arg)
Definition SPIRVUtils.h:393
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...
Definition Local.cpp:537
constexpr unsigned BitWidth
bool isEquivalentTypes(Type *Ty1, Type *Ty2)
Definition SPIRVUtils.h:464
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
iterator_range< pointer_iterator< WrappedIteratorT > > make_pointer_range(RangeT &&Range)
Definition iterator.h:368
bool hasInitializer(const GlobalVariable *GV)
Definition SPIRVUtils.h:354
bool isPointerTyOrWrapper(const Type *Ty)
Definition SPIRVUtils.h:421
@ Enabled
Convert any .debug_str_offsets tables to DWARF64 if needed.
Definition DWP.h:31
bool isSpvIntrinsic(const MachineInstr &MI, Intrinsic::ID IntrinsicID)
PoisonValue * getNormalizedPoisonValue(Type *Ty, bool CanUseAnyVectorRank)
Definition SPIRVUtils.h:541
bool isUntypedPointerTy(const Type *T)
Definition SPIRVUtils.h:368
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.
Definition MIRParser.h:39
#define N
static size_t computeFPFastMathDefaultInfoVecIndex(size_t BitWidth)
Definition SPIRVUtils.h:149