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