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