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 Ty = deduceElementTypeByUsersDeep(Op, Visited, UnknownElemTypeI8);
1037 if (Ty)
1038 break;
1039 }
1040 } else if (auto *CI = dyn_cast<CallInst>(I)) {
1041 static StringMap<unsigned> ResTypeByArg = {
1042 {"to_global", 0},
1043 {"to_local", 0},
1044 {"to_private", 0},
1045 {"__spirv_GenericCastToPtr_ToGlobal", 0},
1046 {"__spirv_GenericCastToPtr_ToLocal", 0},
1047 {"__spirv_GenericCastToPtr_ToPrivate", 0},
1048 {"__spirv_GenericCastToPtrExplicit_ToGlobal", 0},
1049 {"__spirv_GenericCastToPtrExplicit_ToLocal", 0},
1050 {"__spirv_GenericCastToPtrExplicit_ToPrivate", 0}};
1051 // TODO: maybe improve performance by caching demangled names
1052
1053 auto *II = dyn_cast<IntrinsicInst>(I);
1054 if (II && (II->getIntrinsicID() == Intrinsic::spv_resource_getbasepointer ||
1055 II->getIntrinsicID() == Intrinsic::spv_resource_getpointer)) {
1056 auto *HandleType = cast<TargetExtType>(II->getOperand(0)->getType());
1057 if (HandleType->getTargetExtName() == "spirv.Image" ||
1058 HandleType->getTargetExtName() == "spirv.SignedImage") {
1059 for (User *U : II->users()) {
1060 Ty = cast<Instruction>(U)->getAccessType();
1061 if (Ty)
1062 break;
1063 }
1064 } else if (HandleType->getTargetExtName() == "spirv.VulkanBuffer") {
1065 // This call is supposed to index into an array
1066 Ty = HandleType->getTypeParameter(0);
1067 if (II->getIntrinsicID() == Intrinsic::spv_resource_getpointer) {
1068 if (Ty->isArrayTy())
1069 Ty = Ty->getArrayElementType();
1070 else {
1071 assert(Ty && Ty->isStructTy());
1072 uint32_t Index =
1073 cast<ConstantInt>(II->getOperand(1))->getZExtValue();
1074 Ty = cast<StructType>(Ty)->getElementType(Index);
1075 }
1076 }
1078 } else {
1079 llvm_unreachable("Unknown handle type for spv_resource_getpointer.");
1080 }
1081 } else if (II && II->getIntrinsicID() ==
1082 Intrinsic::spv_generic_cast_to_ptr_explicit) {
1083 Ty = deduceElementTypeHelper(CI->getArgOperand(0), Visited,
1084 UnknownElemTypeI8);
1085 } else if (Function *CalledF = CI->getCalledFunction()) {
1086 std::string DemangledName =
1087 getOclOrSpirvBuiltinDemangledName(CalledF->getName());
1088 if (DemangledName.length() > 0)
1089 DemangledName = SPIRV::lookupBuiltinNameHelper(DemangledName);
1090 auto AsArgIt = ResTypeByArg.find(DemangledName);
1091 if (AsArgIt != ResTypeByArg.end())
1092 Ty = deduceElementTypeHelper(CI->getArgOperand(AsArgIt->second),
1093 Visited, UnknownElemTypeI8);
1094 else if (Type *KnownRetTy = GR->findDeducedElementType(CalledF))
1095 Ty = KnownRetTy;
1096 }
1097 }
1098
1099 // remember the found relationship
1100 if (Ty && !IgnoreKnownType) {
1101 // specify nested types if needed, otherwise return unchanged
1103 }
1104
1105 return Ty;
1106}
1107
1108// Re-create a type of the value if it has untyped pointer fields, also nested.
1109// Return the original value type if no corrections of untyped pointer
1110// information is found or needed.
1111Type *SPIRVEmitIntrinsicsImpl::deduceNestedTypeHelper(User *U,
1112 bool UnknownElemTypeI8) {
1113 SmallPtrSet<Value *, 0> Visited;
1114 return deduceNestedTypeHelper(U, U->getType(), Visited, UnknownElemTypeI8);
1115}
1116
1117Type *SPIRVEmitIntrinsicsImpl::deduceNestedTypeHelper(
1118 User *U, Type *OrigTy, SmallPtrSetImpl<Value *> &Visited,
1119 bool UnknownElemTypeI8) {
1120 if (!U)
1121 return OrigTy;
1122
1123 // maybe already known
1124 if (Type *KnownTy = GR->findDeducedCompositeType(U))
1125 return KnownTy;
1126
1127 // maybe a cycle
1128 if (!Visited.insert(U).second)
1129 return OrigTy;
1130
1131 if (isa<StructType>(OrigTy)) {
1133 bool Change = false;
1134 for (unsigned i = 0; i < U->getNumOperands(); ++i) {
1135 Value *Op = U->getOperand(i);
1136 assert(Op && "Operands should not be null.");
1137 Type *OpTy = Op->getType();
1138 Type *Ty = OpTy;
1139 if (auto *PtrTy = dyn_cast<PointerType>(OpTy)) {
1140 if (Type *NestedTy =
1141 deduceElementTypeHelper(Op, Visited, UnknownElemTypeI8))
1142 Ty = getTypedPointerWrapper(NestedTy, PtrTy->getAddressSpace());
1143 } else {
1144 Ty = deduceNestedTypeHelper(dyn_cast<User>(Op), OpTy, Visited,
1145 UnknownElemTypeI8);
1146 }
1147 Tys.push_back(Ty);
1148 Change |= Ty != OpTy;
1149 }
1150 if (Change) {
1151 Type *NewTy = StructType::create(Tys);
1152 GR->addDeducedCompositeType(U, NewTy);
1153 return NewTy;
1154 }
1155 } else if (auto *ArrTy = dyn_cast<ArrayType>(OrigTy)) {
1156 if (Value *Op = U->getNumOperands() > 0 ? U->getOperand(0) : nullptr) {
1157 Type *OpTy = ArrTy->getElementType();
1158 Type *Ty = OpTy;
1159 if (auto *PtrTy = dyn_cast<PointerType>(OpTy)) {
1160 if (Type *NestedTy =
1161 deduceElementTypeHelper(Op, Visited, UnknownElemTypeI8))
1162 Ty = getTypedPointerWrapper(NestedTy, PtrTy->getAddressSpace());
1163 } else {
1164 Ty = deduceNestedTypeHelper(dyn_cast<User>(Op), OpTy, Visited,
1165 UnknownElemTypeI8);
1166 }
1167 if (Ty != OpTy) {
1168 Type *NewTy = ArrayType::get(Ty, ArrTy->getNumElements());
1169 GR->addDeducedCompositeType(U, NewTy);
1170 return NewTy;
1171 }
1172 }
1173 } else if (auto *VecTy = dyn_cast<VectorType>(OrigTy)) {
1174 if (Value *Op = U->getNumOperands() > 0 ? U->getOperand(0) : nullptr) {
1175 Type *OpTy = VecTy->getElementType();
1176 Type *Ty = OpTy;
1177 if (auto *PtrTy = dyn_cast<PointerType>(OpTy)) {
1178 if (Type *NestedTy =
1179 deduceElementTypeHelper(Op, Visited, UnknownElemTypeI8))
1180 Ty = getTypedPointerWrapper(NestedTy, PtrTy->getAddressSpace());
1181 } else {
1182 Ty = deduceNestedTypeHelper(dyn_cast<User>(Op), OpTy, Visited,
1183 UnknownElemTypeI8);
1184 }
1185 if (Ty != OpTy) {
1186 Type *NewTy = VectorType::get(Ty, VecTy->getElementCount());
1188 return NewTy;
1189 }
1190 }
1191 }
1192
1193 return OrigTy;
1194}
1195
1196Type *SPIRVEmitIntrinsicsImpl::deduceElementType(Value *I,
1197 bool UnknownElemTypeI8) {
1198 if (Type *Ty = deduceElementTypeHelper(I, UnknownElemTypeI8))
1199 return Ty;
1200 if (!UnknownElemTypeI8)
1201 return nullptr;
1202 insertTodoType(I);
1203 return IntegerType::getInt8Ty(I->getContext());
1204}
1205
1207 Value *PointerOperand) {
1208 Type *PointeeTy = GR->findDeducedElementType(PointerOperand);
1209 if (PointeeTy && !isUntypedPointerTy(PointeeTy))
1210 return nullptr;
1211 auto *PtrTy = dyn_cast<PointerType>(I->getType());
1212 if (!PtrTy)
1213 return I->getType();
1214 if (Type *NestedTy = GR->findDeducedElementType(I))
1215 return getTypedPointerWrapper(NestedTy, PtrTy->getAddressSpace());
1216 return nullptr;
1217}
1218
1219// Try to deduce element type for a call base. Returns false if this is an
1220// indirect function invocation, and true otherwise.
1221bool SPIRVEmitIntrinsicsImpl::deduceOperandElementTypeCalledFunction(
1222 CallInst *CI, SmallVector<std::pair<Value *, unsigned>> &Ops,
1223 Type *&KnownElemTy, bool &Incomplete) {
1224 Function *CalledF = CI->getCalledFunction();
1225 if (!CalledF)
1226 return false;
1227 std::string DemangledName =
1229 if (DemangledName.length() > 0 &&
1230 !StringRef(DemangledName).starts_with("llvm.")) {
1231 const SPIRVSubtarget &ST = TM.getSubtarget<SPIRVSubtarget>(*CalledF);
1232 auto [Grp, Opcode, ExtNo] = SPIRV::mapBuiltinToOpcode(
1233 DemangledName, ST.getPreferredInstructionSet());
1234 if (Opcode == SPIRV::OpGroupAsyncCopy) {
1235 for (unsigned i = 0, PtrCnt = 0; i < CI->arg_size() && PtrCnt < 2; ++i) {
1236 Value *Op = CI->getArgOperand(i);
1237 if (!isPointerTy(Op->getType()))
1238 continue;
1239 ++PtrCnt;
1240 if (Type *ElemTy = GR->findDeducedElementType(Op))
1241 KnownElemTy = ElemTy; // src will rewrite dest if both are defined
1242 Ops.push_back(std::make_pair(Op, i));
1243 }
1244 } else if (Grp == SPIRV::Atomic || Grp == SPIRV::AtomicFloating) {
1245 if (CI->arg_size() == 0)
1246 return true;
1247 Value *Op = CI->getArgOperand(0);
1248 if (!isPointerTy(Op->getType()))
1249 return true;
1250 switch (Opcode) {
1251 case SPIRV::OpAtomicFAddEXT:
1252 case SPIRV::OpAtomicFMinEXT:
1253 case SPIRV::OpAtomicFMaxEXT:
1254 case SPIRV::OpAtomicLoad:
1255 case SPIRV::OpAtomicCompareExchangeWeak:
1256 case SPIRV::OpAtomicCompareExchange:
1257 case SPIRV::OpAtomicExchange:
1258 case SPIRV::OpAtomicIAdd:
1259 case SPIRV::OpAtomicISub:
1260 case SPIRV::OpAtomicOr:
1261 case SPIRV::OpAtomicXor:
1262 case SPIRV::OpAtomicAnd:
1263 case SPIRV::OpAtomicUMin:
1264 case SPIRV::OpAtomicUMax:
1265 case SPIRV::OpAtomicSMin:
1266 case SPIRV::OpAtomicSMax: {
1267 KnownElemTy = isPointerTy(CI->getType()) ? getAtomicElemTy(GR, CI, Op)
1268 : CI->getType();
1269 if (!KnownElemTy)
1270 return true;
1271 Incomplete = isTodoType(Op);
1272 Ops.push_back(std::make_pair(Op, 0));
1273 } break;
1274 case SPIRV::OpAtomicStore: {
1275 if (CI->arg_size() < 4)
1276 return true;
1277 Value *ValOp = CI->getArgOperand(3);
1278 KnownElemTy = isPointerTy(ValOp->getType())
1279 ? getAtomicElemTy(GR, CI, Op)
1280 : ValOp->getType();
1281 if (!KnownElemTy)
1282 return true;
1283 Incomplete = isTodoType(Op);
1284 Ops.push_back(std::make_pair(Op, 0));
1285 } break;
1286 }
1287 }
1288 }
1289 return true;
1290}
1291
1292// Try to deduce element type for a function pointer.
1293void SPIRVEmitIntrinsicsImpl::deduceOperandElementTypeFunctionPointer(
1294 CallInst *CI, SmallVector<std::pair<Value *, unsigned>> &Ops,
1295 Type *&KnownElemTy, bool IsPostprocessing) {
1296 Value *Op = CI->getCalledOperand();
1297 if (!Op || !isPointerTy(Op->getType()))
1298 return;
1299 Ops.push_back(std::make_pair(Op, std::numeric_limits<unsigned>::max()));
1300 FunctionType *FTy = SPIRV::getOriginalFunctionType(*CI);
1301 bool IsNewFTy = false, IsIncomplete = false;
1303 for (auto &&[ParmIdx, Arg] : llvm::enumerate(CI->args())) {
1304 Type *ArgTy = Arg->getType();
1305 if (ArgTy->isPointerTy()) {
1306 if (Type *ElemTy = GR->findDeducedElementType(Arg)) {
1307 IsNewFTy = true;
1308 ArgTy = getTypedPointerWrapper(ElemTy, getPointerAddressSpace(ArgTy));
1309 if (isTodoType(Arg))
1310 IsIncomplete = true;
1311 } else {
1312 IsIncomplete = true;
1313 }
1314 } else {
1315 ArgTy = FTy->getFunctionParamType(ParmIdx);
1316 }
1317 ArgTys.push_back(ArgTy);
1318 }
1319 Type *RetTy = FTy->getReturnType();
1320 if (CI->getType()->isPointerTy()) {
1321 if (Type *ElemTy = GR->findDeducedElementType(CI)) {
1322 IsNewFTy = true;
1323 RetTy =
1325 if (isTodoType(CI))
1326 IsIncomplete = true;
1327 } else {
1328 IsIncomplete = true;
1329 }
1330 }
1331 if (!IsPostprocessing && IsIncomplete)
1332 insertTodoType(Op);
1333 KnownElemTy =
1334 IsNewFTy ? FunctionType::get(RetTy, ArgTys, FTy->isVarArg()) : FTy;
1335}
1336
1337bool SPIRVEmitIntrinsicsImpl::deduceOperandElementTypeFunctionRet(
1338 Instruction *I, SmallPtrSetImpl<Instruction *> *IncompleteRets,
1339 const SmallPtrSetImpl<Value *> *AskOps, bool IsPostprocessing,
1340 Type *&KnownElemTy, Value *Op, Function *F) {
1341 KnownElemTy = GR->findDeducedElementType(F);
1342 if (KnownElemTy)
1343 return false;
1344 if (Type *OpElemTy = GR->findDeducedElementType(Op)) {
1345 OpElemTy = normalizeType(OpElemTy);
1346 GR->addDeducedElementType(F, OpElemTy);
1347 GR->addReturnType(
1348 F, TypedPointerType::get(OpElemTy,
1349 getPointerAddressSpace(F->getReturnType())));
1350 // non-recursive update of types in function uses
1351 DenseSet<std::pair<Value *, Value *>> VisitedSubst{std::make_pair(I, Op)};
1352 for (User *U : F->users()) {
1353 CallInst *CI = dyn_cast<CallInst>(U);
1354 if (!CI || CI->getCalledFunction() != F)
1355 continue;
1356 if (CallInst *AssignCI = GR->findAssignPtrTypeInstr(CI)) {
1357 if (Type *PrevElemTy = GR->findDeducedElementType(CI)) {
1358 GR->updateAssignType(AssignCI, CI,
1359 getNormalizedPoisonValue(OpElemTy));
1360 propagateElemType(CI, PrevElemTy, VisitedSubst);
1361 }
1362 }
1363 }
1364 // Non-recursive update of types in the function uncomplete returns.
1365 // This may happen just once per a function, the latch is a pair of
1366 // findDeducedElementType(F) / addDeducedElementType(F, ...).
1367 // With or without the latch it is a non-recursive call due to
1368 // IncompleteRets set to nullptr in this call.
1369 if (IncompleteRets)
1370 for (Instruction *IncompleteRetI : *IncompleteRets)
1371 deduceOperandElementType(IncompleteRetI, nullptr, AskOps,
1372 IsPostprocessing);
1373 } else if (IncompleteRets) {
1374 IncompleteRets->insert(I);
1375 }
1376 TypeValidated.insert(I);
1377 return true;
1378}
1379
1380// If the Instruction has Pointer operands with unresolved types, this function
1381// tries to deduce them. If the Instruction has Pointer operands with known
1382// types which differ from expected, this function tries to insert a bitcast to
1383// resolve the issue.
1384void SPIRVEmitIntrinsicsImpl::deduceOperandElementType(
1385 Instruction *I, SmallPtrSetImpl<Instruction *> *IncompleteRets,
1386 const SmallPtrSetImpl<Value *> *AskOps, bool IsPostprocessing) {
1388 Type *KnownElemTy = nullptr;
1389 bool Incomplete = false;
1390 // look for known basic patterns of type inference
1391 if (auto *Ref = dyn_cast<PHINode>(I)) {
1392 if (!isPointerTy(I->getType()) ||
1393 !(KnownElemTy = GR->findDeducedElementType(I)))
1394 return;
1395 Incomplete = isTodoType(I);
1396 for (unsigned i = 0; i < Ref->getNumIncomingValues(); i++) {
1397 Value *Op = Ref->getIncomingValue(i);
1398 if (isPointerTy(Op->getType()))
1399 Ops.push_back(std::make_pair(Op, i));
1400 }
1401 } else if (auto *Ref = dyn_cast<AddrSpaceCastInst>(I)) {
1402 KnownElemTy = GR->findDeducedElementType(I);
1403 if (!KnownElemTy)
1404 return;
1405 Incomplete = isTodoType(I);
1406 Ops.push_back(std::make_pair(Ref->getPointerOperand(), 0));
1407 } else if (auto *Ref = dyn_cast<BitCastInst>(I)) {
1408 if (!isPointerTy(I->getType()))
1409 return;
1410 KnownElemTy = GR->findDeducedElementType(I);
1411 if (!KnownElemTy)
1412 return;
1413 Incomplete = isTodoType(I);
1414 Ops.push_back(std::make_pair(Ref->getOperand(0), 0));
1415 } else if (auto *Ref = dyn_cast<GetElementPtrInst>(I)) {
1416 if (GR->findDeducedElementType(Ref->getPointerOperand()))
1417 return;
1418 KnownElemTy = Ref->getSourceElementType();
1419 Ops.push_back(std::make_pair(Ref->getPointerOperand(),
1421 } else if (auto *Ref = dyn_cast<StructuredGEPInst>(I)) {
1422 if (GR->findDeducedElementType(Ref->getPointerOperand()))
1423 return;
1424 KnownElemTy = Ref->getBaseType();
1425 Ops.push_back(std::make_pair(Ref->getPointerOperand(),
1427 } else if (auto *Ref = dyn_cast<LoadInst>(I)) {
1428 KnownElemTy = I->getType();
1429 if (isUntypedPointerTy(KnownElemTy)) {
1430 // A T** loaded back from its alloca comes out opaque, dropping type info.
1431 // When the load is a pointer-to-pointer, type the alloca as that pointer.
1432 Type *LoadedElemTy = GR->findDeducedElementType(I);
1433 if (!LoadedElemTy || !isPointerTyOrWrapper(LoadedElemTy))
1434 return;
1435 Value *Root = Ref->getPointerOperand()->stripPointerCasts();
1436 if (!isa<AllocaInst>(Root))
1437 return;
1438 KnownElemTy = getTypedPointerWrapper(LoadedElemTy,
1439 getPointerAddressSpace(KnownElemTy));
1440 }
1441 Type *PointeeTy = GR->findDeducedElementType(Ref->getPointerOperand());
1442 if (PointeeTy && !isUntypedPointerTy(PointeeTy))
1443 return;
1444 Ops.push_back(std::make_pair(Ref->getPointerOperand(),
1446 } else if (auto *Ref = dyn_cast<StoreInst>(I)) {
1447 if (!(KnownElemTy =
1448 reconstructType(Ref->getValueOperand(), false, IsPostprocessing)))
1449 return;
1450 Type *PointeeTy = GR->findDeducedElementType(Ref->getPointerOperand());
1451 if (PointeeTy && !isUntypedPointerTy(PointeeTy))
1452 return;
1453 Ops.push_back(std::make_pair(Ref->getPointerOperand(),
1455 } else if (auto *Ref = dyn_cast<AtomicCmpXchgInst>(I)) {
1456 KnownElemTy = isPointerTy(I->getType())
1457 ? getAtomicElemTy(GR, I, Ref->getPointerOperand())
1458 : I->getType();
1459 if (!KnownElemTy)
1460 return;
1461 Incomplete = isTodoType(Ref->getPointerOperand());
1462 Ops.push_back(std::make_pair(Ref->getPointerOperand(),
1464 } else if (auto *Ref = dyn_cast<AtomicRMWInst>(I)) {
1465 KnownElemTy = isPointerTy(I->getType())
1466 ? getAtomicElemTy(GR, I, Ref->getPointerOperand())
1467 : I->getType();
1468 if (!KnownElemTy)
1469 return;
1470 Incomplete = isTodoType(Ref->getPointerOperand());
1471 Ops.push_back(std::make_pair(Ref->getPointerOperand(),
1473 } else if (auto *Ref = dyn_cast<SelectInst>(I)) {
1474 if (!isPointerTy(I->getType()) ||
1475 !(KnownElemTy = GR->findDeducedElementType(I)))
1476 return;
1477 Incomplete = isTodoType(I);
1478 for (unsigned i = 0; i < Ref->getNumOperands(); i++) {
1479 Value *Op = Ref->getOperand(i);
1480 if (isPointerTy(Op->getType()))
1481 Ops.push_back(std::make_pair(Op, i));
1482 }
1483 } else if (auto *Ref = dyn_cast<ReturnInst>(I)) {
1484 if (!isPointerTy(CurrF->getReturnType()))
1485 return;
1486 Value *Op = Ref->getReturnValue();
1487 if (!Op)
1488 return;
1489 if (deduceOperandElementTypeFunctionRet(I, IncompleteRets, AskOps,
1490 IsPostprocessing, KnownElemTy, Op,
1491 CurrF))
1492 return;
1493 Incomplete = isTodoType(CurrF);
1494 Ops.push_back(std::make_pair(Op, 0));
1495 } else if (auto *Ref = dyn_cast<ICmpInst>(I)) {
1496 if (!isPointerTy(Ref->getOperand(0)->getType()))
1497 return;
1498 Value *Op0 = Ref->getOperand(0);
1499 Value *Op1 = Ref->getOperand(1);
1500 bool Incomplete0 = isTodoType(Op0);
1501 bool Incomplete1 = isTodoType(Op1);
1502 Type *ElemTy1 = GR->findDeducedElementType(Op1);
1503 Type *ElemTy0 = (Incomplete0 && !Incomplete1 && ElemTy1)
1504 ? nullptr
1505 : GR->findDeducedElementType(Op0);
1506 if (ElemTy0) {
1507 KnownElemTy = ElemTy0;
1508 Incomplete = Incomplete0;
1509 Ops.push_back(std::make_pair(Op1, 1));
1510 } else if (ElemTy1) {
1511 KnownElemTy = ElemTy1;
1512 Incomplete = Incomplete1;
1513 Ops.push_back(std::make_pair(Op0, 0));
1514 }
1515 } else if (CallInst *CI = dyn_cast<CallInst>(I)) {
1516 if (!CI->isIndirectCall())
1517 deduceOperandElementTypeCalledFunction(CI, Ops, KnownElemTy, Incomplete);
1518 else if (HaveFunPtrs)
1519 deduceOperandElementTypeFunctionPointer(CI, Ops, KnownElemTy,
1520 IsPostprocessing);
1521 }
1522
1523 // There is no enough info to deduce types or all is valid.
1524 if (!KnownElemTy || Ops.size() == 0)
1525 return;
1526
1527 LLVMContext &Ctx = CurrF->getContext();
1528 IRBuilder<> B(Ctx);
1529 for (auto &OpIt : Ops) {
1530 Value *Op = OpIt.first;
1531 if (AskOps && !AskOps->contains(Op))
1532 continue;
1533 Type *AskTy = nullptr;
1534 CallInst *AskCI = nullptr;
1535 if (IsPostprocessing && AskOps) {
1536 AskTy = GR->findDeducedElementType(Op);
1537 AskCI = GR->findAssignPtrTypeInstr(Op);
1538 assert(AskTy && AskCI);
1539 }
1540 Type *Ty = AskTy ? AskTy : GR->findDeducedElementType(Op);
1541 if (Ty == KnownElemTy)
1542 continue;
1543 Value *OpTyVal = getNormalizedPoisonValue(KnownElemTy);
1544 Type *OpTy = Op->getType();
1545 // Do not let a non-pointer element type clobber an already-deduced pointer
1546 // pointee.
1547 bool WouldClobberPtrWithNonPtr = Ty && isPointerTyOrWrapper(Ty) &&
1548 !isPointerTyOrWrapper(KnownElemTy) &&
1550 if (Op->hasUseList() && !WouldClobberPtrWithNonPtr &&
1551 (!Ty || AskTy || isUntypedPointerTy(Ty) || isTodoType(Op))) {
1552 Type *PrevElemTy = GR->findDeducedElementType(Op);
1553 GR->addDeducedElementType(Op, normalizeType(KnownElemTy));
1554 // check if KnownElemTy is complete
1555 if (!Incomplete)
1556 eraseTodoType(Op);
1557 else if (!IsPostprocessing)
1558 insertTodoType(Op);
1559 // check if there is existing Intrinsic::spv_assign_ptr_type instruction
1560 CallInst *AssignCI = AskCI ? AskCI : GR->findAssignPtrTypeInstr(Op);
1561 if (AssignCI == nullptr) {
1562 Instruction *User = dyn_cast<Instruction>(Op->use_begin()->get());
1563 setInsertPointSkippingPhis(B, User ? User->getNextNode() : I);
1564 CallInst *CI =
1565 buildIntrWithMD(Intrinsic::spv_assign_ptr_type, {OpTy}, OpTyVal, Op,
1566 {B.getInt32(getPointerAddressSpace(OpTy))}, B);
1567 GR->addAssignPtrTypeInstr(Op, CI);
1568 } else {
1569 GR->updateAssignType(AssignCI, Op, OpTyVal);
1570 DenseSet<std::pair<Value *, Value *>> VisitedSubst{
1571 std::make_pair(I, Op)};
1572 propagateElemTypeRec(Op, KnownElemTy, PrevElemTy, VisitedSubst);
1573 }
1574 } else {
1575 eraseTodoType(Op);
1576 CallInst *PtrCastI =
1577 buildSpvPtrcast(I->getParent()->getParent(), Op, KnownElemTy);
1578 if (OpIt.second == std::numeric_limits<unsigned>::max())
1579 dyn_cast<CallInst>(I)->setCalledOperand(PtrCastI);
1580 else
1581 I->setOperand(OpIt.second, PtrCastI);
1582 }
1583 }
1584 TypeValidated.insert(I);
1585}
1586
1587void SPIRVEmitIntrinsicsImpl::replaceMemInstrUses(Instruction *Old,
1588 Instruction *New,
1589 IRBuilder<> &B) {
1590 while (!Old->user_empty()) {
1591 auto *U = Old->user_back();
1592 if (isAssignTypeInstr(U)) {
1593 B.SetInsertPoint(U);
1594 SmallVector<Value *, 2> Args = {New, U->getOperand(1)};
1595 CallInst *AssignCI = B.CreateIntrinsicWithoutFolding(
1596 Intrinsic::spv_assign_type, {New->getType()}, Args);
1597 GR->addAssignPtrTypeInstr(New, AssignCI);
1598 U->eraseFromParent();
1599 } else if (isMemInstrToReplace(U) || isa<ReturnInst>(U) ||
1600 isa<CallInst>(U)) {
1601 U->replaceUsesOfWith(Old, New);
1602 // For a `llvm.spv.abort` call whose composite message argument was
1603 // rewritten to a value-id (i32), also retarget the call to a matching
1604 // intrinsic declaration so the IR verifier is satisfied. The SPIR-V
1605 // type of the value is tracked via the GlobalRegistry, so the selector
1606 // still emits OpAbortKHR with the original composite type.
1607 if (auto *CI = dyn_cast<CallInst>(U);
1608 CI && CI->getIntrinsicID() == Intrinsic::spv_abort) {
1609 Type *NewArgTy = New->getType();
1610 Type *ExpectedArgTy = CI->getFunctionType()->getParamType(0);
1611 if (NewArgTy != ExpectedArgTy) {
1612 Module *M = CI->getModule();
1614 M, Intrinsic::spv_abort, {NewArgTy});
1615 CI->setCalledFunction(NewF);
1616 }
1617 }
1618 } else if (isa<PHINode>(U) || isa<SelectInst>(U) || isa<FreezeInst>(U)) {
1619 // Aggregate-typed PHIs, selects and freezes have already been mutated to
1620 // the i32 value-id type up front in runOnFunction, so only the operand
1621 // needs replacing here; their extractvalue users are lowered to
1622 // spv_extractv by visitExtractValueInst.
1623 assert(U->getType() == New->getType() &&
1624 "aggregate PHI/select/freeze should have been mutated to value-id "
1625 "type");
1626 U->replaceUsesOfWith(Old, New);
1627 } else {
1628 llvm_unreachable("illegal aggregate intrinsic user");
1629 }
1630 }
1631 New->copyMetadata(*Old);
1632 Old->eraseFromParent();
1633}
1634
1635// Lower a poison or undef Op to its placeholder intrinsic.
1636Value *SPIRVEmitIntrinsicsImpl::lowerUndefOrPoison(Value *Op, IRBuilder<> &B,
1637 bool HasPoisonExt) {
1638 auto *UV = dyn_cast<UndefValue>(Op);
1639 if (!UV)
1640 return nullptr;
1641
1642 bool AsPoison = HasPoisonExt && isa<PoisonValue>(UV);
1643 if (isa<PoisonValue>(UV) && !HasPoisonExt)
1644 LLVM_DEBUG(dbgs() << "SPV_KHR_poison_freeze is not enabled. Poison is "
1645 "lowered as undef\n");
1646
1647 Intrinsic::ID IID = AsPoison ? Intrinsic::spv_poison : Intrinsic::spv_undef;
1648 Type *Ty = UV->getType();
1649
1650 // Aggregates use an i32-result placeholder with the real type kept in
1651 // AggrConstTypes and scalar poison uses a type-overloaded one.
1652 if (Ty->isAggregateType()) {
1653 auto *Call =
1654 AsPoison ? B.CreateIntrinsicWithoutFolding(IID, {B.getInt32Ty()}, {})
1655 : B.CreateIntrinsicWithoutFolding(IID, {});
1656 AggrConsts[Call] = UV;
1657 AggrConstTypes[Call] = Ty;
1658 return Call;
1659 }
1660
1661 if (AsPoison)
1662 return B.CreateIntrinsic(IID, {Ty}, {});
1663 return nullptr;
1664}
1665
1666// Replace aggregate undef or poison operands and extension-enabled scalar
1667// poison operands with placeholder intrinsics. Scalar undef is left as is. See
1668// lowerUndefOrPoison.
1669void SPIRVEmitIntrinsicsImpl::preprocessUndefsAndPoisons(IRBuilder<> &B) {
1670 const SPIRVSubtarget *STI = TM.getSubtargetImpl(*CurrF);
1671 bool HasPoisonExt =
1672 STI->canUseExtension(SPIRV::Extension::SPV_KHR_poison_freeze);
1673
1674 SmallVector<Instruction *, 16> Insts;
1675 for (auto &I : instructions(CurrF))
1676 Insts.push_back(&I);
1677
1678 for (Instruction *I : Insts) {
1679 bool BPrepared = false;
1680 auto *Phi = dyn_cast<PHINode>(I);
1681 for (unsigned Idx = 0; Idx < I->getNumOperands(); ++Idx) {
1682 Value *Op = I->getOperand(Idx);
1683 if (!isa<UndefValue>(Op) || Op->getType()->isMetadataTy())
1684 continue;
1685 bool IsScalar = !Op->getType()->isAggregateType();
1686 bool AsPoison = HasPoisonExt && isa<PoisonValue>(Op);
1687 // Scalar undef or extensionless scalar poison is directly translatable.
1688 if (IsScalar && !AsPoison)
1689 continue;
1690 // Scalar poison in a phi materializes in the incoming block. Everything
1691 // else materializes right before I.
1692 if (IsScalar && Phi)
1693 B.SetInsertPoint(Phi->getIncomingBlock(Idx)->getTerminator());
1694 else if (!BPrepared) {
1696 BPrepared = true;
1697 }
1698 if (Value *Repl = lowerUndefOrPoison(Op, B, HasPoisonExt))
1699 I->setOperand(Idx, Repl);
1700 }
1701 }
1702}
1703
1704// Simplify addrspacecast(null) instructions to ConstantPointerNull of the
1705// target type. Casting null always yields null, and this avoids SPIR-V
1706// lowering issues where the null gets typed as an integer instead of a
1707// pointer.
1708void SPIRVEmitIntrinsicsImpl::simplifyNullAddrSpaceCasts() {
1709 for (Instruction &I : make_early_inc_range(instructions(CurrF)))
1710 if (auto *ASC = dyn_cast<AddrSpaceCastInst>(&I))
1711 if (isa<ConstantPointerNull>(ASC->getPointerOperand())) {
1712 ASC->replaceAllUsesWith(
1714 ASC->eraseFromParent();
1715 }
1716}
1717
1718// True for an aggregate value the legalizer splits into a multi-result op
1719// (with.overflow -> G_UADDO, frexp/sincos/modf -> G_FFREXP/...). These keep a
1720// genuine multi-register result; all other aggregates become a single value-id.
1722 if (!V->getType()->isAggregateType())
1723 return false;
1724 return isa<IntrinsicInst>(V) && !isSpvIntrinsic(V);
1725}
1726
1727// True for an aggregate PHI/select/freeze, which is lowered to a single
1728// value-id.
1730 return (isa<PHINode>(I) || isa<SelectInst>(I) || isa<FreezeInst>(I)) &&
1731 I.getType()->isAggregateType();
1732}
1733
1734// Give each multi-register aggregate arm of an aggregate PHI/select/freeze a
1735// single value-id by reassembling it with extractvalue + insertvalue, so the
1736// arm matches the result once it is mutated to a value-id.
1737void SPIRVEmitIntrinsicsImpl::insertCompositeAggregateArms(Instruction *I,
1738 IRBuilder<> &B) {
1739 auto *Phi = dyn_cast<PHINode>(I);
1740 for (Use &U : I->operands()) {
1741 Value *Op = U.get();
1743 continue;
1744 // A PHI arm materializes in its incoming block, everything else after the
1745 // producer.
1746 if (Phi)
1747 B.SetInsertPoint(Phi->getIncomingBlock(U)->getTerminator());
1748 else
1750 auto *AggrTy = cast<StructType>(Op->getType());
1751 Value *Composite = PoisonValue::get(AggrTy);
1752 for (unsigned Idx = 0, E = AggrTy->getNumElements(); Idx != E; ++Idx) {
1753 Value *Field = B.CreateExtractValue(Op, Idx);
1754 Composite = B.CreateInsertValue(Composite, Field, Idx);
1755 }
1756 U.set(Composite);
1757 }
1758}
1759
1760void SPIRVEmitIntrinsicsImpl::preprocessCompositeConstants(IRBuilder<> &B) {
1761 const SPIRVSubtarget *STI = TM.getSubtargetImpl(*CurrF);
1762 bool HasPoisonExt =
1763 STI->canUseExtension(SPIRV::Extension::SPV_KHR_poison_freeze);
1764 std::queue<Instruction *> Worklist;
1765 for (auto &I : instructions(CurrF))
1766 Worklist.push(&I);
1767
1768 while (!Worklist.empty()) {
1769 auto *I = Worklist.front();
1770 bool IsPhi = isa<PHINode>(I), BPrepared = false;
1771 assert(I);
1772 bool KeepInst = false;
1773 for (const auto &Op : I->operands()) {
1774 Constant *AggrConst = nullptr;
1775 Type *ResTy = nullptr;
1776 if (auto *COp = dyn_cast<ConstantVector>(Op)) {
1777 AggrConst = COp;
1778 ResTy = COp->getType();
1779 } else if (auto *COp = dyn_cast<ConstantArray>(Op)) {
1780 AggrConst = COp;
1781 ResTy = B.getInt32Ty();
1782 } else if (auto *COp = dyn_cast<ConstantStruct>(Op)) {
1783 AggrConst = COp;
1784 ResTy = B.getInt32Ty();
1785 } else if (auto *COp = dyn_cast<ConstantDataArray>(Op)) {
1786 AggrConst = COp;
1787 ResTy = B.getInt32Ty();
1788 } else if (auto *COp = dyn_cast<ConstantAggregateZero>(Op)) {
1789 AggrConst = COp;
1790 ResTy = Op->getType()->isVectorTy() ? COp->getType() : B.getInt32Ty();
1791 }
1792 if (AggrConst) {
1793 auto PrepareInsert = [&]() {
1794 if (BPrepared)
1795 return;
1796 IsPhi ? B.SetInsertPointPastAllocas(I->getParent()->getParent())
1797 : B.SetInsertPoint(I);
1798 BPrepared = true;
1799 };
1801 if (auto *COp = dyn_cast<ConstantDataSequential>(Op))
1802 for (unsigned i = 0; i < COp->getNumElements(); ++i)
1803 Args.push_back(COp->getElementAsConstant(i));
1804 else
1805 for (Value *Op : AggrConst->operands()) {
1806 // Simplify addrspacecast(null) to null in the target address space
1807 // so that null pointers get the correct pointer type when lowered.
1808 if (auto *CE = dyn_cast<ConstantExpr>(Op);
1809 CE && CE->getOpcode() == Instruction::AddrSpaceCast &&
1810 isa<ConstantPointerNull>(CE->getOperand(0)))
1812 // Undef or poison nested in a constant aggregate is not a direct
1813 // instruction operand, so preprocessUndefsAndPoisons() misses it.
1814 // An unlowered aggregate one would reach IRTranslator as an
1815 // untranslatable spv_const_composite operand.
1816 if (isa<UndefValue>(Op)) {
1817 PrepareInsert();
1818 if (Value *Repl = lowerUndefOrPoison(Op, B, HasPoisonExt))
1819 Op = Repl;
1820 }
1821 Args.push_back(Op);
1822 }
1823 PrepareInsert();
1824 auto *CI = B.CreateIntrinsicWithoutFolding(
1825 Intrinsic::spv_const_composite, {ResTy}, {Args});
1826 Worklist.push(CI);
1827 I->replaceUsesOfWith(Op, CI);
1828 KeepInst = true;
1829 AggrConsts[CI] = AggrConst;
1830 AggrConstTypes[CI] = deduceNestedTypeHelper(AggrConst, false);
1831 }
1832 }
1833 if (!KeepInst)
1834 Worklist.pop();
1835 }
1836}
1837
1839 IRBuilder<> &B) {
1840 LLVMContext &Ctx = I->getContext();
1842 B.CreateIntrinsic(Intrinsic::spv_assign_decoration, {I->getType()},
1843 {I, MetadataAsValue::get(Ctx, MDNode::get(Ctx, {Node}))});
1844}
1845
1847 unsigned RoundingModeDeco,
1848 IRBuilder<> &B) {
1849 LLVMContext &Ctx = I->getContext();
1850 Type *Int32Ty = Type::getInt32Ty(Ctx);
1851 MDNode *RoundingModeNode = MDNode::get(
1852 Ctx,
1854 ConstantInt::get(Int32Ty, SPIRV::Decoration::FPRoundingMode)),
1855 ConstantAsMetadata::get(ConstantInt::get(Int32Ty, RoundingModeDeco))});
1856 createDecorationIntrinsic(I, RoundingModeNode, B);
1857}
1858
1860 IRBuilder<> &B) {
1861 LLVMContext &Ctx = I->getContext();
1862 Type *Int32Ty = Type::getInt32Ty(Ctx);
1863 MDNode *SaturatedConversionNode =
1864 MDNode::get(Ctx, {ConstantAsMetadata::get(ConstantInt::get(
1865 Int32Ty, SPIRV::Decoration::SaturatedConversion))});
1866 createDecorationIntrinsic(I, SaturatedConversionNode, B);
1867}
1868
1873
1874Instruction *SPIRVEmitIntrinsicsImpl::visitCallInst(CallInst &Call) {
1875 if (!Call.isInlineAsm())
1876 return &Call;
1877
1878 LLVMContext &Ctx = CurrF->getContext();
1879 // TODO: this does not retain elementtype info for memory constraints, which
1880 // in turn means that we lower them into pointers to i8, rather than
1881 // pointers to elementtype; this can be fixed during reverse translation
1882 // but we should correct it here, possibly by tweaking the function
1883 // type to take TypedPointerType args.
1884 Constant *TyC = UndefValue::get(SPIRV::getOriginalFunctionType(Call));
1885 MDString *ConstraintString =
1886 MDString::get(Ctx, SPIRV::getOriginalAsmConstraints(Call));
1888 buildMD(TyC),
1889 MetadataAsValue::get(Ctx, MDNode::get(Ctx, ConstraintString))};
1890 for (unsigned OpIdx = 0; OpIdx < Call.arg_size(); OpIdx++)
1891 Args.push_back(Call.getArgOperand(OpIdx));
1892
1894 B.SetInsertPoint(&Call);
1895 B.CreateIntrinsic(Intrinsic::spv_inline_asm, {Args});
1896 return &Call;
1897}
1898
1899// Use a tip about rounding mode to create a decoration.
1900void SPIRVEmitIntrinsicsImpl::useRoundingMode(ConstrainedFPIntrinsic *FPI,
1901 IRBuilder<> &B) {
1902 std::optional<RoundingMode> RM = FPI->getRoundingMode();
1903 if (!RM.has_value())
1904 return;
1905 unsigned RoundingModeDeco = std::numeric_limits<unsigned>::max();
1906 switch (RM.value()) {
1907 default:
1908 // ignore unknown rounding modes
1909 break;
1910 case RoundingMode::NearestTiesToEven:
1911 RoundingModeDeco = SPIRV::FPRoundingMode::FPRoundingMode::RTE;
1912 break;
1913 case RoundingMode::TowardNegative:
1914 RoundingModeDeco = SPIRV::FPRoundingMode::FPRoundingMode::RTN;
1915 break;
1916 case RoundingMode::TowardPositive:
1917 RoundingModeDeco = SPIRV::FPRoundingMode::FPRoundingMode::RTP;
1918 break;
1919 case RoundingMode::TowardZero:
1920 RoundingModeDeco = SPIRV::FPRoundingMode::FPRoundingMode::RTZ;
1921 break;
1922 case RoundingMode::Dynamic:
1923 case RoundingMode::NearestTiesToAway:
1924 // TODO: check if supported
1925 break;
1926 }
1927 if (RoundingModeDeco == std::numeric_limits<unsigned>::max())
1928 return;
1929 // Convert the tip about rounding mode into a decoration record.
1930 createRoundingModeDecoration(FPI, RoundingModeDeco, B);
1931}
1932
1933Instruction *SPIRVEmitIntrinsicsImpl::visitSwitchInst(SwitchInst &I) {
1934 BasicBlock *ParentBB = I.getParent();
1935 Function *F = ParentBB->getParent();
1936 IRBuilder<> B(ParentBB);
1937 B.SetInsertPoint(&I);
1938 SmallVector<Value *, 4> Args;
1940 Args.push_back(I.getCondition());
1941 BBCases.push_back(I.getDefaultDest());
1942 Args.push_back(BlockAddress::get(F, I.getDefaultDest()));
1943 for (auto &Case : I.cases()) {
1944 Args.push_back(Case.getCaseValue());
1945 BBCases.push_back(Case.getCaseSuccessor());
1946 Args.push_back(BlockAddress::get(F, Case.getCaseSuccessor()));
1947 }
1948 CallInst *NewI = B.CreateIntrinsicWithoutFolding(
1949 Intrinsic::spv_switch, {I.getOperand(0)->getType()}, {Args});
1950 // remove switch to avoid its unneeded and undesirable unwrap into branches
1951 // and conditions
1952 replaceAllUsesWith(&I, NewI);
1953 I.eraseFromParent();
1954 // insert artificial and temporary instruction to preserve valid CFG,
1955 // it will be removed after IR translation pass
1956 B.SetInsertPoint(ParentBB);
1957 IndirectBrInst *BrI = B.CreateIndirectBr(
1958 Constant::getNullValue(PointerType::getUnqual(ParentBB->getContext())),
1959 BBCases.size());
1960 for (BasicBlock *BBCase : BBCases)
1961 BrI->addDestination(BBCase);
1962 return BrI;
1963}
1964
1966 return GEP->getNumIndices() > 0 && match(GEP->getOperand(1), m_Zero());
1967}
1968
1969Instruction *SPIRVEmitIntrinsicsImpl::visitIntrinsicInst(IntrinsicInst &I) {
1970 auto *SGEP = dyn_cast<StructuredGEPInst>(&I);
1971 if (!SGEP)
1972 return &I;
1973
1974 IRBuilder<> B(I.getParent());
1975 B.SetInsertPoint(&I);
1976 SmallVector<Type *, 2> Types = {I.getType(), I.getOperand(0)->getType()};
1977 SmallVector<Value *, 4> Args;
1978 Args.push_back(/* inBounds= */ B.getInt1(true));
1979 Args.push_back(I.getOperand(0));
1980 Args.push_back(/* zero index */ B.getInt32(0));
1981 for (unsigned J = 0; J < SGEP->getNumIndices(); ++J)
1982 Args.push_back(SGEP->getIndexOperand(J));
1983
1984 Instruction *NewI =
1985 B.CreateIntrinsicWithoutFolding(Intrinsic::spv_gep, Types, Args);
1986 replaceAllUsesWithAndErase(B, &I, NewI);
1987 return NewI;
1988}
1989
1991SPIRVEmitIntrinsicsImpl::visitGetElementPtrInst(GetElementPtrInst &I) {
1992 IRBuilder<> B(I.getParent());
1993 B.SetInsertPoint(&I);
1994
1995 // OpPtrAccessChain requires a scalar pointer result; scalarize per-lane
1996 // GEPs that return <N x ptr> and rebuild the vector via insertelement.
1997 if (auto *RetVTy = dyn_cast<FixedVectorType>(I.getType())) {
1998 unsigned N = RetVTy->getNumElements();
1999 Value *PtrOp = I.getPointerOperand();
2000 bool PtrIsVec = isa<VectorType>(PtrOp->getType());
2001 Type *ResultPtrTy = RetVTy->getElementType();
2002 Type *ScalarPtrTy = PtrOp->getType()->getScalarType();
2003 SmallVector<Type *, 2> GepTypes = {ResultPtrTy, ScalarPtrTy};
2004 Value *InBounds = B.getInt1(I.isInBounds());
2005 Type *LanePointeeTy = getGEPType(&I);
2006 Type *SrcElemTy = I.getSourceElementType();
2007
2008 // Pin the lane pointee type on the vector operand and on each extracted
2009 // lane so the prelegalizer wraps them as OpTypeVector/OpTypePointer of
2010 // the right element type instead of defaulting to i8.
2011 if (PtrIsVec)
2012 GR->buildAssignPtr(B, SrcElemTy, PtrOp);
2013
2014 Value *VecResult = PoisonValue::get(RetVTy);
2015 for (unsigned Lane = 0; Lane < N; ++Lane) {
2016 Value *LaneIdx = B.getInt32(Lane);
2017 Value *ScalarPtr = PtrOp;
2018 if (PtrIsVec) {
2019 SmallVector<Type *, 3> ExtractTypes = {ScalarPtrTy, PtrOp->getType(),
2020 LaneIdx->getType()};
2021 ScalarPtr = B.CreateIntrinsic(Intrinsic::spv_extractelt, {ExtractTypes},
2022 {PtrOp, LaneIdx});
2023 GR->buildAssignPtr(B, SrcElemTy, ScalarPtr);
2024 }
2025 SmallVector<Value *, 4> Args;
2026 Args.push_back(InBounds);
2027 Args.push_back(ScalarPtr);
2028 for (Value *Idx : I.indices()) {
2029 if (isa<VectorType>(Idx->getType()))
2030 Args.push_back(B.CreateExtractElement(Idx, LaneIdx));
2031 else
2032 Args.push_back(Idx);
2033 }
2034 Value *ScalarGep = B.CreateIntrinsic(Intrinsic::spv_gep, GepTypes, Args);
2035 GR->buildAssignPtr(B, LanePointeeTy, ScalarGep);
2036 VecResult = B.CreateInsertElement(VecResult, ScalarGep, LaneIdx);
2037 }
2038
2039 auto *NewI = cast<Instruction>(VecResult);
2040 replaceAllUsesWithAndErase(B, &I, NewI);
2041
2042 if (CallInst *Old = GR->findAssignPtrTypeInstr(NewI)) {
2043 Old->eraseFromParent();
2044 GR->addAssignPtrTypeInstr(NewI, nullptr);
2045 }
2047 GR->buildAssignPtr(B, LanePointeeTy, NewI);
2048
2049 return NewI;
2050 }
2051
2053 // Logical SPIR-V cannot use the OpPtrAccessChain instruction. If the first
2054 // index of the GEP is not 0, then we need to try to adjust it.
2055 //
2056 // If the GEP is doing byte addressing, try to rebuild the full access chain
2057 // from the type of the pointer.
2058 if (getByteAddressingMultiplier(I.getSourceElementType())) {
2059 return buildLogicalAccessChainFromGEP(I);
2060 }
2061
2062 // Look for the array-to-pointer decay. If this is the pattern
2063 // we can adjust the types, and prepend a 0 to the indices.
2064 Value *PtrOp = I.getPointerOperand();
2065 Type *SrcElemTy = I.getSourceElementType();
2066 Type *DeducedPointeeTy = deduceElementType(PtrOp, true);
2067
2068 if (auto *ArrTy = dyn_cast<ArrayType>(DeducedPointeeTy)) {
2069 if (ArrTy->getElementType() == SrcElemTy) {
2070 SmallVector<Value *> NewIndices;
2071 Type *FirstIdxType = I.getOperand(1)->getType();
2072 NewIndices.push_back(ConstantInt::get(FirstIdxType, 0));
2073 for (Value *Idx : I.indices())
2074 NewIndices.push_back(Idx);
2075
2076 SmallVector<Type *, 2> Types = {I.getType(), I.getPointerOperandType()};
2077 SmallVector<Value *, 4> Args;
2078 Args.push_back(B.getInt1(I.isInBounds()));
2079 Args.push_back(I.getPointerOperand());
2080 Args.append(NewIndices.begin(), NewIndices.end());
2081
2082 Instruction *NewI = B.CreateIntrinsicWithoutFolding(Intrinsic::spv_gep,
2083 {Types}, {Args});
2084 replaceAllUsesWithAndErase(B, &I, NewI);
2085 return NewI;
2086 }
2087 }
2088 }
2089
2090 SmallVector<Type *, 2> Types = {I.getType(), I.getOperand(0)->getType()};
2091 SmallVector<Value *, 4> Args;
2092 Args.push_back(B.getInt1(I.isInBounds()));
2093 llvm::append_range(Args, I.operands());
2094 Instruction *NewI =
2095 B.CreateIntrinsicWithoutFolding(Intrinsic::spv_gep, {Types}, {Args});
2096 replaceAllUsesWithAndErase(B, &I, NewI);
2097 return NewI;
2098}
2099
2100Instruction *SPIRVEmitIntrinsicsImpl::visitBitCastInst(BitCastInst &I) {
2101 IRBuilder<> B(I.getParent());
2102 B.SetInsertPoint(&I);
2103 Value *Source = I.getOperand(0);
2104
2105 // SPIR-V, contrary to LLVM 17+ IR, supports bitcasts between pointers of
2106 // varying element types. In case of IR coming from older versions of LLVM
2107 // such bitcasts do not provide sufficient information, should be just skipped
2108 // here, and handled in insertPtrCastOrAssignTypeInstr.
2109 if (isPointerTy(I.getType())) {
2110 replaceAllUsesWith(&I, Source);
2111 I.eraseFromParent();
2112 return nullptr;
2113 }
2114
2115 SmallVector<Type *, 2> Types = {I.getType(), Source->getType()};
2116 SmallVector<Value *> Args(I.op_begin(), I.op_end());
2117 Instruction *NewI =
2118 B.CreateIntrinsicWithoutFolding(Intrinsic::spv_bitcast, {Types}, {Args});
2119 replaceAllUsesWithAndErase(B, &I, NewI);
2120 return NewI;
2121}
2122
2123void SPIRVEmitIntrinsicsImpl::insertAssignPtrTypeTargetExt(
2124 TargetExtType *AssignedType, Value *V, IRBuilder<> &B) {
2125 Type *VTy = V->getType();
2126
2127 // A couple of sanity checks.
2128 assert((isPointerTy(VTy)) && "Expect a pointer type!");
2129 if (Type *ElemTy = getPointeeType(VTy))
2130 if (ElemTy != AssignedType)
2131 report_fatal_error("Unexpected pointer element type!");
2132
2133 CallInst *AssignCI = GR->findAssignPtrTypeInstr(V);
2134 if (!AssignCI) {
2135 GR->buildAssignType(B, AssignedType, V);
2136 return;
2137 }
2138
2139 Type *CurrentType =
2141 cast<MetadataAsValue>(AssignCI->getOperand(1))->getMetadata())
2142 ->getType();
2143 if (CurrentType == AssignedType)
2144 return;
2145
2146 // Builtin types cannot be redeclared or casted.
2147 if (CurrentType->isTargetExtTy())
2148 report_fatal_error("Type mismatch " + CurrentType->getTargetExtName() +
2149 "/" + AssignedType->getTargetExtName() +
2150 " for value " + V->getName(),
2151 false);
2152
2153 // Our previous guess about the type seems to be wrong, let's update
2154 // inferred type according to a new, more precise type information.
2155 GR->updateAssignType(AssignCI, V, getNormalizedPoisonValue(AssignedType));
2156}
2157
2158void SPIRVEmitIntrinsicsImpl::replacePointerOperandWithPtrCast(
2159 Instruction *I, Value *Pointer, Type *ExpectedElementType,
2160 unsigned OperandToReplace, IRBuilder<> &B) {
2161 TypeValidated.insert(I);
2162
2163 // Do not emit spv_ptrcast if Pointer's element type is ExpectedElementType
2164 Type *PointerElemTy = deduceElementTypeHelper(Pointer, false);
2165 if (PointerElemTy == ExpectedElementType ||
2166 isEquivalentTypes(PointerElemTy, ExpectedElementType))
2167 return;
2168
2170 Value *ExpectedElementVal = getNormalizedPoisonValue(ExpectedElementType);
2171 MetadataAsValue *VMD = buildMD(ExpectedElementVal);
2172 unsigned AddressSpace = getPointerAddressSpace(Pointer->getType());
2173 bool FirstPtrCastOrAssignPtrType = true;
2174
2175 // Do not emit new spv_ptrcast if equivalent one already exists or when
2176 // spv_assign_ptr_type already targets this pointer with the same element
2177 // type.
2178 if (Pointer->hasUseList()) {
2179 for (auto User : Pointer->users()) {
2180 auto *II = dyn_cast<IntrinsicInst>(User);
2181 if (!II ||
2182 (II->getIntrinsicID() != Intrinsic::spv_assign_ptr_type &&
2183 II->getIntrinsicID() != Intrinsic::spv_ptrcast) ||
2184 II->getOperand(0) != Pointer)
2185 continue;
2186
2187 // There is some spv_ptrcast/spv_assign_ptr_type already targeting this
2188 // pointer.
2189 FirstPtrCastOrAssignPtrType = false;
2190 if (II->getOperand(1) != VMD ||
2191 dyn_cast<ConstantInt>(II->getOperand(2))->getSExtValue() !=
2193 continue;
2194
2195 // The spv_ptrcast/spv_assign_ptr_type targeting this pointer is of the
2196 // same element type and address space.
2197 if (II->getIntrinsicID() != Intrinsic::spv_ptrcast)
2198 return;
2199
2200 // This must be a spv_ptrcast, do not emit new if this one has the same BB
2201 // as I. Otherwise, search for other spv_ptrcast/spv_assign_ptr_type.
2202 if (II->getParent() != I->getParent())
2203 continue;
2204
2205 I->setOperand(OperandToReplace, II);
2206 return;
2207 }
2208 }
2209
2210 // Never replace an already-deduced pointer pointee with a non-pointer one.
2211 // The conflicting use comes from a mis-deduced expected type. Leave the
2212 // operand untouched rather than emitting a ptrcast that re-introduces
2213 // the collapsed type at the use site.
2214 if (PointerElemTy && isPointerTyOrWrapper(PointerElemTy) &&
2215 !isPointerTyOrWrapper(ExpectedElementType) &&
2216 tracesToPointerAlloca(Pointer))
2217 return;
2218
2219 if (isa<Instruction>(Pointer) || isa<Argument>(Pointer)) {
2220 if (FirstPtrCastOrAssignPtrType) {
2221 // If this would be the first spv_ptrcast, do not emit spv_ptrcast and
2222 // emit spv_assign_ptr_type instead.
2223 GR->buildAssignPtr(B, ExpectedElementType, Pointer);
2224 return;
2225 } else if (isTodoType(Pointer)) {
2226 eraseTodoType(Pointer);
2227 if (!isa<CallInst>(Pointer) && !isaGEP(Pointer) &&
2228 !isa<AllocaInst>(Pointer)) {
2229 // If this wouldn't be the first spv_ptrcast but existing type info is
2230 // uncomplete, update spv_assign_ptr_type arguments.
2231 if (CallInst *AssignCI = GR->findAssignPtrTypeInstr(Pointer)) {
2232 Type *PrevElemTy = GR->findDeducedElementType(Pointer);
2233 assert(PrevElemTy);
2234 DenseSet<std::pair<Value *, Value *>> VisitedSubst{
2235 std::make_pair(I, Pointer)};
2236 GR->updateAssignType(AssignCI, Pointer, ExpectedElementVal);
2237 propagateElemType(Pointer, PrevElemTy, VisitedSubst);
2238 } else {
2239 GR->buildAssignPtr(B, ExpectedElementType, Pointer);
2240 }
2241 return;
2242 }
2243 }
2244 }
2245
2246 // Emit spv_ptrcast
2247 SmallVector<Type *, 2> Types = {Pointer->getType(), Pointer->getType()};
2248 SmallVector<Value *, 2> Args = {Pointer, VMD, B.getInt32(AddressSpace)};
2249 auto *PtrCastI = B.CreateIntrinsic(Intrinsic::spv_ptrcast, {Types}, Args);
2250 I->setOperand(OperandToReplace, PtrCastI);
2251 // We need to set up a pointee type for the newly created spv_ptrcast.
2252 GR->buildAssignPtr(B, ExpectedElementType, PtrCastI);
2253}
2254
2255void SPIRVEmitIntrinsicsImpl::insertPtrCastOrAssignTypeInstr(Instruction *I,
2256 IRBuilder<> &B) {
2257 // Handle basic instructions:
2258 StoreInst *SI = dyn_cast<StoreInst>(I);
2259 if (IsKernelArgInt8(CurrF, SI)) {
2260 replacePointerOperandWithPtrCast(
2261 I, SI->getValueOperand(), IntegerType::getInt8Ty(CurrF->getContext()),
2262 0, B);
2263 }
2264 if (SI) {
2265 Value *Op = SI->getValueOperand();
2266 Value *Pointer = SI->getPointerOperand();
2267 Type *OpTy = Op->getType();
2268 if (auto *OpI = dyn_cast<Instruction>(Op)) {
2269 OpTy = restoreMutatedType(GR, OpI, OpTy);
2270 if (auto It = AggrConstTypes.find(OpI); It != AggrConstTypes.end())
2271 OpTy = It->second;
2272 }
2273 if (OpTy == Op->getType())
2274 OpTy = deduceElementTypeByValueDeep(OpTy, Op, false);
2275 replacePointerOperandWithPtrCast(I, Pointer, OpTy, 1, B);
2276 return;
2277 }
2278 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
2279 Value *Pointer = LI->getPointerOperand();
2280 Type *OpTy = LI->getType();
2281 if (auto *PtrTy = dyn_cast<PointerType>(OpTy)) {
2282 if (Type *ElemTy = GR->findDeducedElementType(LI)) {
2283 OpTy = getTypedPointerWrapper(ElemTy, PtrTy->getAddressSpace());
2284 } else {
2285 Type *NewOpTy = OpTy;
2286 OpTy = deduceElementTypeByValueDeep(OpTy, LI, false);
2287 if (OpTy == NewOpTy)
2288 insertTodoType(Pointer);
2289 }
2290 }
2291 replacePointerOperandWithPtrCast(I, Pointer, OpTy, 0, B);
2292 return;
2293 }
2294 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
2295 Value *Pointer = GEPI->getPointerOperand();
2296 Type *OpTy = nullptr;
2297
2298 // Logical SPIR-V is not allowed to use Op*PtrAccessChain instructions. If
2299 // the first index is 0, then we can trivially lower to OpAccessChain. If
2300 // not we need to try to rewrite the GEP. We avoid adding a pointer cast at
2301 // this time, and will rewrite the GEP when visiting it.
2302 if (TM.getSubtargetImpl()->isLogicalSPIRV() && !isFirstIndexZero(GEPI)) {
2303 return;
2304 }
2305
2306 // In all cases, fall back to the GEP type if type scavenging failed.
2307 if (!OpTy)
2308 OpTy = GEPI->getSourceElementType();
2309
2310 replacePointerOperandWithPtrCast(I, Pointer, OpTy, 0, B);
2311 if (isNestedPointer(OpTy))
2312 insertTodoType(Pointer);
2313 return;
2314 }
2315
2316 // TODO: review and merge with existing logics:
2317 // Handle calls to builtins (non-intrinsics):
2318 CallInst *CI = dyn_cast<CallInst>(I);
2319 if (!CI || CI->isIndirectCall() || CI->isInlineAsm() ||
2321 return;
2322
2323 // collect information about formal parameter types
2324 std::string DemangledName =
2326 Function *CalledF = CI->getCalledFunction();
2327 SmallVector<Type *, 4> CalledArgTys;
2328 bool HaveTypes = false;
2329 for (unsigned OpIdx = 0; OpIdx < CalledF->arg_size(); ++OpIdx) {
2330 Argument *CalledArg = CalledF->getArg(OpIdx);
2331 Type *ArgType = CalledArg->getType();
2332 if (!isPointerTy(ArgType)) {
2333 CalledArgTys.push_back(nullptr);
2334 } else if (Type *ArgTypeElem = getPointeeType(ArgType)) {
2335 CalledArgTys.push_back(ArgTypeElem);
2336 HaveTypes = true;
2337 } else {
2338 Type *ElemTy = GR->findDeducedElementType(CalledArg);
2339 if (!ElemTy && hasPointeeTypeAttr(CalledArg))
2340 ElemTy = getPointeeTypeByAttr(CalledArg);
2341 if (!ElemTy) {
2342 ElemTy = getPointeeTypeByCallInst(DemangledName, CalledF, OpIdx);
2343 if (ElemTy) {
2344 GR->addDeducedElementType(CalledArg, normalizeType(ElemTy));
2345 } else {
2346 for (User *U : CalledArg->users()) {
2347 if (Instruction *Inst = dyn_cast<Instruction>(U)) {
2348 if ((ElemTy = deduceElementTypeHelper(Inst, false)) != nullptr)
2349 break;
2350 }
2351 }
2352 }
2353 }
2354 HaveTypes |= ElemTy != nullptr;
2355 CalledArgTys.push_back(ElemTy);
2356 }
2357 }
2358
2359 if (DemangledName.empty() && !HaveTypes)
2360 return;
2361
2362 for (unsigned OpIdx = 0; OpIdx < CI->arg_size(); OpIdx++) {
2363 Value *ArgOperand = CI->getArgOperand(OpIdx);
2364 if (!isPointerTy(ArgOperand->getType()))
2365 continue;
2366
2367 // Constants (nulls/undefs) are handled in insertAssignPtrTypeIntrs()
2368 if (!isa<Instruction>(ArgOperand) && !isa<Argument>(ArgOperand)) {
2369 // However, we may have assumptions about the formal argument's type and
2370 // may have a need to insert a ptr cast for the actual parameter of this
2371 // call.
2372 Argument *CalledArg = CalledF->getArg(OpIdx);
2373 if (!GR->findDeducedElementType(CalledArg))
2374 continue;
2375 }
2376
2377 Type *ExpectedType =
2378 OpIdx < CalledArgTys.size() ? CalledArgTys[OpIdx] : nullptr;
2379 if (!ExpectedType && !DemangledName.empty())
2380 ExpectedType = SPIRV::parseBuiltinCallArgumentBaseType(
2381 DemangledName, OpIdx, I->getContext());
2382 if (!ExpectedType || ExpectedType->isVoidTy())
2383 continue;
2384
2385 if (ExpectedType->isTargetExtTy() &&
2387 insertAssignPtrTypeTargetExt(cast<TargetExtType>(ExpectedType),
2388 ArgOperand, B);
2389 else
2390 replacePointerOperandWithPtrCast(CI, ArgOperand, ExpectedType, OpIdx, B);
2391 }
2392}
2393
2395SPIRVEmitIntrinsicsImpl::visitInsertElementInst(InsertElementInst &I) {
2396 // If it's a <1 x Type> vector type, don't modify it. It's not a legal vector
2397 // type in LLT and IRTranslator will replace it by the scalar.
2398 if (isVector1(I.getType()))
2399 return &I;
2400
2401 SmallVector<Type *, 4> Types = {I.getType(), I.getOperand(0)->getType(),
2402 I.getOperand(1)->getType(),
2403 I.getOperand(2)->getType()};
2404 IRBuilder<> B(I.getParent());
2405 B.SetInsertPoint(&I);
2406 SmallVector<Value *> Args(I.op_begin(), I.op_end());
2407 Instruction *NewI = B.CreateIntrinsicWithoutFolding(Intrinsic::spv_insertelt,
2408 {Types}, {Args});
2409 replaceAllUsesWithAndErase(B, &I, NewI);
2410 return NewI;
2411}
2412
2414SPIRVEmitIntrinsicsImpl::visitExtractElementInst(ExtractElementInst &I) {
2415 // If it's a <1 x Type> vector type, don't modify it. It's not a legal vector
2416 // type in LLT and IRTranslator will replace it by the scalar.
2417 if (isVector1(I.getVectorOperandType()))
2418 return &I;
2419
2420 IRBuilder<> B(I.getParent());
2421 B.SetInsertPoint(&I);
2422 SmallVector<Type *, 3> Types = {I.getType(), I.getVectorOperandType(),
2423 I.getIndexOperand()->getType()};
2424 SmallVector<Value *, 2> Args = {I.getVectorOperand(), I.getIndexOperand()};
2425 Instruction *NewI = B.CreateIntrinsicWithoutFolding(Intrinsic::spv_extractelt,
2426 {Types}, {Args});
2427 replaceAllUsesWithAndErase(B, &I, NewI);
2428 return NewI;
2429}
2430
2431Instruction *SPIRVEmitIntrinsicsImpl::visitInsertValueInst(InsertValueInst &I) {
2432 IRBuilder<> B(I.getParent());
2433 B.SetInsertPoint(&I);
2434 SmallVector<Type *, 1> Types = {I.getInsertedValueOperand()->getType()};
2436 Value *AggregateOp = I.getAggregateOperand();
2437 if (isa<UndefValue>(AggregateOp))
2438 Args.push_back(UndefValue::get(B.getInt32Ty()));
2439 else
2440 Args.push_back(AggregateOp);
2441 Args.push_back(I.getInsertedValueOperand());
2442 for (auto &Op : I.indices())
2443 Args.push_back(B.getInt32(Op));
2444 Instruction *NewI =
2445 B.CreateIntrinsicWithoutFolding(Intrinsic::spv_insertv, {Types}, {Args});
2446 replaceMemInstrUses(&I, NewI, B);
2447 return NewI;
2448}
2449
2451SPIRVEmitIntrinsicsImpl::visitExtractValueInst(ExtractValueInst &I) {
2452 IRBuilder<> B(I.getParent());
2453 B.SetInsertPoint(&I);
2454 if (I.getAggregateOperand()->getType()->isAggregateType()) {
2455 // Mutate an aggregate-returning spv_extractv producer to i32 so
2456 // IRTranslator does not see a multi-register value.
2457 CallBase *CB = dyn_cast<CallBase>(I.getAggregateOperand());
2458 if (!CB || CB->getIntrinsicID() != Intrinsic::spv_extractv)
2459 return &I;
2460 CB->mutateType(B.getInt32Ty());
2461 }
2462 SmallVector<Value *> Args(I.operands());
2463 for (auto &Op : I.indices())
2464 Args.push_back(B.getInt32(Op));
2465 Instruction *NewI = B.CreateIntrinsicWithoutFolding(Intrinsic::spv_extractv,
2466 {I.getType()}, {Args});
2467 replaceAllUsesWithAndErase(B, &I, NewI);
2468 // If the aggregate result feeds a return or callsite whose type was rewritten
2469 // to an i32 value-id by SPIRVPrepareFunctions, mutate it to match.
2470 if (NewI->getType()->isAggregateType()) {
2471 for (const Use &U : NewI->uses()) {
2472 User *Usr = U.getUser();
2473 if (auto *RI = dyn_cast<ReturnInst>(Usr)) {
2474 if (RI->getFunction()->getReturnType() != NewI->getType()) {
2475 NewI->mutateType(B.getInt32Ty());
2476 break;
2477 }
2478 continue;
2479 }
2480 auto *CB = dyn_cast<CallBase>(Usr);
2481 if (!CB || !CB->isArgOperand(&U))
2482 continue;
2483 unsigned ArgNo = CB->getArgOperandNo(&U);
2484 FunctionType *FT = CB->getFunctionType();
2485 if (ArgNo < FT->getNumParams() &&
2486 !FT->getParamType(ArgNo)->isAggregateType()) {
2487 NewI->mutateType(B.getInt32Ty());
2488 break;
2489 }
2490 }
2491 }
2492 return NewI;
2493}
2494
2495Instruction *SPIRVEmitIntrinsicsImpl::visitLoadInst(LoadInst &I) {
2496 if (!I.getType()->isAggregateType())
2497 return &I;
2498 IRBuilder<> B(I.getParent());
2499 B.SetInsertPoint(&I);
2500 TrackConstants = false;
2501 const auto *TLI = TM.getSubtargetImpl()->getTargetLowering();
2503 TLI->getLoadMemOperandFlags(I, CurrF->getDataLayout());
2504
2505 unsigned IntrinsicId;
2506 SmallVector<Value *, 4> Args = {I.getPointerOperand(), B.getInt16(Flags)};
2507 if (!I.isAtomic()) {
2508 IntrinsicId = Intrinsic::spv_load;
2509 Args.push_back(B.getInt32(I.getAlign().value()));
2510 } else {
2511 IntrinsicId = Intrinsic::spv_atomic_load;
2512 Args.push_back(B.getInt8(static_cast<uint8_t>(I.getOrdering())));
2513 }
2514 CallInst *NewI = B.CreateIntrinsicWithoutFolding(
2515 IntrinsicId, {I.getOperand(0)->getType()}, Args);
2516
2517 replaceMemInstrUses(&I, NewI, B);
2518 return NewI;
2519}
2520
2521Instruction *SPIRVEmitIntrinsicsImpl::visitStoreInst(StoreInst &I) {
2522 if (!AggrStores.contains(&I))
2523 return &I;
2524 IRBuilder<> B(I.getParent());
2525 B.SetInsertPoint(&I);
2526 TrackConstants = false;
2527 const auto *TLI = TM.getSubtargetImpl()->getTargetLowering();
2529 TLI->getStoreMemOperandFlags(I, CurrF->getDataLayout());
2530 auto *PtrOp = I.getPointerOperand();
2531
2532 if (I.getValueOperand()->getType()->isAggregateType()) {
2533 // It is possible that what used to be an ExtractValueInst has been replaced
2534 // with a call to the spv_extractv intrinsic, and that said call hasn't
2535 // had its return type replaced with i32 during the dedicated pass (because
2536 // it was emitted later); we have to handle this here, because IRTranslator
2537 // cannot deal with multi-register types at the moment.
2538 CallBase *CB = dyn_cast<CallBase>(I.getValueOperand());
2539 assert(CB && CB->getIntrinsicID() == Intrinsic::spv_extractv &&
2540 "Unexpected argument of aggregate type, should be spv_extractv!");
2541 CB->mutateType(B.getInt32Ty());
2542 }
2543
2544 unsigned IntrinsicId;
2545 SmallVector<Value *, 4> Args = {I.getValueOperand(), PtrOp,
2546 B.getInt16(Flags)};
2547 if (!I.isAtomic()) {
2548 IntrinsicId = Intrinsic::spv_store;
2549 Args.push_back(B.getInt32(I.getAlign().value()));
2550 } else {
2551 IntrinsicId = Intrinsic::spv_atomic_store;
2552 Args.push_back(B.getInt8(static_cast<uint8_t>(I.getOrdering())));
2553 }
2554 Instruction *NewI = B.CreateIntrinsicWithoutFolding(
2555 IntrinsicId, {I.getValueOperand()->getType(), PtrOp->getType()}, Args);
2556 NewI->copyMetadata(I);
2557 I.eraseFromParent();
2558 return NewI;
2559}
2560
2561Instruction *SPIRVEmitIntrinsicsImpl::visitAllocaInst(AllocaInst &I) {
2562 Value *ArraySize = nullptr;
2563 if (I.isArrayAllocation()) {
2564 const SPIRVSubtarget *STI = TM.getSubtargetImpl(*I.getFunction());
2565 if (!STI->canUseExtension(
2566 SPIRV::Extension::SPV_INTEL_variable_length_array))
2568 "array allocation: this instruction requires the following "
2569 "SPIR-V extension: SPV_INTEL_variable_length_array",
2570 false);
2571 ArraySize = I.getArraySize();
2572 }
2573 IRBuilder<> B(I.getParent());
2574 B.SetInsertPoint(&I);
2575 TrackConstants = false;
2576 Type *PtrTy = I.getType();
2577 Instruction *NewI =
2578 ArraySize
2579 ? B.CreateIntrinsicWithoutFolding(
2580 Intrinsic::spv_alloca_array, {PtrTy, ArraySize->getType()},
2581 {ArraySize, B.getInt32(I.getAlign().value())})
2582 : B.CreateIntrinsicWithoutFolding(Intrinsic::spv_alloca, {PtrTy},
2583 {B.getInt32(I.getAlign().value())});
2584 replaceAllUsesWithAndErase(B, &I, NewI);
2585 return NewI;
2586}
2587
2589SPIRVEmitIntrinsicsImpl::visitAtomicCmpXchgInst(AtomicCmpXchgInst &I) {
2590 assert(I.getType()->isAggregateType() && "Aggregate result is expected");
2591 IRBuilder<> B(I.getParent());
2592 B.SetInsertPoint(&I);
2593 SmallVector<Value *> Args(I.operands());
2594 Args.push_back(B.getInt32(
2595 static_cast<uint32_t>(getMemScope(I.getContext(), I.getSyncScopeID()))));
2596 // Per SPIR-V spec atomic ops must combine the ordering bits with the
2597 // storage-class bit.
2598 const SPIRVSubtarget &ST = TM.getSubtarget<SPIRVSubtarget>(*I.getFunction());
2599 unsigned AS = I.getPointerOperand()->getType()->getPointerAddressSpace();
2600 uint32_t ScSem = static_cast<uint32_t>(
2602 Args.push_back(B.getInt32(
2603 static_cast<uint32_t>(getMemSemantics(I.getSuccessOrdering())) | ScSem));
2604 Args.push_back(B.getInt32(
2605 static_cast<uint32_t>(getMemSemantics(I.getFailureOrdering())) | ScSem));
2606 Instruction *NewI = B.CreateIntrinsicWithoutFolding(
2607 Intrinsic::spv_cmpxchg, {I.getPointerOperand()->getType()}, {Args});
2608 replaceMemInstrUses(&I, NewI, B);
2609 return NewI;
2610}
2611
2612static bool isAbortCall(const Instruction &I, const SPIRVSubtarget &ST) {
2613 auto *CI = dyn_cast<CallInst>(&I);
2614 if (!CI)
2615 return false;
2616 switch (CI->getIntrinsicID()) {
2617 case Intrinsic::spv_abort:
2618 return true;
2619 case Intrinsic::trap:
2620 case Intrinsic::ubsantrap:
2621 // When the extension is enabled, selection lowers these to OpAbortKHR.
2622 return ST.canUseExtension(SPIRV::Extension::SPV_KHR_abort);
2623 default:
2624 return false;
2625 }
2626}
2627
2628// The OpAbortKHR instruction itself is a block terminator, so we don't need to
2629// emit an extra OpUnreachable instruction.
2631 const SPIRVSubtarget &ST) {
2632 // Find a previous non-debug instruction.
2633 const Instruction *Prev = I.getPrevNode();
2634 while (Prev && Prev->isDebugOrPseudoInst())
2635 Prev = Prev->getPrevNode();
2636
2637 if (Prev && isAbortCall(*Prev, ST))
2638 return true;
2639
2641 *I.getParent(),
2642 [&ST](const Instruction &II) { return isAbortCall(II, ST); }) &&
2643 "abort-like call must be the last non-debug instruction before its "
2644 "block's terminator");
2645 return false;
2646}
2647
2648Instruction *SPIRVEmitIntrinsicsImpl::visitUnreachableInst(UnreachableInst &I) {
2649 const SPIRVSubtarget &ST = TM.getSubtarget<SPIRVSubtarget>(*I.getFunction());
2650 if (precededByAbortIntrinsic(I, ST))
2651 return &I;
2652 IRBuilder<> B(&I);
2653 B.CreateIntrinsic(Intrinsic::spv_unreachable, {});
2654 return &I;
2655}
2656
2657// llvm.compiler.used and llvm.used hold use-list entries that protect their
2658// referenced globals from DCE without participating in code generation.
2659static bool isUseListGlobal(StringRef Name) {
2660 return Name == "llvm.compiler.used" || Name == "llvm.used";
2661}
2662
2663// Returns true for module-level globals that should not have SPIR-V intrinsics
2664// emitted (use-list globals plus llvm.global.annotations).
2666 return isUseListGlobal(Name) || Name == "llvm.global.annotations";
2667}
2668
2669// Returns true if every use of GV traces back to llvm.compiler.used or
2670// llvm.used.
2674 while (!Stack.empty()) {
2675 const Value *V = Stack.pop_back_val();
2676 if (!Visited.insert(V).second)
2677 continue;
2678 if (const auto *GVUser = dyn_cast<GlobalVariable>(V)) {
2679 if (!isUseListGlobal(GVUser->getName()))
2680 return false;
2681 continue;
2682 }
2683 if (const auto *C = dyn_cast<Constant>(V)) {
2684 Stack.append(C->user_begin(), C->user_end());
2685 continue;
2686 }
2687 return false;
2688 }
2689 return true;
2690}
2691
2692static bool
2693shouldEmitIntrinsicsForGlobalValue(const GlobalVariableUsers &GVUsers,
2694 const GlobalVariable &GV,
2695 const Function *F) {
2696 // Skip special artificial variables.
2697 if (isArtificialGlobal(GV.getName()))
2698 return false;
2699
2700 auto &UserFunctions = GVUsers.getTransitiveUserFunctions(GV);
2701 if (UserFunctions.contains(F))
2702 return true;
2703
2704 // Do not emit the intrinsics in this function, it's going to be emitted on
2705 // the functions that reference it.
2706 if (!UserFunctions.empty())
2707 return false;
2708
2709 // Emit definitions for globals that are not referenced by any function on the
2710 // first function definition.
2711 const Module &M = *F->getParent();
2712 const Function &FirstDefinition = *M.getFunctionDefs().begin();
2713 return F == &FirstDefinition;
2714}
2715
2716Value *SPIRVEmitIntrinsicsImpl::buildSpvUndefComposite(Type *AggrTy,
2717 IRBuilder<> &B) {
2718 auto MakeLeaf = [&](Type *ElemTy) -> Instruction * {
2719 CallInst *Leaf = B.CreateIntrinsicWithoutFolding(Intrinsic::spv_undef, {});
2720 AggrConsts[Leaf] = PoisonValue::get(ElemTy);
2721 AggrConstTypes[Leaf] = ElemTy;
2722 return Leaf;
2723 };
2724 SmallVector<Value *, 4> Elems;
2725 if (auto *ArrTy = dyn_cast<ArrayType>(AggrTy)) {
2726 Elems.assign(ArrTy->getNumElements(), MakeLeaf(ArrTy->getElementType()));
2727 } else {
2728 auto *StructTy = cast<StructType>(AggrTy);
2729 DenseMap<Type *, Instruction *> LeafByType;
2730 for (unsigned I = 0; I < StructTy->getNumElements(); ++I) {
2731 Type *ElemTy = StructTy->getContainedType(I);
2732 auto &Entry = LeafByType[ElemTy];
2733 if (!Entry)
2734 Entry = MakeLeaf(ElemTy);
2735 Elems.push_back(Entry);
2736 }
2737 }
2738 CallInst *Composite = B.CreateIntrinsicWithoutFolding(
2739 Intrinsic::spv_const_composite, {B.getInt32Ty()}, Elems);
2740 AggrConsts[Composite] = PoisonValue::get(AggrTy);
2741 AggrConstTypes[Composite] = AggrTy;
2742 return Composite;
2743}
2744
2745// If a function directly returns an aggregate-typed call result,
2746// the ReturnInst carries an aggregate while the function signature
2747// was rewritten to i32 by SPIRVPrepareFunctions. Rebuild the return value
2748// via extractvalue/insertvalue so the regular spv_extractv/spv_insertv
2749// lowering produces a valid OpReturnValue.
2750void SPIRVEmitIntrinsicsImpl::reconstructAggregateReturns(Function &Func,
2751 IRBuilder<> &B) {
2752 Type *OrigRetTy = GR->findMutated(&Func);
2753 if (!OrigRetTy || !OrigRetTy->isAggregateType())
2754 return;
2755 for (BasicBlock &BB : Func) {
2756 auto *RI = dyn_cast<ReturnInst>(BB.getTerminator());
2757 if (!RI)
2758 continue;
2759 Value *RetVal = RI->getReturnValue();
2760 if (!RetVal || RetVal->getType() != OrigRetTy || !isa<CallBase>(RetVal))
2761 continue;
2762 Type *AggrTy = RetVal->getType();
2763 uint64_t NumElts = isa<StructType>(AggrTy)
2764 ? cast<StructType>(AggrTy)->getNumElements()
2765 : cast<ArrayType>(AggrTy)->getNumElements();
2766 B.SetInsertPoint(RI);
2767 Value *Rebuilt = PoisonValue::get(AggrTy);
2768 for (uint64_t I = 0; I < NumElts; ++I) {
2769 Value *Elt = B.CreateExtractValue(RetVal, I);
2770 Rebuilt = B.CreateInsertValue(Rebuilt, Elt, I);
2771 }
2772 RI->setOperand(0, Rebuilt);
2773 }
2774}
2775
2776void SPIRVEmitIntrinsicsImpl::processGlobalValue(GlobalVariable &GV,
2777 IRBuilder<> &B) {
2778
2779 if (!shouldEmitIntrinsicsForGlobalValue(GVUsers, GV, CurrF))
2780 return;
2781
2782 // Record the pointee type for every global, not only initialized ones, so an
2783 // undef non-constant aggregate global is not later collapsed to its element
2784 // type. Result is ignored, because TypedPointerType is not supported
2785 // by llvm IR general logic.
2786 deduceElementTypeHelper(&GV, false);
2787
2788 Constant *Init = nullptr;
2789 if (hasInitializer(&GV)) {
2790 Init = GV.getInitializer();
2791 Value *InitOp = Init;
2792 if (isa<UndefValue>(Init) && Init->getType()->isAggregateType()) {
2793 const SPIRVSubtarget *STI = TM.getSubtargetImpl();
2794 bool UsePoison =
2795 isa<PoisonValue>(Init) &&
2796 STI->canUseExtension(SPIRV::Extension::SPV_KHR_poison_freeze);
2797 if (UsePoison) {
2798 CallInst *Call = B.CreateIntrinsicWithoutFolding(Intrinsic::spv_poison,
2799 {B.getInt32Ty()}, {});
2800 AggrConsts[Call] = cast<PoisonValue>(Init);
2801 AggrConstTypes[Call] = Init->getType();
2802 InitOp = Call;
2803 } else {
2804 InitOp = buildSpvUndefComposite(Init->getType(), B);
2805 }
2806 }
2807 Type *Ty = isAggrConstForceInt32(Init) ? B.getInt32Ty() : Init->getType();
2808 Constant *Const = isAggrConstForceInt32(Init) ? B.getInt32(1) : Init;
2809 CallInst *InitInst = B.CreateIntrinsicWithoutFolding(
2810 Intrinsic::spv_init_global, {GV.getType(), Ty}, {&GV, Const});
2811 InitInst->setArgOperand(1, InitOp);
2812 }
2813 // Globals with only use-list references have no real function uses. Emit
2814 // spv_unref_global so buildGlobalVariable is called for them.
2815 if (!Init && hasOnlyArtificialUses(GV))
2816 B.CreateIntrinsic(Intrinsic::spv_unref_global, GV.getType(), &GV);
2817}
2818
2819// Return true, if we can't decide what is the pointee type now and will get
2820// back to the question later. Return false is spv_assign_ptr_type is not needed
2821// or can be inserted immediately.
2822bool SPIRVEmitIntrinsicsImpl::insertAssignPtrTypeIntrs(Instruction *I,
2823 IRBuilder<> &B,
2824 bool UnknownElemTypeI8) {
2826 if (!isPointerTy(I->getType()) || !requireAssignType(I))
2827 return false;
2828
2830 if (Type *ElemTy = deduceElementType(I, UnknownElemTypeI8)) {
2831 GR->buildAssignPtr(B, ElemTy, I);
2832 return false;
2833 }
2834 return true;
2835}
2836
2837void SPIRVEmitIntrinsicsImpl::insertAssignTypeIntrs(Instruction *I,
2838 IRBuilder<> &B) {
2839 // TODO: extend the list of functions with known result types
2840 static StringMap<unsigned> ResTypeWellKnown = {
2841 {"async_work_group_copy", WellKnownTypes::Event},
2842 {"async_work_group_strided_copy", WellKnownTypes::Event},
2843 {"__spirv_GroupAsyncCopy", WellKnownTypes::Event}};
2844
2846
2847 bool IsKnown = false;
2848 if (auto *CI = dyn_cast<CallInst>(I)) {
2849 if (!CI->isIndirectCall() && !CI->isInlineAsm() &&
2850 CI->getCalledFunction() && !CI->getCalledFunction()->isIntrinsic()) {
2851 Function *CalledF = CI->getCalledFunction();
2852 std::string DemangledName =
2854 FPDecorationId DecorationId = FPDecorationId::NONE;
2855 if (DemangledName.length() > 0)
2856 DemangledName =
2857 SPIRV::lookupBuiltinNameHelper(DemangledName, &DecorationId);
2858 auto ResIt = ResTypeWellKnown.find(DemangledName);
2859 if (ResIt != ResTypeWellKnown.end()) {
2860 IsKnown = true;
2862 switch (ResIt->second) {
2863 case WellKnownTypes::Event:
2864 GR->buildAssignType(
2865 B, TargetExtType::get(I->getContext(), "spirv.Event"), I);
2866 break;
2867 }
2868 }
2869 // check if a floating rounding mode or saturation info is present
2870 switch (DecorationId) {
2871 default:
2872 break;
2873 case FPDecorationId::SAT:
2875 break;
2876 case FPDecorationId::RTE:
2878 CI, SPIRV::FPRoundingMode::FPRoundingMode::RTE, B);
2879 break;
2880 case FPDecorationId::RTZ:
2882 CI, SPIRV::FPRoundingMode::FPRoundingMode::RTZ, B);
2883 break;
2884 case FPDecorationId::RTP:
2886 CI, SPIRV::FPRoundingMode::FPRoundingMode::RTP, B);
2887 break;
2888 case FPDecorationId::RTN:
2890 CI, SPIRV::FPRoundingMode::FPRoundingMode::RTN, B);
2891 break;
2892 }
2893 }
2894 }
2895
2896 Type *Ty = I->getType();
2897 if (!IsKnown && !Ty->isVoidTy() && !isPointerTy(Ty) && requireAssignType(I)) {
2899 Type *TypeToAssign = Ty;
2900 if (auto *II = dyn_cast<IntrinsicInst>(I)) {
2901 if (isSpvAggrPlaceholder(II)) {
2902 auto It = AggrConstTypes.find(II);
2903 if (It == AggrConstTypes.end())
2904 report_fatal_error("Unknown composite intrinsic type");
2905 TypeToAssign = It->second;
2906 } else if (II->getIntrinsicID() == Intrinsic::spv_poison) {
2907 if (auto It = AggrConstTypes.find(II); It != AggrConstTypes.end())
2908 TypeToAssign = It->second;
2909 }
2910 } else if (auto It = AggrConstTypes.find(I); It != AggrConstTypes.end())
2911 TypeToAssign = It->second;
2912 TypeToAssign = restoreMutatedType(GR, I, TypeToAssign);
2913 GR->buildAssignType(B, TypeToAssign, I);
2914 }
2915 for (const auto &Op : I->operands()) {
2917 // Check GetElementPtrConstantExpr case.
2919 (isa<GEPOperator>(Op) ||
2920 (cast<ConstantExpr>(Op)->getOpcode() == CastInst::IntToPtr)))) {
2922 Type *OpTy = Op->getType();
2923 if (isa<UndefValue>(Op) && OpTy->isAggregateType()) {
2924 CallInst *AssignCI =
2925 buildIntrWithMD(Intrinsic::spv_assign_type, {B.getInt32Ty()}, Op,
2926 UndefValue::get(B.getInt32Ty()), {}, B);
2927 GR->addAssignPtrTypeInstr(Op, AssignCI);
2928 } else if (!isa<Instruction>(Op)) {
2929 Type *OpTy = Op->getType();
2930 Type *OpTyElem = getPointeeType(OpTy);
2931 if (OpTyElem) {
2932 GR->buildAssignPtr(B, OpTyElem, Op);
2933 } else if (isPointerTy(OpTy)) {
2934 Type *ElemTy = GR->findDeducedElementType(Op);
2935 GR->buildAssignPtr(B, ElemTy ? ElemTy : deduceElementType(Op, true),
2936 Op);
2937 } else {
2938 Value *OpTyVal = Op;
2939 if (OpTy->isTargetExtTy()) {
2940 // We need to do this in order to be consistent with how target ext
2941 // types are handled in `processInstrAfterVisit`
2942 OpTyVal = getNormalizedPoisonValue(OpTy);
2943 }
2944 CallInst *AssignCI =
2945 buildIntrWithMD(Intrinsic::spv_assign_type, {OpTy},
2946 getNormalizedPoisonValue(OpTy), OpTyVal, {}, B);
2947 GR->addAssignPtrTypeInstr(OpTyVal, AssignCI);
2948 }
2949 }
2950 }
2951 }
2952}
2953
2954bool SPIRVEmitIntrinsicsImpl::shouldTryToAddMemAliasingDecoration(
2955 Instruction *Inst) {
2956 const SPIRVSubtarget *STI = TM.getSubtargetImpl(*Inst->getFunction());
2957 if (!STI->canUseExtension(SPIRV::Extension::SPV_INTEL_memory_access_aliasing))
2958 return false;
2959 // Add aliasing decorations to internal load and store intrinsics.
2960 // Do not attach them to store atomic or load atomic intrinsics / instructions
2961 // since the extension is inconsistent at the moment (we cannot add the
2962 // decoration to atomic stores because they do not have an id).
2963 return match(Inst,
2965}
2966
2967void SPIRVEmitIntrinsicsImpl::insertSpirvDecorations(Instruction *I,
2968 IRBuilder<> &B) {
2969 if (MDNode *MD = I->getMetadata("spirv.Decorations")) {
2971 B.CreateIntrinsic(Intrinsic::spv_assign_decoration, {I->getType()},
2972 {I, MetadataAsValue::get(I->getContext(), MD)});
2973 }
2974 // Lower alias.scope/noalias metadata
2975 {
2976 auto processMemAliasingDecoration = [&](unsigned Kind) {
2977 if (MDNode *AliasListMD = I->getMetadata(Kind)) {
2978 if (shouldTryToAddMemAliasingDecoration(I)) {
2979 uint32_t Dec = Kind == LLVMContext::MD_alias_scope
2980 ? SPIRV::Decoration::AliasScopeINTEL
2981 : SPIRV::Decoration::NoAliasINTEL;
2983 I, ConstantInt::get(B.getInt32Ty(), Dec),
2984 MetadataAsValue::get(I->getContext(), AliasListMD)};
2986 B.CreateIntrinsic(Intrinsic::spv_assign_aliasing_decoration,
2987 {I->getType()}, {Args});
2988 }
2989 }
2990 };
2991 processMemAliasingDecoration(LLVMContext::MD_alias_scope);
2992 processMemAliasingDecoration(LLVMContext::MD_noalias);
2993 }
2994 // MD_fpmath
2995 if (MDNode *MD = I->getMetadata(LLVMContext::MD_fpmath)) {
2996 const SPIRVSubtarget *STI = TM.getSubtargetImpl(*I->getFunction());
2997 bool AllowFPMaxError =
2998 STI->canUseExtension(SPIRV::Extension::SPV_INTEL_fp_max_error);
2999 if (!AllowFPMaxError)
3000 return;
3001
3003 B.CreateIntrinsic(Intrinsic::spv_assign_fpmaxerror_decoration,
3004 {I->getType()},
3005 {I, MetadataAsValue::get(I->getContext(), MD)});
3006 }
3007 if (I->getModule()->getTargetTriple().getVendor() == Triple::AMD &&
3009 // If present, we encode AMDGPU atomic metadata as UserSemantic string
3010 // decorations, which will be parsed during reverse translation.
3011 auto &Ctx = B.getContext();
3012 auto *US = ConstantAsMetadata::get(
3013 ConstantInt::get(B.getInt32Ty(), SPIRV::Decoration::UserSemantic));
3014
3016 if (I->hasMetadata("amdgpu.no.fine.grained.memory"))
3018 Ctx, {US, MDString::get(Ctx, "amdgpu.no.fine.grained.memory")}));
3019 if (I->hasMetadata("amdgpu.no.remote.memory"))
3021 Ctx, {US, MDString::get(Ctx, "amdgpu.no.remote.memory")}));
3022 if (I->hasMetadata("amdgpu.ignore.denormal.mode"))
3024 Ctx, {US, MDString::get(Ctx, "amdgpu.ignore.denormal.mode")}));
3025 if (!MDs.empty())
3026 B.CreateIntrinsic(Intrinsic::spv_assign_decoration, {I->getType()},
3027 {I, MetadataAsValue::get(Ctx, MDNode::get(Ctx, MDs))});
3028 }
3029}
3030
3032 const Module &M,
3034 &FPFastMathDefaultInfoMap,
3035 Function *F) {
3036 auto it = FPFastMathDefaultInfoMap.find(F);
3037 if (it != FPFastMathDefaultInfoMap.end())
3038 return it->second;
3039
3040 // If the map does not contain the entry, create a new one. Initialize it to
3041 // contain all 3 elements sorted by bit width of target type: {half, float,
3042 // double}.
3043 SPIRV::FPFastMathDefaultInfoVector FPFastMathDefaultInfoVec;
3044 FPFastMathDefaultInfoVec.emplace_back(Type::getHalfTy(M.getContext()),
3045 SPIRV::FPFastMathMode::None);
3046 FPFastMathDefaultInfoVec.emplace_back(Type::getFloatTy(M.getContext()),
3047 SPIRV::FPFastMathMode::None);
3048 FPFastMathDefaultInfoVec.emplace_back(Type::getDoubleTy(M.getContext()),
3049 SPIRV::FPFastMathMode::None);
3050 return FPFastMathDefaultInfoMap[F] = std::move(FPFastMathDefaultInfoVec);
3051}
3052
3054 SPIRV::FPFastMathDefaultInfoVector &FPFastMathDefaultInfoVec,
3055 const Type *Ty) {
3056 size_t BitWidth = Ty->getScalarSizeInBits();
3057 int Index =
3059 BitWidth);
3060 assert(Index >= 0 && Index < 3 &&
3061 "Expected FPFastMathDefaultInfo for half, float, or double");
3062 assert(FPFastMathDefaultInfoVec.size() == 3 &&
3063 "Expected FPFastMathDefaultInfoVec to have exactly 3 elements");
3064 return FPFastMathDefaultInfoVec[Index];
3065}
3066
3067void SPIRVEmitIntrinsicsImpl::insertConstantsForFPFastMathDefault(Module &M) {
3068 const SPIRVSubtarget *ST = TM.getSubtargetImpl();
3069 if (!ST->canUseExtension(SPIRV::Extension::SPV_KHR_float_controls2))
3070 return;
3071
3072 // Store the FPFastMathDefaultInfo in the FPFastMathDefaultInfoMap.
3073 // We need the entry point (function) as the key, and the target
3074 // type and flags as the value.
3075 // We also need to check ContractionOff and SignedZeroInfNanPreserve
3076 // execution modes, as they are now deprecated and must be replaced
3077 // with FPFastMathDefaultInfo.
3078 auto Node = M.getNamedMetadata("spirv.ExecutionMode");
3079 if (!Node) {
3080 if (!M.getNamedMetadata("opencl.enable.FP_CONTRACT")) {
3081 // This requires emitting ContractionOff. However, because
3082 // ContractionOff is now deprecated, we need to replace it with
3083 // FPFastMathDefaultInfo with FP Fast Math Mode bitmask set to all 0.
3084 // We need to create the constant for that.
3085
3086 // Create constant instruction with the bitmask flags.
3087 Constant *InitValue =
3088 ConstantInt::get(Type::getInt32Ty(M.getContext()), 0);
3089 // TODO: Reuse constant if there is one already with the required
3090 // value.
3091 [[maybe_unused]] GlobalVariable *GV =
3092 new GlobalVariable(M, // Module
3093 Type::getInt32Ty(M.getContext()), // Type
3094 true, // isConstant
3096 InitValue // Initializer
3097 );
3098 }
3099 return;
3100 }
3101
3102 // The table maps function pointers to their default FP fast math info. It
3103 // can be assumed that the SmallVector is sorted by the bit width of the
3104 // type. The first element is the smallest bit width, and the last element
3105 // is the largest bit width, therefore, we will have {half, float, double}
3106 // in the order of their bit widths.
3107 DenseMap<Function *, SPIRV::FPFastMathDefaultInfoVector>
3108 FPFastMathDefaultInfoMap;
3109
3110 for (unsigned i = 0; i < Node->getNumOperands(); i++) {
3111 MDNode *MDN = cast<MDNode>(Node->getOperand(i));
3112 assert(MDN->getNumOperands() >= 2 && "Expected at least 2 operands");
3114 cast<ConstantAsMetadata>(MDN->getOperand(0))->getValue());
3115 const auto EM =
3117 cast<ConstantAsMetadata>(MDN->getOperand(1))->getValue())
3118 ->getZExtValue();
3119 if (EM == SPIRV::ExecutionMode::FPFastMathDefault) {
3120 assert(MDN->getNumOperands() == 4 &&
3121 "Expected 4 operands for FPFastMathDefault");
3122 const Type *T = cast<ValueAsMetadata>(MDN->getOperand(2))->getType();
3123 unsigned Flags =
3125 cast<ConstantAsMetadata>(MDN->getOperand(3))->getValue())
3126 ->getZExtValue();
3127 SPIRV::FPFastMathDefaultInfoVector &FPFastMathDefaultInfoVec =
3128 getOrCreateFPFastMathDefaultInfoVec(M, FPFastMathDefaultInfoMap, F);
3129 SPIRV::FPFastMathDefaultInfo &Info =
3130 getFPFastMathDefaultInfo(FPFastMathDefaultInfoVec, T);
3131 Info.FastMathFlags = Flags;
3132 Info.FPFastMathDefault = true;
3133 } else if (EM == SPIRV::ExecutionMode::ContractionOff) {
3134 assert(MDN->getNumOperands() == 2 &&
3135 "Expected no operands for ContractionOff");
3136
3137 // We need to save this info for every possible FP type, i.e. {half,
3138 // float, double, fp128}.
3139 SPIRV::FPFastMathDefaultInfoVector &FPFastMathDefaultInfoVec =
3140 getOrCreateFPFastMathDefaultInfoVec(M, FPFastMathDefaultInfoMap, F);
3141 for (SPIRV::FPFastMathDefaultInfo &Info : FPFastMathDefaultInfoVec) {
3142 Info.ContractionOff = true;
3143 }
3144 } else if (EM == SPIRV::ExecutionMode::SignedZeroInfNanPreserve) {
3145 assert(MDN->getNumOperands() == 3 &&
3146 "Expected 1 operand for SignedZeroInfNanPreserve");
3147 unsigned TargetWidth =
3149 cast<ConstantAsMetadata>(MDN->getOperand(2))->getValue())
3150 ->getZExtValue();
3151 // We need to save this info only for the FP type with TargetWidth.
3152 SPIRV::FPFastMathDefaultInfoVector &FPFastMathDefaultInfoVec =
3153 getOrCreateFPFastMathDefaultInfoVec(M, FPFastMathDefaultInfoMap, F);
3156 assert(Index >= 0 && Index < 3 &&
3157 "Expected FPFastMathDefaultInfo for half, float, or double");
3158 assert(FPFastMathDefaultInfoVec.size() == 3 &&
3159 "Expected FPFastMathDefaultInfoVec to have exactly 3 elements");
3160 FPFastMathDefaultInfoVec[Index].SignedZeroInfNanPreserve = true;
3161 }
3162 }
3163
3164 DenseMap<unsigned, GlobalVariable *> GlobalVars;
3165 for (auto &[Func, FPFastMathDefaultInfoVec] : FPFastMathDefaultInfoMap) {
3166 if (FPFastMathDefaultInfoVec.empty())
3167 continue;
3168
3169 for (const SPIRV::FPFastMathDefaultInfo &Info : FPFastMathDefaultInfoVec) {
3170 assert(Info.Ty && "Expected target type for FPFastMathDefaultInfo");
3171 // Skip if none of the execution modes was used.
3172 unsigned Flags = Info.FastMathFlags;
3173 if (Flags == SPIRV::FPFastMathMode::None && !Info.ContractionOff &&
3174 !Info.SignedZeroInfNanPreserve && !Info.FPFastMathDefault)
3175 continue;
3176
3177 // Check if flags are compatible.
3178 if (Info.ContractionOff && (Flags & SPIRV::FPFastMathMode::AllowContract))
3179 report_fatal_error("Conflicting FPFastMathFlags: ContractionOff "
3180 "and AllowContract");
3181
3182 if (Info.SignedZeroInfNanPreserve &&
3183 !(Flags &
3184 (SPIRV::FPFastMathMode::NotNaN | SPIRV::FPFastMathMode::NotInf |
3185 SPIRV::FPFastMathMode::NSZ))) {
3186 if (Info.FPFastMathDefault)
3187 report_fatal_error("Conflicting FPFastMathFlags: "
3188 "SignedZeroInfNanPreserve but at least one of "
3189 "NotNaN/NotInf/NSZ is enabled.");
3190 }
3191
3192 if ((Flags & SPIRV::FPFastMathMode::AllowTransform) &&
3193 !((Flags & SPIRV::FPFastMathMode::AllowReassoc) &&
3194 (Flags & SPIRV::FPFastMathMode::AllowContract))) {
3195 report_fatal_error("Conflicting FPFastMathFlags: "
3196 "AllowTransform requires AllowReassoc and "
3197 "AllowContract to be set.");
3198 }
3199
3200 auto it = GlobalVars.find(Flags);
3201 GlobalVariable *GV = nullptr;
3202 if (it != GlobalVars.end()) {
3203 // Reuse existing global variable.
3204 GV = it->second;
3205 } else {
3206 // Create constant instruction with the bitmask flags.
3207 Constant *InitValue =
3208 ConstantInt::get(Type::getInt32Ty(M.getContext()), Flags);
3209 // TODO: Reuse constant if there is one already with the required
3210 // value.
3211 GV = new GlobalVariable(M, // Module
3212 Type::getInt32Ty(M.getContext()), // Type
3213 true, // isConstant
3215 InitValue // Initializer
3216 );
3217 GlobalVars[Flags] = GV;
3218 }
3219 }
3220 }
3221}
3222
3223void SPIRVEmitIntrinsicsImpl::processInstrAfterVisit(Instruction *I,
3224 IRBuilder<> &B) {
3225 auto *II = dyn_cast<IntrinsicInst>(I);
3226 bool IsConstComposite =
3227 II && II->getIntrinsicID() == Intrinsic::spv_const_composite;
3228 if (IsConstComposite && TrackConstants) {
3230 auto t = AggrConsts.find(I);
3231 assert(t != AggrConsts.end());
3232 auto *NewOp =
3233 buildIntrWithMD(Intrinsic::spv_track_constant,
3234 {II->getType(), II->getType()}, t->second, I, {}, B);
3235 replaceAllUsesWith(I, NewOp, false);
3236 NewOp->setArgOperand(0, I);
3237 }
3238 bool IsPhi = isa<PHINode>(I), BPrepared = false;
3239 for (const auto &Op : I->operands()) {
3240 if (isa<PHINode>(I) || isa<SwitchInst>(I) ||
3242 continue;
3243 unsigned OpNo = Op.getOperandNo();
3244 if (II && ((II->getIntrinsicID() == Intrinsic::spv_gep && OpNo == 0) ||
3245 (!II->isBundleOperand(OpNo) &&
3246 II->paramHasAttr(OpNo, Attribute::ImmArg))))
3247 continue;
3248
3249 if (!BPrepared) {
3250 IsPhi ? B.SetInsertPointPastAllocas(I->getParent()->getParent())
3251 : B.SetInsertPoint(I);
3252 BPrepared = true;
3253 }
3254 Type *OpTy = Op->getType();
3255 Type *OpElemTy = GR->findDeducedElementType(Op);
3256 Value *NewOp = Op;
3257 if (OpTy->isTargetExtTy()) {
3258 // Since this value is replaced by poison, we need to do the same in
3259 // `insertAssignTypeIntrs`.
3260 Value *OpTyVal = getNormalizedPoisonValue(OpTy);
3261 NewOp = buildIntrWithMD(Intrinsic::spv_track_constant,
3262 {OpTy, OpTyVal->getType()}, Op, OpTyVal, {}, B);
3263 }
3264 if (!IsConstComposite && isPointerTy(OpTy) && OpElemTy != nullptr &&
3265 OpElemTy != IntegerType::getInt8Ty(I->getContext())) {
3266 SmallVector<Type *, 2> Types = {OpTy, OpTy};
3267 SmallVector<Value *, 2> Args = {
3268 NewOp, buildMD(getNormalizedPoisonValue(OpElemTy)),
3269 B.getInt32(getPointerAddressSpace(OpTy))};
3270 CallInst *PtrCasted = B.CreateIntrinsicWithoutFolding(
3271 Intrinsic::spv_ptrcast, {Types}, Args);
3272 GR->buildAssignPtr(B, OpElemTy, PtrCasted);
3273 NewOp = PtrCasted;
3274 }
3275 if (NewOp != Op)
3276 I->setOperand(OpNo, NewOp);
3277 }
3278 if (Named.insert(I).second)
3279 emitAssignName(I, B);
3280}
3281
3282Type *SPIRVEmitIntrinsicsImpl::deduceFunParamElementType(Function *F,
3283 unsigned OpIdx) {
3284 SmallPtrSet<Function *, 0> FVisited;
3285 return deduceFunParamElementType(F, OpIdx, FVisited);
3286}
3287
3288Type *SPIRVEmitIntrinsicsImpl::deduceFunParamElementType(
3289 Function *F, unsigned OpIdx, SmallPtrSetImpl<Function *> &FVisited) {
3290 // maybe a cycle
3291 if (!FVisited.insert(F).second)
3292 return nullptr;
3293
3294 SmallPtrSet<Value *, 0> Visited;
3296 // search in function's call sites
3297 for (User *U : F->users()) {
3298 CallInst *CI = dyn_cast<CallInst>(U);
3299 if (!CI || OpIdx >= CI->arg_size())
3300 continue;
3301 Value *OpArg = CI->getArgOperand(OpIdx);
3302 if (!isPointerTy(OpArg->getType()))
3303 continue;
3304 // maybe we already know operand's element type
3305 if (Type *KnownTy = GR->findDeducedElementType(OpArg))
3306 return KnownTy;
3307 // try to deduce from the operand itself
3308 Visited.clear();
3309 if (Type *Ty = deduceElementTypeHelper(OpArg, Visited, false))
3310 return Ty;
3311 // search in actual parameter's users
3312 for (User *OpU : OpArg->users()) {
3314 if (!Inst || Inst == CI)
3315 continue;
3316 Visited.clear();
3317 if (Type *Ty = deduceElementTypeHelper(Inst, Visited, false))
3318 return Ty;
3319 }
3320 // check if it's a formal parameter of the outer function
3321 if (!CI->getParent() || !CI->getParent()->getParent())
3322 continue;
3323 Function *OuterF = CI->getParent()->getParent();
3324 if (FVisited.find(OuterF) != FVisited.end())
3325 continue;
3326 for (unsigned i = 0; i < OuterF->arg_size(); ++i) {
3327 if (OuterF->getArg(i) == OpArg) {
3328 Lookup.push_back(std::make_pair(OuterF, i));
3329 break;
3330 }
3331 }
3332 }
3333
3334 // search in function parameters
3335 for (auto &Pair : Lookup) {
3336 if (Type *Ty = deduceFunParamElementType(Pair.first, Pair.second, FVisited))
3337 return Ty;
3338 }
3339
3340 return nullptr;
3341}
3342
3343void SPIRVEmitIntrinsicsImpl::processParamTypesByFunHeader(Function *F,
3344 IRBuilder<> &B) {
3345 B.SetInsertPointPastAllocas(F);
3346 for (unsigned OpIdx = 0; OpIdx < F->arg_size(); ++OpIdx) {
3347 Argument *Arg = F->getArg(OpIdx);
3348 // Vector-of-pointers arg: deduce pointee from a GEP user so the function
3349 // type isn't emitted with the default i8 pointee.
3350 if (isUntypedPointerVectorTy(Arg->getType()) &&
3351 !GR->findDeducedElementType(Arg)) {
3352 for (User *U : Arg->users()) {
3354 if (GEP && GEP->getPointerOperand() == Arg) {
3355 GR->buildAssignPtr(B, GEP->getSourceElementType(), Arg);
3356 break;
3357 }
3358 }
3359 continue;
3360 }
3361 if (!isUntypedPointerTy(Arg->getType()))
3362 continue;
3363 Type *ElemTy = GR->findDeducedElementType(Arg);
3364 if (ElemTy)
3365 continue;
3366 if (hasPointeeTypeAttr(Arg) &&
3367 (ElemTy = getPointeeTypeByAttr(Arg)) != nullptr) {
3368 GR->buildAssignPtr(B, ElemTy, Arg);
3369 continue;
3370 }
3371 // search in function's call sites
3372 for (User *U : F->users()) {
3373 CallInst *CI = dyn_cast<CallInst>(U);
3374 if (!CI || OpIdx >= CI->arg_size())
3375 continue;
3376 Value *OpArg = CI->getArgOperand(OpIdx);
3377 if (!isPointerTy(OpArg->getType()))
3378 continue;
3379 // maybe we already know operand's element type
3380 if ((ElemTy = GR->findDeducedElementType(OpArg)) != nullptr)
3381 break;
3382 }
3383 if (ElemTy) {
3384 GR->buildAssignPtr(B, ElemTy, Arg);
3385 continue;
3386 }
3387 if (HaveFunPtrs) {
3388 for (User *U : Arg->users()) {
3389 CallInst *CI = dyn_cast<CallInst>(U);
3390 if (CI && !isa<IntrinsicInst>(CI) && CI->isIndirectCall() &&
3391 CI->getCalledOperand() == Arg &&
3392 CI->getParent()->getParent() == CurrF) {
3394 deduceOperandElementTypeFunctionPointer(CI, Ops, ElemTy, false);
3395 if (ElemTy) {
3396 GR->buildAssignPtr(B, ElemTy, Arg);
3397 break;
3398 }
3399 }
3400 }
3401 }
3402 }
3403}
3404
3405void SPIRVEmitIntrinsicsImpl::processParamTypes(Function *F, IRBuilder<> &B) {
3406 B.SetInsertPointPastAllocas(F);
3407 for (unsigned OpIdx = 0; OpIdx < F->arg_size(); ++OpIdx) {
3408 Argument *Arg = F->getArg(OpIdx);
3409 if (!isUntypedPointerTy(Arg->getType()))
3410 continue;
3411 Type *ElemTy = GR->findDeducedElementType(Arg);
3412 if (!ElemTy && (ElemTy = deduceFunParamElementType(F, OpIdx)) != nullptr) {
3413 if (CallInst *AssignCI = GR->findAssignPtrTypeInstr(Arg)) {
3414 DenseSet<std::pair<Value *, Value *>> VisitedSubst;
3415 GR->updateAssignType(AssignCI, Arg, getNormalizedPoisonValue(ElemTy));
3416 propagateElemType(Arg, IntegerType::getInt8Ty(F->getContext()),
3417 VisitedSubst);
3418 } else {
3419 GR->buildAssignPtr(B, ElemTy, Arg);
3420 }
3421 }
3422 }
3423}
3424
3426 SPIRVGlobalRegistry *GR) {
3427 FunctionType *FTy = F->getFunctionType();
3428 bool IsNewFTy = false;
3430 for (Argument &Arg : F->args()) {
3431 Type *ArgTy = Arg.getType();
3432 if (ArgTy->isPointerTy())
3433 if (Type *ElemTy = GR->findDeducedElementType(&Arg)) {
3434 IsNewFTy = true;
3435 ArgTy = getTypedPointerWrapper(ElemTy, getPointerAddressSpace(ArgTy));
3436 }
3437 ArgTys.push_back(ArgTy);
3438 }
3439 return IsNewFTy
3440 ? FunctionType::get(FTy->getReturnType(), ArgTys, FTy->isVarArg())
3441 : FTy;
3442}
3443
3444bool SPIRVEmitIntrinsicsImpl::processFunctionPointers(Module &M) {
3445 SmallVector<Function *> Worklist;
3446 for (auto &F : M) {
3447 if (F.isIntrinsic())
3448 continue;
3449 if (F.isDeclaration()) {
3450 for (User *U : F.users()) {
3451 CallInst *CI = dyn_cast<CallInst>(U);
3452 if (!CI || CI->getCalledFunction() != &F) {
3453 Worklist.push_back(&F);
3454 break;
3455 }
3456 }
3457 } else {
3458 if (F.user_empty())
3459 continue;
3460 Type *FPElemTy = GR->findDeducedElementType(&F);
3461 if (!FPElemTy)
3462 FPElemTy = getFunctionPointerElemType(&F, GR);
3463 for (User *U : F.users()) {
3464 IntrinsicInst *II = dyn_cast<IntrinsicInst>(U);
3465 if (!II || II->arg_size() != 3 || II->getOperand(0) != &F)
3466 continue;
3467 if (II->getIntrinsicID() == Intrinsic::spv_assign_ptr_type ||
3468 II->getIntrinsicID() == Intrinsic::spv_ptrcast) {
3470 break;
3471 }
3472 }
3473 }
3474 }
3475 if (Worklist.empty())
3476 return false;
3477
3478 LLVMContext &Ctx = M.getContext();
3480 BasicBlock *BB = BasicBlock::Create(Ctx, "entry", SF);
3481 IRBuilder<> IRB(BB);
3482
3483 for (Function *F : Worklist) {
3485 for (const auto &Arg : F->args())
3486 Args.push_back(getNormalizedPoisonValue(Arg.getType()));
3487 IRB.CreateCall(F, Args);
3488 }
3489 IRB.CreateRetVoid();
3490
3491 return true;
3492}
3493
3494// Apply types parsed from demangled function declarations.
3495void SPIRVEmitIntrinsicsImpl::applyDemangledPtrArgTypes(IRBuilder<> &B) {
3496 DenseMap<Function *, CallInst *> Ptrcasts;
3497 for (auto It : FDeclPtrTys) {
3498 Function *F = It.first;
3499 for (auto *U : F->users()) {
3500 CallInst *CI = dyn_cast<CallInst>(U);
3501 if (!CI || CI->getCalledFunction() != F)
3502 continue;
3503 unsigned Sz = CI->arg_size();
3504 for (auto [Idx, ElemTy] : It.second) {
3505 if (Idx >= Sz)
3506 continue;
3507 Value *Param = CI->getArgOperand(Idx);
3508 if (GR->findDeducedElementType(Param) || isa<GlobalValue>(Param))
3509 continue;
3510 if (Argument *Arg = dyn_cast<Argument>(Param)) {
3511 if (!hasPointeeTypeAttr(Arg)) {
3512 B.SetInsertPointPastAllocas(Arg->getParent());
3513 B.SetCurrentDebugLocation(DebugLoc());
3514 GR->buildAssignPtr(B, ElemTy, Arg);
3515 }
3516 } else if (isaGEP(Param)) {
3517 replaceUsesOfWithSpvPtrcast(Param, normalizeType(ElemTy), CI,
3518 Ptrcasts);
3519 } else if (isa<Instruction>(Param)) {
3520 GR->addDeducedElementType(Param, normalizeType(ElemTy));
3521 // insertAssignTypeIntrs() will complete buildAssignPtr()
3522 } else {
3523 B.SetInsertPoint(CI->getParent()
3524 ->getParent()
3525 ->getEntryBlock()
3526 .getFirstNonPHIOrDbgOrAlloca());
3527 GR->buildAssignPtr(B, ElemTy, Param);
3528 }
3529 CallInst *Ref = dyn_cast<CallInst>(Param);
3530 if (!Ref)
3531 continue;
3532 Function *RefF = Ref->getCalledFunction();
3533 if (!RefF || !isPointerTy(RefF->getReturnType()) ||
3534 GR->findDeducedElementType(RefF))
3535 continue;
3536 ElemTy = normalizeType(ElemTy);
3537 GR->addDeducedElementType(RefF, ElemTy);
3538 GR->addReturnType(
3540 ElemTy, getPointerAddressSpace(RefF->getReturnType())));
3541 }
3542 }
3543 }
3544}
3545
3546GetElementPtrInst *SPIRVEmitIntrinsicsImpl::simplifyZeroLengthArrayGepInst(
3547 GetElementPtrInst *GEP) {
3548 // getelementptr [0 x T], P, 0 (zero), I -> getelementptr T, P, I.
3549 // If type is 0-length array and first index is 0 (zero), drop both the
3550 // 0-length array type and the first index. This is a common pattern in
3551 // the IR, e.g. when using a zero-length array as a placeholder for a
3552 // flexible array such as unbound arrays.
3553 assert(GEP && "GEP is null");
3554 Type *SrcTy = GEP->getSourceElementType();
3555 SmallVector<Value *, 8> Indices(GEP->indices());
3556 ArrayType *ArrTy = dyn_cast<ArrayType>(SrcTy);
3557 if (ArrTy && ArrTy->getNumElements() == 0 && match(Indices[0], m_Zero())) {
3558 Indices.erase(Indices.begin());
3559 SrcTy = ArrTy->getElementType();
3560 return GetElementPtrInst::Create(SrcTy, GEP->getPointerOperand(), Indices,
3561 GEP->getNoWrapFlags(), "",
3562 GEP->getIterator());
3563 }
3564 return nullptr;
3565}
3566
3567void SPIRVEmitIntrinsicsImpl::emitUnstructuredLoopControls(Function &F,
3568 IRBuilder<> &B) {
3569 const SPIRVSubtarget *ST = TM.getSubtargetImpl(F);
3570 // Shaders use SPIRVStructurizer which emits OpLoopMerge via spv_loop_merge.
3571 if (ST->isShader())
3572 return;
3573
3574 if (ST->canUseExtension(
3575 SPIRV::Extension::SPV_INTEL_unstructured_loop_controls)) {
3576 for (BasicBlock &BB : F) {
3578 MDNode *LoopMD = Term->getMetadata(LLVMContext::MD_loop);
3579 if (!LoopMD)
3580 continue;
3581
3582 SmallVector<unsigned, 1> Ops =
3584 unsigned LC = Ops[0];
3585 if (LC == SPIRV::LoopControl::None)
3586 continue;
3587
3588 // Emit intrinsic: loop control mask + optional parameters.
3589 B.SetInsertPoint(Term);
3590 SmallVector<Value *, 4> IntrArgs;
3591 for (unsigned Op : Ops)
3592 IntrArgs.push_back(B.getInt32(Op));
3593 B.CreateIntrinsic(Intrinsic::spv_loop_control_intel, IntrArgs);
3594 }
3595 return;
3596 }
3597
3598 // For non-shader targets without the Intel extension, emit OpLoopMerge
3599 // using spv_loop_merge intrinsics, mirroring the structurizer approach.
3600 LoopInfo LI;
3601 LI.analyze(&F);
3602 if (LI.empty())
3603 return;
3604
3605 for (Loop *L : LI.getLoopsInPreorder()) {
3606 BasicBlock *Latch = L->getLoopLatch();
3607 if (!Latch)
3608 continue;
3609 BasicBlock *MergeBlock = L->getUniqueExitBlock();
3610 if (!MergeBlock)
3611 continue;
3612
3613 // Check for loop unroll metadata on the latch terminator.
3614 SmallVector<unsigned, 1> LoopControlOps =
3616 if (LoopControlOps[0] == SPIRV::LoopControl::None)
3617 continue;
3618
3619 BasicBlock *Header = L->getHeader();
3620 B.SetInsertPoint(Header->getTerminator());
3621 auto *MergeAddress = BlockAddress::get(&F, MergeBlock);
3622 auto *ContinueAddress = BlockAddress::get(&F, Latch);
3623 SmallVector<Value *, 4> Args = {MergeAddress, ContinueAddress};
3624 for (unsigned Imm : LoopControlOps)
3625 Args.emplace_back(B.getInt32(Imm));
3626 B.CreateIntrinsic(Intrinsic::spv_loop_merge, {Args});
3627 }
3628}
3629
3630bool SPIRVEmitIntrinsicsImpl::runOnFunction(Function &Func) {
3631 if (Func.isDeclaration())
3632 return false;
3633
3634 const SPIRVSubtarget &ST = TM.getSubtarget<SPIRVSubtarget>(Func);
3635 GR = ST.getSPIRVGlobalRegistry();
3636
3637 if (!CurrF)
3638 HaveFunPtrs =
3639 ST.canUseExtension(SPIRV::Extension::SPV_INTEL_function_pointers);
3640
3641 CurrF = &Func;
3642 IRBuilder<> B(Func.getContext());
3643 AggrConsts.clear();
3644 AggrConstTypes.clear();
3645 AggrStores.clear();
3646
3647 processParamTypesByFunHeader(CurrF, B);
3648
3649 // Fix GEP result types ahead of inference, and simplify if possible.
3650 // Data structure for dead instructions that were simplified and replaced.
3651 SmallPtrSet<Instruction *, 4> DeadInsts;
3652 for (auto &I : instructions(Func)) {
3654 auto *SGEP = dyn_cast<StructuredGEPInst>(&I);
3655
3656 if ((!GEP && !SGEP) || GR->findDeducedElementType(&I))
3657 continue;
3658
3659 if (SGEP) {
3660 GR->addDeducedElementType(SGEP,
3661 normalizeType(SGEP->getResultElementType()));
3662 continue;
3663 }
3664
3665 GetElementPtrInst *NewGEP = simplifyZeroLengthArrayGepInst(GEP);
3666 if (NewGEP) {
3667 GEP->replaceAllUsesWith(NewGEP);
3668 DeadInsts.insert(GEP);
3669 GEP = NewGEP;
3670 }
3671 if (Type *GepTy = getGEPType(GEP))
3672 GR->addDeducedElementType(GEP, normalizeType(GepTy));
3673 }
3674 // Remove dead instructions that were simplified and replaced.
3675 for (auto *I : DeadInsts) {
3676 assert(I->use_empty() && "Dead instruction should not have any uses left");
3677 I->eraseFromParent();
3678 }
3679
3680 // StoreInst's operand type can be changed during the next
3681 // transformations, so we need to store it in the set. Also store already
3682 // transformed types.
3683 for (auto &I : instructions(Func)) {
3684 StoreInst *SI = dyn_cast<StoreInst>(&I);
3685 if (!SI)
3686 continue;
3687 Type *ElTy = SI->getValueOperand()->getType();
3688 if (ElTy->isAggregateType() || ElTy->isVectorTy())
3689 AggrStores.insert(&I);
3690 }
3691
3692 B.SetInsertPoint(&Func.getEntryBlock(), Func.getEntryBlock().begin());
3693 for (auto &GV : Func.getParent()->globals())
3694 processGlobalValue(GV, B);
3695
3696 reconstructAggregateReturns(Func, B);
3697 preprocessUndefsAndPoisons(B);
3698 simplifyNullAddrSpaceCasts();
3699 preprocessCompositeConstants(B);
3700
3701 // A PHINode, SelectInst or FreezeInst takes its result type from its
3702 // operands. Aggregate arms are lowered to i32 value-ids (composite constants
3703 // here, loads and other producers during the visitor pass below), so mutate
3704 // an aggregate PHI, select or freeze to match. The original type is tracked
3705 // in AggrConstTypes (used to assign the SPIR-V type) and its extractvalue
3706 // users are lowered to spv_extractv.
3707 Type *I32Ty = B.getInt32Ty();
3708 for (Instruction &I : instructions(Func)) {
3710 continue;
3711 // Give multi-register arms a value-id first, before the result is mutated.
3712 insertCompositeAggregateArms(&I, B);
3713 AggrConstTypes[&I] = I.getType();
3714 I.mutateType(I32Ty);
3715 }
3716
3717 preprocessBoolVectorBitcasts(Func);
3718 SmallVector<Instruction *> Worklist(
3720
3721 applyDemangledPtrArgTypes(B);
3722
3723 // Pass forward: use operand to deduce instructions result.
3724 for (auto &I : Worklist) {
3725 // Don't emit intrinsincs for convergence intrinsics.
3726 if (isConvergenceIntrinsic(I))
3727 continue;
3728
3729 bool Postpone = insertAssignPtrTypeIntrs(I, B, false);
3730 // if Postpone is true, we can't decide on pointee type yet
3731 insertAssignTypeIntrs(I, B);
3732 insertPtrCastOrAssignTypeInstr(I, B);
3734 // if instruction requires a pointee type set, let's check if we know it
3735 // already, and force it to be i8 if not
3736 if (Postpone && !GR->findAssignPtrTypeInstr(I))
3737 insertAssignPtrTypeIntrs(I, B, true);
3738
3739 if (auto *FPI = dyn_cast<ConstrainedFPIntrinsic>(I))
3740 useRoundingMode(FPI, B);
3741 }
3742
3743 // Pass backward: use instructions results to specify/update/cast operands
3744 // where needed.
3745 SmallPtrSet<Instruction *, 4> IncompleteRets;
3746 for (auto &I : llvm::reverse(instructions(Func)))
3747 deduceOperandElementType(&I, &IncompleteRets);
3748
3749 // Pass forward for PHIs only, their operands are not preceed the
3750 // instruction in meaning of `instructions(Func)`.
3751 for (BasicBlock &BB : Func)
3752 for (PHINode &Phi : BB.phis())
3753 if (isPointerTy(Phi.getType()))
3754 deduceOperandElementType(&Phi, nullptr);
3755
3756 for (auto *I : Worklist) {
3757 TrackConstants = true;
3758 if (!I->getType()->isVoidTy() || isa<StoreInst>(I))
3760 // Visitors return either the original/newly created instruction for
3761 // further processing, nullptr otherwise.
3762 I = visit(*I);
3763 if (!I)
3764 continue;
3765
3766 // Don't emit intrinsics for convergence operations.
3767 if (isConvergenceIntrinsic(I))
3768 continue;
3769
3771 processInstrAfterVisit(I, B);
3772 }
3773
3774 emitUnstructuredLoopControls(Func, B);
3775
3776 return true;
3777}
3778
3779// Try to deduce a better type for pointers to untyped ptr.
3780bool SPIRVEmitIntrinsicsImpl::postprocessTypes(Module &M) {
3781 if (!GR || TodoTypeSz == 0)
3782 return false;
3783
3784 unsigned SzTodo = TodoTypeSz;
3785 DenseMap<Value *, SmallPtrSet<Value *, 4>> ToProcess;
3786 for (auto [Op, Enabled] : TodoType) {
3787 // TODO: add isa<CallInst>(Op) to continue
3788 if (!Enabled || isaGEP(Op))
3789 continue;
3790 CallInst *AssignCI = GR->findAssignPtrTypeInstr(Op);
3791 Type *KnownTy = GR->findDeducedElementType(Op);
3792 if (!KnownTy || !AssignCI)
3793 continue;
3794 assert(Op == AssignCI->getArgOperand(0));
3795 // Try to improve the type deduced after all Functions are processed.
3796 if (auto *CI = dyn_cast<Instruction>(Op)) {
3797 CurrF = CI->getParent()->getParent();
3798 SmallPtrSet<Value *, 0> Visited;
3799 if (Type *ElemTy = deduceElementTypeHelper(Op, Visited, false, true)) {
3800 if (ElemTy != KnownTy) {
3801 DenseSet<std::pair<Value *, Value *>> VisitedSubst;
3802 propagateElemType(CI, ElemTy, VisitedSubst);
3803 eraseTodoType(Op);
3804 continue;
3805 }
3806 }
3807 }
3808
3809 if (Op->hasUseList()) {
3810 for (User *U : Op->users()) {
3812 if (Inst && !isa<IntrinsicInst>(Inst))
3813 ToProcess[Inst].insert(Op);
3814 }
3815 }
3816 }
3817 if (TodoTypeSz == 0)
3818 return true;
3819
3820 for (auto &F : M) {
3821 CurrF = &F;
3822 SmallPtrSet<Instruction *, 4> IncompleteRets;
3823 for (auto &I : llvm::reverse(instructions(F))) {
3824 auto It = ToProcess.find(&I);
3825 if (It == ToProcess.end())
3826 continue;
3827 It->second.remove_if([this](Value *V) { return !isTodoType(V); });
3828 if (It->second.size() == 0)
3829 continue;
3830 deduceOperandElementType(&I, &IncompleteRets, &It->second, true);
3831 if (TodoTypeSz == 0)
3832 return true;
3833 }
3834 }
3835
3836 return SzTodo > TodoTypeSz;
3837}
3838
3839// Parse and store argument types of function declarations where needed.
3840void SPIRVEmitIntrinsicsImpl::parseFunDeclarations(Module &M) {
3841 for (auto &F : M) {
3842 if (!F.isDeclaration() || F.isIntrinsic())
3843 continue;
3844 // get the demangled name
3845 std::string DemangledName = getOclOrSpirvBuiltinDemangledName(F.getName());
3846 if (DemangledName.empty())
3847 continue;
3848 // allow only OpGroupAsyncCopy use case at the moment
3849 const SPIRVSubtarget &ST = TM.getSubtarget<SPIRVSubtarget>(F);
3850 auto [Grp, Opcode, ExtNo] = SPIRV::mapBuiltinToOpcode(
3851 DemangledName, ST.getPreferredInstructionSet());
3852 if (Opcode != SPIRV::OpGroupAsyncCopy)
3853 continue;
3854 // find pointer arguments
3855 SmallVector<unsigned> Idxs;
3856 for (unsigned OpIdx = 0; OpIdx < F.arg_size(); ++OpIdx) {
3857 Argument *Arg = F.getArg(OpIdx);
3858 if (isPointerTy(Arg->getType()) && !hasPointeeTypeAttr(Arg))
3859 Idxs.push_back(OpIdx);
3860 }
3861 if (!Idxs.size())
3862 continue;
3863 // parse function arguments
3864 LLVMContext &Ctx = F.getContext();
3866 SPIRV::parseBuiltinTypeStr(TypeStrs, DemangledName, Ctx);
3867 if (!TypeStrs.size())
3868 continue;
3869 // find type info for pointer arguments
3870 for (unsigned Idx : Idxs) {
3871 if (Idx >= TypeStrs.size())
3872 continue;
3873 if (Type *ElemTy =
3874 SPIRV::parseBuiltinCallArgumentType(TypeStrs[Idx].trim(), Ctx))
3876 !ElemTy->isTargetExtTy())
3877 FDeclPtrTys[&F].push_back(std::make_pair(Idx, ElemTy));
3878 }
3879 }
3880}
3881
3882bool SPIRVEmitIntrinsicsImpl::processMaskedMemIntrinsic(IntrinsicInst &I) {
3883 const SPIRVSubtarget &ST = TM.getSubtarget<SPIRVSubtarget>(*I.getFunction());
3884
3885 if (I.getIntrinsicID() == Intrinsic::masked_gather) {
3886 if (!ST.canUseExtension(
3887 SPIRV::Extension::SPV_INTEL_masked_gather_scatter)) {
3888 I.getContext().emitError(
3889 &I, "llvm.masked.gather requires SPV_INTEL_masked_gather_scatter "
3890 "extension");
3891 // Replace with poison to allow compilation to continue and report error.
3892 I.replaceAllUsesWith(PoisonValue::get(I.getType()));
3893 I.eraseFromParent();
3894 return true;
3895 }
3896
3897 IRBuilder<> B(&I);
3898
3899 Value *Ptrs = I.getArgOperand(0);
3900 Value *Mask = I.getArgOperand(1);
3901 Value *Passthru = I.getArgOperand(2);
3902
3903 // Alignment is stored as a parameter attribute, not as a regular parameter.
3904 uint32_t Alignment = I.getParamAlign(0).valueOrOne().value();
3905
3906 SmallVector<Value *, 4> Args = {Ptrs, B.getInt32(Alignment), Mask,
3907 Passthru};
3908 SmallVector<Type *, 4> Types = {I.getType(), Ptrs->getType(),
3909 Mask->getType(), Passthru->getType()};
3910
3911 auto *NewI = B.CreateIntrinsic(Intrinsic::spv_masked_gather, Types, Args);
3912 I.replaceAllUsesWith(NewI);
3913 I.eraseFromParent();
3914 return true;
3915 }
3916
3917 if (I.getIntrinsicID() == Intrinsic::masked_scatter) {
3918 if (!ST.canUseExtension(
3919 SPIRV::Extension::SPV_INTEL_masked_gather_scatter)) {
3920 I.getContext().emitError(
3921 &I, "llvm.masked.scatter requires SPV_INTEL_masked_gather_scatter "
3922 "extension");
3923 // Erase the intrinsic to allow compilation to continue and report error.
3924 I.eraseFromParent();
3925 return true;
3926 }
3927
3928 IRBuilder<> B(&I);
3929
3930 Value *Values = I.getArgOperand(0);
3931 Value *Ptrs = I.getArgOperand(1);
3932 Value *Mask = I.getArgOperand(2);
3933
3934 // Alignment is stored as a parameter attribute on the ptrs parameter (arg
3935 // 1).
3936 uint32_t Alignment = I.getParamAlign(1).valueOrOne().value();
3937
3938 SmallVector<Value *, 4> Args = {Values, Ptrs, B.getInt32(Alignment), Mask};
3939 SmallVector<Type *, 3> Types = {Values->getType(), Ptrs->getType(),
3940 Mask->getType()};
3941
3942 B.CreateIntrinsic(Intrinsic::spv_masked_scatter, Types, Args);
3943 I.eraseFromParent();
3944 return true;
3945 }
3946
3947 return false;
3948}
3949
3950// SPIR-V doesn't support bitcasts involving vector boolean type. Decompose such
3951// bitcasts into element-wise operations before building instructions
3952// worklist, so new instructions are properly visited and converted to
3953// SPIR-V intrinsics.
3954void SPIRVEmitIntrinsicsImpl::preprocessBoolVectorBitcasts(Function &F) {
3955 struct BoolVecBitcast {
3956 BitCastInst *BC;
3957 FixedVectorType *BoolVecTy;
3958 bool SrcIsBoolVec;
3959 };
3960
3961 auto getAsBoolVec = [](Type *Ty) -> FixedVectorType * {
3962 auto *VTy = dyn_cast<FixedVectorType>(Ty);
3963 return (VTy && VTy->getElementType()->isIntegerTy(1)) ? VTy : nullptr;
3964 };
3965
3967 for (auto &I : instructions(F)) {
3968 auto *BC = dyn_cast<BitCastInst>(&I);
3969 if (!BC)
3970 continue;
3971 if (auto *BVTy = getAsBoolVec(BC->getSrcTy()))
3972 ToReplace.push_back({BC, BVTy, true});
3973 else if (auto *BVTy = getAsBoolVec(BC->getDestTy()))
3974 ToReplace.push_back({BC, BVTy, false});
3975 }
3976
3977 for (auto &[BC, BoolVecTy, SrcIsBoolVec] : ToReplace) {
3978 IRBuilder<> B(BC);
3979 Value *Src = BC->getOperand(0);
3980 unsigned BoolVecN = BoolVecTy->getNumElements();
3981 // Use iN as the scalar intermediate type for the bool vector side.
3982 Type *IntTy = B.getIntNTy(BoolVecN);
3983
3984 // Convert source to scalar integer.
3985 Value *IntVal;
3986 if (SrcIsBoolVec) {
3987 // Extract each bool, zext, shift, and OR.
3988 IntVal = ConstantInt::get(IntTy, 0);
3989 for (unsigned I = 0; I < BoolVecN; ++I) {
3990 Value *Elem = B.CreateExtractElement(Src, B.getInt32(I));
3991 Value *Ext = B.CreateZExt(Elem, IntTy);
3992 if (I > 0)
3993 Ext = B.CreateShl(Ext, ConstantInt::get(IntTy, I));
3994 IntVal = B.CreateOr(IntVal, Ext);
3995 }
3996 } else {
3997 // Source is a non-bool type. If it's already a scalar integer, use it
3998 // directly, otherwise bitcast to iN first.
3999 IntVal = Src;
4000 if (!Src->getType()->isIntegerTy())
4001 IntVal = B.CreateBitCast(Src, IntTy);
4002 }
4003
4004 // Convert scalar integer to destination type.
4005 Value *Result;
4006 if (!SrcIsBoolVec) {
4007 // Test each bit with AND + icmp.
4008 Result = PoisonValue::get(BoolVecTy);
4009 for (unsigned I = 0; I < BoolVecN; ++I) {
4010 Value *Mask = ConstantInt::get(IntTy, APInt::getOneBitSet(BoolVecN, I));
4011 Value *And = B.CreateAnd(IntVal, Mask);
4012 Value *Cmp = B.CreateICmpNE(And, ConstantInt::get(IntTy, 0));
4013 Result = B.CreateInsertElement(Result, Cmp, B.getInt32(I));
4014 }
4015 } else {
4016 // Destination is a non-bool type. If it's a scalar integer, use IntVal
4017 // directly, otherwise bitcast from iN.
4018 Result = IntVal;
4019 if (!BC->getDestTy()->isIntegerTy())
4020 Result = B.CreateBitCast(IntVal, BC->getDestTy());
4021 }
4022
4023 BC->replaceAllUsesWith(Result);
4024 BC->eraseFromParent();
4025 }
4026}
4027
4028bool SPIRVEmitIntrinsicsImpl::convertMaskedMemIntrinsics(Module &M) {
4029 bool Changed = false;
4030
4031 for (Function &F : make_early_inc_range(M)) {
4032 if (!F.isIntrinsic())
4033 continue;
4034 Intrinsic::ID IID = F.getIntrinsicID();
4035 if (IID != Intrinsic::masked_gather && IID != Intrinsic::masked_scatter)
4036 continue;
4037
4038 for (User *U : make_early_inc_range(F.users())) {
4039 if (auto *II = dyn_cast<IntrinsicInst>(U))
4040 Changed |= processMaskedMemIntrinsic(*II);
4041 }
4042
4043 if (F.use_empty())
4044 F.eraseFromParent();
4045 }
4046
4047 return Changed;
4048}
4049
4050bool SPIRVEmitIntrinsicsImpl::runOnModule(Module &M) {
4051 bool Changed = false;
4052
4053 Changed |= convertMaskedMemIntrinsics(M);
4054
4055 parseFunDeclarations(M);
4056 insertConstantsForFPFastMathDefault(M);
4057 GVUsers.init(M);
4058
4059 TodoType.clear();
4060 for (auto &F : M)
4062
4063 // Specify function parameters after all functions were processed.
4064 for (auto &F : M) {
4065 // check if function parameter types are set
4066 CurrF = &F;
4067 if (!F.isDeclaration() && !F.isIntrinsic()) {
4068 IRBuilder<> B(F.getContext());
4069 processParamTypes(&F, B);
4070 }
4071 }
4072
4073 CanTodoType = false;
4074 Changed |= postprocessTypes(M);
4075
4076 if (HaveFunPtrs)
4077 Changed |= processFunctionPointers(M);
4078
4079 return Changed;
4080}
4081
4082PreservedAnalyses
4084 if (SPIRVEmitIntrinsicsImpl(TM).runOnModule(M))
4085 return PreservedAnalyses::none();
4086 return PreservedAnalyses::all();
4087}
4088
4090 return new SPIRVEmitIntrinsicsLegacy(TM);
4091}
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
MachineInstr unsigned OpIdx
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:530
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:830
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:878
Type * getReturnType() const
Returns the type of the ret val.
Definition Function.h:216
Argument * getArg(unsigned i) const
Definition Function.h:863
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 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:63
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:419
RelativeUniformCounterPtr Values
Definition InstrProf.h:91
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:390
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:383
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:563
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:529
std::string getOclOrSpirvBuiltinDemangledName(StringRef Name)
SmallVector< unsigned, 1 > getSpirvLoopControlOperandsFromLoopMetadata(MDNode *LoopMD)
auto reverse(ContainerTy &&C)
Definition STLExtras.h:407
Type * getTypedPointerWrapper(Type *ElemTy, unsigned AS)
Definition SPIRVUtils.h:414
bool isVector1(Type *Ty)
Definition SPIRVUtils.h:507
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:378
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)
SPIRV::Scope::Scope getMemScope(LLVMContext &Ctx, SyncScope::ID Id)
@ 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:403
bool hasPointeeTypeAttr(Argument *Arg)
Definition SPIRVUtils.h:398
constexpr unsigned BitWidth
bool isEquivalentTypes(Type *Ty1, Type *Ty2)
Definition SPIRVUtils.h:469
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:359
Type * normalizeType(Type *Ty)
Definition SPIRVUtils.h:515
bool isPointerTyOrWrapper(const Type *Ty)
Definition SPIRVUtils.h:426
@ 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:525
bool isUntypedPointerTy(const Type *T)
Definition SPIRVUtils.h:373
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:153