LLVM 24.0.0git
DXILIntrinsicExpansion.cpp
Go to the documentation of this file.
1//===- DXILIntrinsicExpansion.cpp - Prepare LLVM Module for DXIL encoding--===//
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/// \file This file contains DXIL intrinsic expansions for those that don't have
10// opcodes in DirectX Intermediate Language (DXIL).
11//===----------------------------------------------------------------------===//
12
14#include "DirectX.h"
15#include "llvm/ADT/APInt.h"
16#include "llvm/ADT/STLExtras.h"
18#include "llvm/CodeGen/Passes.h"
19#include "llvm/IR/Constants.h"
20#include "llvm/IR/IRBuilder.h"
21#include "llvm/IR/InstrTypes.h"
22#include "llvm/IR/Instruction.h"
24#include "llvm/IR/Intrinsics.h"
25#include "llvm/IR/IntrinsicsDirectX.h"
27#include "llvm/IR/Module.h"
28#include "llvm/IR/PassManager.h"
29#include "llvm/IR/Type.h"
30#include "llvm/Pass.h"
34
35#define DEBUG_TYPE "dxil-intrinsic-expansion"
36
37using namespace llvm;
38
40
41public:
42 bool runOnModule(Module &M) override;
44
45 static char ID; // Pass identification.
46};
47
48static bool resourceAccessNeeds64BitExpansion(Module *M, Type *OverloadTy,
49 bool IsRaw) {
50 if (IsRaw && M->getTargetTriple().getDXILVersion() > VersionTuple(1, 2))
51 return false;
52
53 Type *ScalarTy = OverloadTy->getScalarType();
54 return ScalarTy->isDoubleTy() || ScalarTy->isIntegerTy(64);
55}
56
58 Module *M = Orig->getModule();
59 if (M->getTargetTriple().getDXILVersion() >= VersionTuple(1, 9))
60 return nullptr;
61
62 Value *Val = Orig->getOperand(0);
63 Type *ValTy = Val->getType();
64 if (!ValTy->getScalarType()->isHalfTy())
65 return nullptr;
66
67 IRBuilder<> Builder(Orig);
68 Type *IType = Type::getInt16Ty(M->getContext());
69 Constant *PosInf =
70 ValTy->isVectorTy()
73 cast<FixedVectorType>(ValTy)->getNumElements()),
74 ConstantInt::get(IType, 0x7c00))
75 : ConstantInt::get(IType, 0x7c00);
76
77 Constant *NegInf =
78 ValTy->isVectorTy()
81 cast<FixedVectorType>(ValTy)->getNumElements()),
82 ConstantInt::get(IType, 0xfc00))
83 : ConstantInt::get(IType, 0xfc00);
84
85 Value *IVal = Builder.CreateBitCast(Val, PosInf->getType());
86 Value *B1 = Builder.CreateICmpEQ(IVal, PosInf);
87 Value *B2 = Builder.CreateICmpEQ(IVal, NegInf);
88 Value *B3 = Builder.CreateOr(B1, B2);
89 return B3;
90}
91
93 Module *M = Orig->getModule();
94 if (M->getTargetTriple().getDXILVersion() >= VersionTuple(1, 9))
95 return nullptr;
96
97 Value *Val = Orig->getOperand(0);
98 Type *ValTy = Val->getType();
99 if (!ValTy->getScalarType()->isHalfTy())
100 return nullptr;
101
102 IRBuilder<> Builder(Orig);
103 Type *IType = Type::getInt16Ty(M->getContext());
104
105 Constant *ExpBitMask =
106 ValTy->isVectorTy()
109 cast<FixedVectorType>(ValTy)->getNumElements()),
110 ConstantInt::get(IType, 0x7c00))
111 : ConstantInt::get(IType, 0x7c00);
112 Constant *SigBitMask =
113 ValTy->isVectorTy()
116 cast<FixedVectorType>(ValTy)->getNumElements()),
117 ConstantInt::get(IType, 0x3ff))
118 : ConstantInt::get(IType, 0x3ff);
119
120 Constant *Zero =
121 ValTy->isVectorTy()
124 cast<FixedVectorType>(ValTy)->getNumElements()),
125 ConstantInt::get(IType, 0))
126 : ConstantInt::get(IType, 0);
127
128 Value *IVal = Builder.CreateBitCast(Val, ExpBitMask->getType());
129 Value *Exp = Builder.CreateAnd(IVal, ExpBitMask);
130 Value *B1 = Builder.CreateICmpEQ(Exp, ExpBitMask);
131
132 Value *Sig = Builder.CreateAnd(IVal, SigBitMask);
133 Value *B2 = Builder.CreateICmpNE(Sig, Zero);
134 Value *B3 = Builder.CreateAnd(B1, B2);
135 return B3;
136}
137
139 Module *M = Orig->getModule();
140 if (M->getTargetTriple().getDXILVersion() >= VersionTuple(1, 9))
141 return nullptr;
142
143 Value *Val = Orig->getOperand(0);
144 Type *ValTy = Val->getType();
145 if (!ValTy->getScalarType()->isHalfTy())
146 return nullptr;
147
148 IRBuilder<> Builder(Orig);
149 Type *IType = Type::getInt16Ty(M->getContext());
150
151 Constant *ExpBitMask =
152 ValTy->isVectorTy()
155 cast<FixedVectorType>(ValTy)->getNumElements()),
156 ConstantInt::get(IType, 0x7c00))
157 : ConstantInt::get(IType, 0x7c00);
158
159 Value *IVal = Builder.CreateBitCast(Val, ExpBitMask->getType());
160 Value *Exp = Builder.CreateAnd(IVal, ExpBitMask);
161 Value *B1 = Builder.CreateICmpNE(Exp, ExpBitMask);
162 return B1;
163}
164
166 Module *M = Orig->getModule();
167 if (M->getTargetTriple().getDXILVersion() >= VersionTuple(1, 9))
168 return nullptr;
169
170 Value *Val = Orig->getOperand(0);
171 Type *ValTy = Val->getType();
172 if (!ValTy->getScalarType()->isHalfTy())
173 return nullptr;
174
175 IRBuilder<> Builder(Orig);
176 Type *IType = Type::getInt16Ty(M->getContext());
177
178 Constant *ExpBitMask =
179 ValTy->isVectorTy()
182 cast<FixedVectorType>(ValTy)->getNumElements()),
183 ConstantInt::get(IType, 0x7c00))
184 : ConstantInt::get(IType, 0x7c00);
185 Constant *Zero =
186 ValTy->isVectorTy()
189 cast<FixedVectorType>(ValTy)->getNumElements()),
190 ConstantInt::get(IType, 0))
191 : ConstantInt::get(IType, 0);
192
193 Value *IVal = Builder.CreateBitCast(Val, ExpBitMask->getType());
194 Value *Exp = Builder.CreateAnd(IVal, ExpBitMask);
195 Value *NotAllZeroes = Builder.CreateICmpNE(Exp, Zero);
196 Value *NotAllOnes = Builder.CreateICmpNE(Exp, ExpBitMask);
197 Value *B1 = Builder.CreateAnd(NotAllZeroes, NotAllOnes);
198 return B1;
199}
200
202 switch (F.getIntrinsicID()) {
203 case Intrinsic::assume:
204 case Intrinsic::abs:
205 case Intrinsic::atan2:
206 case Intrinsic::fshl:
207 case Intrinsic::fshr:
208 case Intrinsic::exp:
209 case Intrinsic::is_fpclass:
210 case Intrinsic::log:
211 case Intrinsic::log10:
212 case Intrinsic::pow:
213 case Intrinsic::powi:
214 case Intrinsic::dx_all:
215 case Intrinsic::dx_any:
216 case Intrinsic::dx_uclamp:
217 case Intrinsic::dx_sclamp:
218 case Intrinsic::dx_nclamp:
219 case Intrinsic::dx_degrees:
220 case Intrinsic::dx_isinf:
221 case Intrinsic::dx_isnan:
222 case Intrinsic::dx_lerp:
223 case Intrinsic::dx_normalize:
224 case Intrinsic::dx_fdot:
225 case Intrinsic::dx_sdot:
226 case Intrinsic::dx_udot:
227 case Intrinsic::dx_sign:
228 case Intrinsic::dx_radians:
229 case Intrinsic::usub_sat:
230 case Intrinsic::vector_reduce_add:
231 case Intrinsic::vector_reduce_fadd:
232 case Intrinsic::matrix_multiply:
233 case Intrinsic::matrix_transpose:
234 case Intrinsic::umul_with_overflow:
235 case Intrinsic::smul_with_overflow:
236 case Intrinsic::dx_load_input:
237 case Intrinsic::dx_store_output:
238 return true;
239 case Intrinsic::dx_resource_load_rawbuffer:
241 F.getParent(), F.getReturnType()->getStructElementType(0),
242 /*IsRaw*/ true);
243 case Intrinsic::dx_resource_load_typedbuffer:
245 F.getParent(), F.getReturnType()->getStructElementType(0),
246 /*IsRaw*/ false);
247 case Intrinsic::dx_resource_store_rawbuffer:
249 F.getParent(), F.getFunctionType()->getParamType(3), /*IsRaw*/ true);
250 case Intrinsic::dx_resource_store_typedbuffer:
252 F.getParent(), F.getFunctionType()->getParamType(2), /*IsRaw*/ false);
253 }
254 return false;
255}
256
258 Value *A = Orig->getArgOperand(0);
259 Value *B = Orig->getArgOperand(1);
260 Type *Ty = A->getType();
261
262 IRBuilder<> Builder(Orig);
263
264 Value *Cmp = Builder.CreateICmpULT(A, B, "usub.cmp");
265 Value *Sub = Builder.CreateSub(A, B, "usub.sub");
266 Value *Zero = ConstantInt::get(Ty, 0);
267 return Builder.CreateSelect(Cmp, Zero, Sub, "usub.sat");
268}
269
270// Compute the high N bits of the 2N-bit unsigned product of two N-bit values
271// using only N-bit arithmetic, so we don't introduce a wider integer type that
272// may be unsupported in DXIL.
274 Type *Ty, unsigned BW) {
275 assert(BW % 2 == 0 && "high-half split needs symmetric halves");
276 unsigned Half = BW / 2;
277 Value *HalfShift = ConstantInt::get(Ty, Half);
278 Value *LoMask = ConstantInt::get(Ty, APInt::getLowBitsSet(BW, Half));
279
280 Value *U0 = Builder.CreateAnd(A, LoMask);
281 Value *U1 = Builder.CreateLShr(A, HalfShift);
282 Value *V0 = Builder.CreateAnd(B, LoMask);
283 Value *V1 = Builder.CreateLShr(B, HalfShift);
284
285 Value *W0 = Builder.CreateMul(U0, V0);
286 Value *T = Builder.CreateAdd(Builder.CreateMul(U1, V0),
287 Builder.CreateLShr(W0, HalfShift));
288 Value *W1 = Builder.CreateAnd(T, LoMask);
289 Value *W2 = Builder.CreateLShr(T, HalfShift);
290 W1 = Builder.CreateAdd(Builder.CreateMul(U0, V1), W1);
291 return Builder.CreateAdd(Builder.CreateAdd(Builder.CreateMul(U1, V1), W2),
292 Builder.CreateLShr(W1, HalfShift));
293}
294
295// Expand a {u,s}mul.with.overflow intrinsic. The low half of the result is a
296// plain multiply; overflow is derived from the high half of the double-width
297// product.
299 IRBuilder<> Builder(Orig);
300 Value *A = Orig->getArgOperand(0);
301 Value *B = Orig->getArgOperand(1);
302 Type *Ty = A->getType();
303 unsigned BW = Ty->getScalarSizeInBits();
304
305 Value *Lo;
306 Value *Ov;
307
308 // A plain double-width multiply is simplest, but we avoid it once it would
309 // introduce a 64-bit (or wider) integer, which DXIL does not always support.
310 // For i32 we use the native DXIL IMul/UMul ops, which return the full product
311 // as two i32s; wider types fall back to a same-width high-half computation.
312 if (2 * BW <= 32) {
313 Lo = Builder.CreateMul(A, B);
314 Type *WideTy = Ty->getWithNewBitWidth(2 * BW);
315 Value *WideA =
316 Signed ? Builder.CreateSExt(A, WideTy) : Builder.CreateZExt(A, WideTy);
317 Value *WideB =
318 Signed ? Builder.CreateSExt(B, WideTy) : Builder.CreateZExt(B, WideTy);
319 Value *Wide = Builder.CreateMul(WideA, WideB);
320 if (Signed) {
321 // Overflow when the full product doesn't fit back into BW signed bits.
322 Ov = Builder.CreateICmpNE(Wide, Builder.CreateSExt(Lo, WideTy));
323 } else {
324 Value *Hi = Builder.CreateLShr(Wide, ConstantInt::get(WideTy, BW));
325 Ov = Builder.CreateICmpNE(Hi, ConstantInt::get(WideTy, 0));
326 }
327 } else if (BW == 32) {
328 // IMul/UMul return {high, low}; index 0 is the high 32 bits.
329 Type *ResTy = StructType::get(Ty, Ty);
330 Intrinsic::ID IntrinsicID =
331 Signed ? Intrinsic::dx_imul : Intrinsic::dx_umul;
332 Value *Mul = Builder.CreateIntrinsic(ResTy, IntrinsicID, {A, B});
333 Value *Hi = Builder.CreateExtractValue(Mul, 0);
334 Lo = Builder.CreateExtractValue(Mul, 1);
335 if (Signed)
336 Ov = Builder.CreateICmpNE(
337 Hi, Builder.CreateAShr(Lo, ConstantInt::get(Ty, BW - 1)));
338 else
339 Ov = Builder.CreateICmpNE(Hi, ConstantInt::get(Ty, 0));
340 } else {
341 Lo = Builder.CreateMul(A, B);
342 Value *Hi = createMulHighUnsigned(Builder, A, B, Ty, BW);
343 if (Signed) {
344 // Turn the unsigned high half into the signed one, then overflow means it
345 // isn't the sign extension of the low half.
346 Value *SignShift = ConstantInt::get(Ty, BW - 1);
347 Value *ASign = Builder.CreateAShr(A, SignShift);
348 Value *BSign = Builder.CreateAShr(B, SignShift);
349 Hi = Builder.CreateSub(Hi, Builder.CreateAnd(ASign, B));
350 Hi = Builder.CreateSub(Hi, Builder.CreateAnd(BSign, A));
351 Ov = Builder.CreateICmpNE(Hi, Builder.CreateAShr(Lo, SignShift));
352 } else {
353 Ov = Builder.CreateICmpNE(Hi, ConstantInt::get(Ty, 0));
354 }
355 }
356
357 Value *Agg = PoisonValue::get(Orig->getType());
358 Agg = Builder.CreateInsertValue(Agg, Lo, 0);
359 return Builder.CreateInsertValue(Agg, Ov, 1);
360}
361
362static Value *expandVecReduceAdd(CallInst *Orig, Intrinsic::ID IntrinsicId) {
363 assert(IntrinsicId == Intrinsic::vector_reduce_add ||
364 IntrinsicId == Intrinsic::vector_reduce_fadd);
365
366 IRBuilder<> Builder(Orig);
367 bool IsFAdd = (IntrinsicId == Intrinsic::vector_reduce_fadd);
368
369 Value *X = Orig->getOperand(IsFAdd ? 1 : 0);
370 Type *Ty = X->getType();
371 auto *XVec = dyn_cast<FixedVectorType>(Ty);
372 unsigned XVecSize = XVec->getNumElements();
373 Value *Sum = Builder.CreateExtractElement(X, static_cast<uint64_t>(0));
374
375 // Handle the initial start value for floating-point addition.
376 if (IsFAdd) {
377 Constant *StartValue = dyn_cast<Constant>(Orig->getOperand(0));
378 if (StartValue && !StartValue->isNullValue())
379 Sum = Builder.CreateFAdd(Sum, StartValue);
380 }
381
382 // Accumulate the remaining vector elements.
383 for (unsigned I = 1; I < XVecSize; I++) {
384 Value *Elt = Builder.CreateExtractElement(X, I);
385 if (IsFAdd)
386 Sum = Builder.CreateFAdd(Sum, Elt);
387 else
388 Sum = Builder.CreateAdd(Sum, Elt);
389 }
390
391 return Sum;
392}
393
394static Value *expandAbs(CallInst *Orig) {
395 Value *X = Orig->getOperand(0);
396 IRBuilder<> Builder(Orig);
397 Type *Ty = X->getType();
398 Type *EltTy = Ty->getScalarType();
399 Constant *Zero = Ty->isVectorTy()
402 cast<FixedVectorType>(Ty)->getNumElements()),
403 ConstantInt::get(EltTy, 0))
404 : ConstantInt::get(EltTy, 0);
405 auto *V = Builder.CreateSub(Zero, X);
406 return Builder.CreateIntrinsic(Ty, Intrinsic::smax, {X, V}, nullptr,
407 "dx.max");
408}
409
410// Create appropriate DXIL float dot intrinsic for the given A and B operands
411// The appropriate opcode will be determined by the size of the operands
412// The dot product is placed in the position indicated by Orig
414 Type *ATy = A->getType();
415 [[maybe_unused]] Type *BTy = B->getType();
416 assert(ATy->isVectorTy() && BTy->isVectorTy());
417
418 IRBuilder<> Builder(Orig);
419
420 auto *AVec = dyn_cast<FixedVectorType>(ATy);
421
423
424 Intrinsic::ID DotIntrinsic = Intrinsic::dx_dot4;
425 int NumElts = AVec->getNumElements();
426 switch (NumElts) {
427 case 2:
428 DotIntrinsic = Intrinsic::dx_dot2;
429 break;
430 case 3:
431 DotIntrinsic = Intrinsic::dx_dot3;
432 break;
433 case 4:
434 DotIntrinsic = Intrinsic::dx_dot4;
435 break;
436 default:
438 "Invalid dot product input vector: length is outside 2-4");
439 return nullptr;
440 }
441
443 for (int I = 0; I < NumElts; ++I)
444 Args.push_back(Builder.CreateExtractElement(A, Builder.getInt32(I)));
445 for (int I = 0; I < NumElts; ++I)
446 Args.push_back(Builder.CreateExtractElement(B, Builder.getInt32(I)));
447 return Builder.CreateIntrinsic(ATy->getScalarType(), DotIntrinsic, Args,
448 nullptr, "dot");
449}
450
451// Create the appropriate DXIL float dot intrinsic for the operands of Orig
452// The appropriate opcode will be determined by the size of the operands
453// The dot product is placed in the position indicated by Orig
455 return expandFloatDotIntrinsic(Orig, Orig->getOperand(0),
456 Orig->getOperand(1));
457}
458
459// Expand integer dot product to multiply and add ops
461 Intrinsic::ID DotIntrinsic) {
462 assert(DotIntrinsic == Intrinsic::dx_sdot ||
463 DotIntrinsic == Intrinsic::dx_udot);
464 Value *A = Orig->getOperand(0);
465 Value *B = Orig->getOperand(1);
466 Type *ATy = A->getType();
467 [[maybe_unused]] Type *BTy = B->getType();
468 assert(ATy->isVectorTy() && BTy->isVectorTy());
469
470 IRBuilder<> Builder(Orig);
471
472 auto *AVec = dyn_cast<FixedVectorType>(ATy);
473
475
476 Value *Result;
477 Intrinsic::ID MadIntrinsic = DotIntrinsic == Intrinsic::dx_sdot
478 ? Intrinsic::dx_imad
479 : Intrinsic::dx_umad;
480 Value *Elt0 = Builder.CreateExtractElement(A, (uint64_t)0);
481 Value *Elt1 = Builder.CreateExtractElement(B, (uint64_t)0);
482 Result = Builder.CreateMul(Elt0, Elt1);
483 for (unsigned I = 1; I < AVec->getNumElements(); I++) {
484 Elt0 = Builder.CreateExtractElement(A, I);
485 Elt1 = Builder.CreateExtractElement(B, I);
486 Result = Builder.CreateIntrinsic(Result->getType(), MadIntrinsic,
487 ArrayRef<Value *>{Elt0, Elt1, Result},
488 nullptr, "dx.mad");
489 }
490 return Result;
491}
492
494 Value *X = Orig->getOperand(0);
495 IRBuilder<> Builder(Orig);
496 Type *Ty = X->getType();
497 Type *EltTy = Ty->getScalarType();
498 Constant *Log2eConst =
499 Ty->isVectorTy() ? ConstantVector::getSplat(
501 cast<FixedVectorType>(Ty)->getNumElements()),
502 ConstantFP::get(EltTy, numbers::log2ef))
503 : ConstantFP::get(EltTy, numbers::log2ef);
504 Value *NewX = Builder.CreateFMul(Log2eConst, X);
505 CallInst *Exp2Call = Builder.CreateIntrinsicWithoutFolding(
506 Ty, Intrinsic::exp2, {NewX}, nullptr, "dx.exp2");
507 Exp2Call->setTailCall(Orig->isTailCall());
508 Exp2Call->setAttributes(Orig->getAttributes());
509 return Exp2Call;
510}
511
513 Value *T = Orig->getArgOperand(1);
514 auto *TCI = dyn_cast<ConstantInt>(T);
515
516 // These FPClassTest cases have DXIL opcodes, so they will be handled in
517 // DXIL Op Lowering instead for all non f16 cases.
518 switch (TCI->getZExtValue()) {
520 return expand16BitIsInf(Orig);
522 return expand16BitIsNaN(Orig);
524 return expand16BitIsNormal(Orig);
526 return expand16BitIsFinite(Orig);
527 }
528
529 IRBuilder<> Builder(Orig);
530
531 Value *F = Orig->getArgOperand(0);
532 Type *FTy = F->getType();
533 unsigned FNumElem = 0; // 0 => F is not a vector
534
535 unsigned BitWidth; // Bit width of F or the ElemTy of F
536 Type *BitCastTy; // An IntNTy of the same bitwidth as F or ElemTy of F
537
538 if (auto *FVecTy = dyn_cast<FixedVectorType>(FTy)) {
539 Type *ElemTy = FVecTy->getElementType();
540 FNumElem = FVecTy->getNumElements();
541 BitWidth = ElemTy->getPrimitiveSizeInBits();
542 BitCastTy = FixedVectorType::get(Builder.getIntNTy(BitWidth), FNumElem);
543 } else {
545 BitCastTy = Builder.getIntNTy(BitWidth);
546 }
547
548 Value *FBitCast = Builder.CreateBitCast(F, BitCastTy);
549 switch (TCI->getZExtValue()) {
551 Value *NegZero =
552 ConstantInt::get(Builder.getIntNTy(BitWidth), 1 << (BitWidth - 1),
553 /*IsSigned=*/true);
554 Value *RetVal;
555 if (FNumElem) {
556 Value *NegZeroSplat = Builder.CreateVectorSplat(FNumElem, NegZero);
557 RetVal =
558 Builder.CreateICmpEQ(FBitCast, NegZeroSplat, "is.fpclass.negzero");
559 } else
560 RetVal = Builder.CreateICmpEQ(FBitCast, NegZero, "is.fpclass.negzero");
561 return RetVal;
562 }
563 default:
564 reportFatalUsageError("Unsupported FPClassTest");
565 }
566}
567
569 Intrinsic::ID IntrinsicId) {
570 Value *X = Orig->getOperand(0);
571 IRBuilder<> Builder(Orig);
572 Type *Ty = X->getType();
573 Type *EltTy = Ty->getScalarType();
574
575 auto ApplyOp = [&Builder](Intrinsic::ID IntrinsicId, Value *Result,
576 Value *Elt) {
577 if (IntrinsicId == Intrinsic::dx_any)
578 return Builder.CreateOr(Result, Elt);
579 assert(IntrinsicId == Intrinsic::dx_all);
580 return Builder.CreateAnd(Result, Elt);
581 };
582
583 Value *Result = nullptr;
584 if (!Ty->isVectorTy()) {
585 Result = EltTy->isFloatingPointTy()
586 ? Builder.CreateFCmpUNE(X, ConstantFP::get(EltTy, 0))
587 : Builder.CreateICmpNE(X, ConstantInt::get(EltTy, 0));
588 } else {
589 auto *XVec = dyn_cast<FixedVectorType>(Ty);
590 Value *Cond =
591 EltTy->isFloatingPointTy()
592 ? Builder.CreateFCmpUNE(
594 ElementCount::getFixed(XVec->getNumElements()),
595 ConstantFP::get(EltTy, 0)))
596 : Builder.CreateICmpNE(
598 ElementCount::getFixed(XVec->getNumElements()),
599 ConstantInt::get(EltTy, 0)));
600 Result = Builder.CreateExtractElement(Cond, (uint64_t)0);
601 for (unsigned I = 1; I < XVec->getNumElements(); I++) {
602 Value *Elt = Builder.CreateExtractElement(Cond, I);
603 Result = ApplyOp(IntrinsicId, Result, Elt);
604 }
605 }
606 return Result;
607}
608
610 Value *X = Orig->getOperand(0);
611 Value *Y = Orig->getOperand(1);
612 Value *S = Orig->getOperand(2);
613 IRBuilder<> Builder(Orig);
614 auto *V = Builder.CreateFSub(Y, X);
615 V = Builder.CreateFMul(S, V);
616 return Builder.CreateFAdd(X, V, "dx.lerp");
617}
618
620 float LogConstVal = numbers::ln2f) {
621 Value *X = Orig->getOperand(0);
622 IRBuilder<> Builder(Orig);
623 Type *Ty = X->getType();
624 Type *EltTy = Ty->getScalarType();
625 Constant *Ln2Const =
626 Ty->isVectorTy() ? ConstantVector::getSplat(
628 cast<FixedVectorType>(Ty)->getNumElements()),
629 ConstantFP::get(EltTy, LogConstVal))
630 : ConstantFP::get(EltTy, LogConstVal);
631 CallInst *Log2Call = Builder.CreateIntrinsicWithoutFolding(
632 Ty, Intrinsic::log2, {X}, nullptr, "elt.log2");
633 Log2Call->setTailCall(Orig->isTailCall());
634 Log2Call->setAttributes(Orig->getAttributes());
635 return Builder.CreateFMul(Ln2Const, Log2Call);
636}
640
641// Use dot product of vector operand with itself to calculate the length.
642// Divide the vector by that length to normalize it.
644 Value *X = Orig->getOperand(0);
645 Type *Ty = Orig->getType();
646 Type *EltTy = Ty->getScalarType();
647 IRBuilder<> Builder(Orig);
648
649 auto *XVec = dyn_cast<FixedVectorType>(Ty);
650 if (!XVec) {
651 if (auto *constantFP = dyn_cast<ConstantFP>(X)) {
652 const APFloat &fpVal = constantFP->getValueAPF();
653 if (fpVal.isZero())
654 reportFatalUsageError("Invalid input scalar: length is zero");
655 }
656 return Builder.CreateFDiv(X, X);
657 }
658
659 Value *DotProduct = expandFloatDotIntrinsic(Orig, X, X);
660
661 // verify that the length is non-zero
662 // (if the dot product is non-zero, then the length is non-zero)
663 if (auto *constantFP = dyn_cast<ConstantFP>(DotProduct)) {
664 const APFloat &fpVal = constantFP->getValueAPF();
665 if (fpVal.isZero())
666 reportFatalUsageError("Invalid input vector: length is zero");
667 }
668
669 Value *Multiplicand = Builder.CreateIntrinsic(EltTy, Intrinsic::dx_rsqrt,
670 ArrayRef<Value *>{DotProduct},
671 nullptr, "dx.rsqrt");
672
673 Value *MultiplicandVec =
674 Builder.CreateVectorSplat(XVec->getNumElements(), Multiplicand);
675 return Builder.CreateFMul(X, MultiplicandVec);
676}
677
679 Value *Y = Orig->getOperand(0);
680 Value *X = Orig->getOperand(1);
681 Type *Ty = X->getType();
682 IRBuilder<> Builder(Orig);
683 Builder.setFastMathFlags(Orig->getFastMathFlags());
684
685 Value *Tan = Builder.CreateFDiv(Y, X);
686
687 CallInst *Atan = Builder.CreateIntrinsicWithoutFolding(
688 Ty, Intrinsic::atan, {Tan}, nullptr, "Elt.Atan");
689 Atan->setTailCall(Orig->isTailCall());
690 Atan->setAttributes(Orig->getAttributes());
691
692 // Modify atan result based on https://en.wikipedia.org/wiki/Atan2.
693 Constant *Pi = ConstantFP::get(Ty, llvm::numbers::pi);
694 Constant *HalfPi = ConstantFP::get(Ty, llvm::numbers::pi / 2);
695 Constant *NegHalfPi = ConstantFP::get(Ty, -llvm::numbers::pi / 2);
696 Constant *Zero = ConstantFP::get(Ty, 0);
697 Value *AtanAddPi = Builder.CreateFAdd(Atan, Pi);
698 Value *AtanSubPi = Builder.CreateFSub(Atan, Pi);
699
700 // x > 0 -> atan.
701 Value *Result = Atan;
702 Value *XLt0 = Builder.CreateFCmpOLT(X, Zero);
703 Value *XEq0 = Builder.CreateFCmpOEQ(X, Zero);
704 Value *YGe0 = Builder.CreateFCmpOGE(Y, Zero);
705 Value *YLt0 = Builder.CreateFCmpOLT(Y, Zero);
706
707 // x < 0, y >= 0 -> atan + pi.
708 Value *XLt0AndYGe0 = Builder.CreateAnd(XLt0, YGe0);
709 Result = Builder.CreateSelect(XLt0AndYGe0, AtanAddPi, Result);
710
711 // x < 0, y < 0 -> atan - pi.
712 Value *XLt0AndYLt0 = Builder.CreateAnd(XLt0, YLt0);
713 Result = Builder.CreateSelect(XLt0AndYLt0, AtanSubPi, Result);
714
715 // x == 0, y < 0 -> -pi/2
716 Value *XEq0AndYLt0 = Builder.CreateAnd(XEq0, YLt0);
717 Result = Builder.CreateSelect(XEq0AndYLt0, NegHalfPi, Result);
718
719 // x == 0, y > 0 -> pi/2
720 Value *XEq0AndYGe0 = Builder.CreateAnd(XEq0, YGe0);
721 Result = Builder.CreateSelect(XEq0AndYGe0, HalfPi, Result);
722
723 return Result;
724}
725
726template <bool LeftFunnel>
728 Type *Ty = Orig->getType();
729 Value *A = Orig->getOperand(0);
730 Value *B = Orig->getOperand(1);
731 Value *Shift = Orig->getOperand(2);
732
733 IRBuilder<> Builder(Orig);
734
735 unsigned BitWidth = Ty->getScalarSizeInBits();
737 "Can't use Mask to compute modulo and inverse");
738
739 // Note: if (Shift % BitWidth) == 0 then (BitWidth - Shift) == BitWidth,
740 // shifting by the bitwidth for shl/lshr returns a poisoned result. As such,
741 // we implement the same formula as LegalizerHelper::lowerFunnelShiftAsShifts.
742 //
743 // The funnel shift is expanded like so:
744 // fshl
745 // -> msb_extract((concat(A, B) << (Shift % BitWidth)), BitWidth)
746 // -> A << (Shift % BitWidth) | B >> 1 >> (BitWidth - 1 - (Shift % BitWidth))
747 // fshr
748 // -> lsb_extract((concat(A, B) >> (Shift % BitWidth), BitWidth))
749 // -> A << 1 << (BitWidth - 1 - (Shift % BitWidth)) | B >> (Shift % BitWidth)
750
751 // (BitWidth - 1) -> Mask
752 Constant *Mask = ConstantInt::get(Ty, Ty->getScalarSizeInBits() - 1);
753
754 // Shift % BitWidth
755 // -> Shift & (BitWidth - 1)
756 // -> Shift & Mask
757 Value *MaskedShift = Builder.CreateAnd(Shift, Mask);
758
759 // (BitWidth - 1) - (Shift % BitWidth)
760 // -> ~Shift & (BitWidth - 1)
761 // -> ~Shift & Mask
762 Value *NotShift = Builder.CreateNot(Shift);
763 Value *InverseShift = Builder.CreateAnd(NotShift, Mask);
764
765 Constant *One = ConstantInt::get(Ty, 1);
766 Value *ShiftedA;
767 Value *ShiftedB;
768
769 if (LeftFunnel) {
770 ShiftedA = Builder.CreateShl(A, MaskedShift);
771 Value *ShiftB1 = Builder.CreateLShr(B, One);
772 ShiftedB = Builder.CreateLShr(ShiftB1, InverseShift);
773 } else {
774 Value *ShiftA1 = Builder.CreateShl(A, One);
775 ShiftedA = Builder.CreateShl(ShiftA1, InverseShift);
776 ShiftedB = Builder.CreateLShr(B, MaskedShift);
777 }
778
779 Value *Result = Builder.CreateOr(ShiftedA, ShiftedB);
780 return Result;
781}
782
783static Value *expandPowIntrinsic(CallInst *Orig, Intrinsic::ID IntrinsicId) {
784
785 Value *X = Orig->getOperand(0);
786 Value *Y = Orig->getOperand(1);
787 Type *Ty = X->getType();
788 IRBuilder<> Builder(Orig);
789
790 if (IntrinsicId == Intrinsic::powi)
791 Y = Builder.CreateSIToFP(Y, Ty);
792
793 Value *Log2Call =
794 Builder.CreateIntrinsic(Ty, Intrinsic::log2, {X}, nullptr, "elt.log2");
795 auto *Mul = Builder.CreateFMul(Log2Call, Y);
796 CallInst *Exp2Call = Builder.CreateIntrinsicWithoutFolding(
797 Ty, Intrinsic::exp2, {Mul}, nullptr, "elt.exp2");
798 Exp2Call->setTailCall(Orig->isTailCall());
799 Exp2Call->setAttributes(Orig->getAttributes());
800 return Exp2Call;
801}
802
804 Value *X = Orig->getOperand(0);
805 Type *Ty = X->getType();
806 IRBuilder<> Builder(Orig);
807 Value *PiOver180 = ConstantFP::get(Ty, llvm::numbers::pi / 180.0);
808 return Builder.CreateFMul(X, PiOver180);
809}
810
811static bool expandBufferLoadIntrinsic(CallInst *Orig, bool IsRaw) {
812 IRBuilder<> Builder(Orig);
813
814 Type *BufferTy = Orig->getType()->getStructElementType(0);
815 Type *ScalarTy = BufferTy->getScalarType();
816 bool IsDouble = ScalarTy->isDoubleTy();
817 assert(IsDouble || ScalarTy->isIntegerTy(64) &&
818 "Only expand double or int64 scalars or vectors");
819 bool IsVector = false;
820 unsigned ExtractNum = 2;
821 if (auto *VT = dyn_cast<FixedVectorType>(BufferTy)) {
822 ExtractNum = 2 * VT->getNumElements();
823 IsVector = true;
824 assert(IsRaw || ExtractNum == 4 && "TypedBufferLoad vector must be size 2");
825 }
826
828 Value *Result = PoisonValue::get(BufferTy);
829 unsigned Base = 0;
830 // If we need to extract more than 4 i32; we need to break it up into
831 // more than one load. LoadNum tells us how many i32s we are loading in
832 // each load
833 while (ExtractNum > 0) {
834 unsigned LoadNum = std::min(ExtractNum, 4u);
835 Type *Ty = VectorType::get(Builder.getInt32Ty(), LoadNum, false);
836
837 Type *LoadType = StructType::get(Ty, Builder.getInt1Ty());
838 Intrinsic::ID LoadIntrinsic = Intrinsic::dx_resource_load_typedbuffer;
839 SmallVector<Value *, 3> Args = {Orig->getOperand(0), Orig->getOperand(1)};
840 if (IsRaw) {
841 LoadIntrinsic = Intrinsic::dx_resource_load_rawbuffer;
842 Value *Tmp = Builder.getInt32(4 * Base * 2);
843 Args.push_back(Builder.CreateAdd(Orig->getOperand(2), Tmp));
844 }
845
846 Value *Load = Builder.CreateIntrinsic(LoadType, LoadIntrinsic, Args);
847 Loads.push_back(Load);
848
849 // extract the buffer load's result
850 Value *Extract = Builder.CreateExtractValue(Load, {0});
851
852 SmallVector<Value *> ExtractElements;
853 for (unsigned I = 0; I < LoadNum; ++I)
854 ExtractElements.push_back(
855 Builder.CreateExtractElement(Extract, Builder.getInt32(I)));
856
857 // combine into double(s) or int64(s)
858 for (unsigned I = 0; I < LoadNum; I += 2) {
859 Value *Combined = nullptr;
860 if (IsDouble)
861 // For doubles, use dx_asdouble intrinsic
862 Combined = Builder.CreateIntrinsic(
863 Builder.getDoubleTy(), Intrinsic::dx_asdouble,
864 {ExtractElements[I], ExtractElements[I + 1]});
865 else {
866 // For int64, manually combine two int32s
867 // First, zero-extend both values to i64
868 Value *Lo =
869 Builder.CreateZExt(ExtractElements[I], Builder.getInt64Ty());
870 Value *Hi =
871 Builder.CreateZExt(ExtractElements[I + 1], Builder.getInt64Ty());
872 // Shift the high bits left by 32 bits
873 Value *ShiftedHi = Builder.CreateShl(Hi, Builder.getInt64(32));
874 // OR the high and low bits together
875 Combined = Builder.CreateOr(Lo, ShiftedHi);
876 }
877
878 if (IsVector)
879 Result = Builder.CreateInsertElement(Result, Combined,
880 Builder.getInt32((I / 2) + Base));
881 else
882 Result = Combined;
883 }
884
885 ExtractNum -= LoadNum;
886 Base += LoadNum / 2;
887 }
888
889 Value *CheckBit = nullptr;
890 for (User *U : make_early_inc_range(Orig->users())) {
891 // If it's not a ExtractValueInst, we don't know how to
892 // handle it
893 auto *EVI = dyn_cast<ExtractValueInst>(U);
894 if (!EVI)
895 llvm_unreachable("Unexpected user of typedbufferload");
896
897 ArrayRef<unsigned> Indices = EVI->getIndices();
898 assert(Indices.size() == 1);
899
900 if (Indices[0] == 0) {
901 // Use of the value(s)
902 EVI->replaceAllUsesWith(Result);
903 } else {
904 // Use of the check bit
905 assert(Indices[0] == 1 && "Unexpected type for typedbufferload");
906 // Note: This does not always match the historical behaviour of DXC.
907 // See https://github.com/microsoft/DirectXShaderCompiler/issues/7622
908 if (!CheckBit) {
909 SmallVector<Value *, 2> CheckBits;
910 for (Value *L : Loads)
911 CheckBits.push_back(Builder.CreateExtractValue(L, {1}));
912 CheckBit = Builder.CreateAnd(CheckBits);
913 }
914 EVI->replaceAllUsesWith(CheckBit);
915 }
916 EVI->eraseFromParent();
917 }
918 Orig->eraseFromParent();
919 return true;
920}
921
922static bool expandBufferStoreIntrinsic(CallInst *Orig, bool IsRaw) {
923 IRBuilder<> Builder(Orig);
924
925 unsigned ValIndex = IsRaw ? 3 : 2;
926 Type *BufferTy = Orig->getFunctionType()->getParamType(ValIndex);
927 Type *ScalarTy = BufferTy->getScalarType();
928 bool IsDouble = ScalarTy->isDoubleTy();
929 assert((IsDouble || ScalarTy->isIntegerTy(64)) &&
930 "Only expand double or int64 scalars or vectors");
931
932 // Determine if we're dealing with a vector or scalar
933 bool IsVector = false;
934 unsigned ExtractNum = 2;
935 unsigned VecLen = 0;
936 if (auto *VT = dyn_cast<FixedVectorType>(BufferTy)) {
937 VecLen = VT->getNumElements();
938 assert(IsRaw || VecLen == 2 && "TypedBufferStore vector must be size 2");
939 ExtractNum = VecLen * 2;
940 IsVector = true;
941 }
942
943 // Create the appropriate vector type for the result
944 Type *Int32Ty = Builder.getInt32Ty();
945 Type *ResultTy = VectorType::get(Int32Ty, ExtractNum, false);
946 Value *Val = PoisonValue::get(ResultTy);
947
948 Type *SplitElementTy = Int32Ty;
949 if (IsVector)
950 SplitElementTy = VectorType::get(SplitElementTy, VecLen, false);
951
952 Value *LowBits = nullptr;
953 Value *HighBits = nullptr;
954 // Split the 64-bit values into 32-bit components
955 if (IsDouble) {
956 auto *SplitTy = llvm::StructType::get(SplitElementTy, SplitElementTy);
957 Value *Split = Builder.CreateIntrinsic(SplitTy, Intrinsic::dx_splitdouble,
958 {Orig->getOperand(ValIndex)});
959 LowBits = Builder.CreateExtractValue(Split, 0);
960 HighBits = Builder.CreateExtractValue(Split, 1);
961 } else {
962 // Handle int64 type(s)
963 Value *InputVal = Orig->getOperand(ValIndex);
964 Constant *ShiftAmt = Builder.getInt64(32);
965 if (IsVector)
966 ShiftAmt =
968
969 // Split into low and high 32-bit parts
970 LowBits = Builder.CreateTrunc(InputVal, SplitElementTy);
971 Value *ShiftedVal = Builder.CreateLShr(InputVal, ShiftAmt);
972 HighBits = Builder.CreateTrunc(ShiftedVal, SplitElementTy);
973 }
974
975 if (IsVector) {
977 for (unsigned I = 0; I < VecLen; ++I) {
978 Mask.push_back(I);
979 Mask.push_back(I + VecLen);
980 }
981 Val = Builder.CreateShuffleVector(LowBits, HighBits, Mask);
982 } else {
983 Val = Builder.CreateInsertElement(Val, LowBits, Builder.getInt32(0));
984 Val = Builder.CreateInsertElement(Val, HighBits, Builder.getInt32(1));
985 }
986
987 // If we need to extract more than 4 i32; we need to break it up into
988 // more than one store. StoreNum tells us how many i32s we are storing in
989 // each store
990 unsigned Base = 0;
991 while (ExtractNum > 0) {
992 unsigned StoreNum = std::min(ExtractNum, 4u);
993
994 Intrinsic::ID StoreIntrinsic = Intrinsic::dx_resource_store_typedbuffer;
995 SmallVector<Value *, 4> Args = {Orig->getOperand(0), Orig->getOperand(1)};
996 if (IsRaw) {
997 StoreIntrinsic = Intrinsic::dx_resource_store_rawbuffer;
998 Value *Tmp = Builder.getInt32(4 * Base);
999 Args.push_back(Builder.CreateAdd(Orig->getOperand(2), Tmp));
1000 }
1001
1003 for (unsigned I = 0; I < StoreNum; ++I) {
1004 Mask.push_back(Base + I);
1005 }
1006
1007 Value *SubVal = Val;
1008 if (VecLen > 2)
1009 SubVal = Builder.CreateShuffleVector(Val, Mask);
1010
1011 Args.push_back(SubVal);
1012 // Create the final intrinsic call
1013 Builder.CreateIntrinsic(Builder.getVoidTy(), StoreIntrinsic, Args);
1014
1015 ExtractNum -= StoreNum;
1016 Base += StoreNum;
1017 }
1018 Orig->eraseFromParent();
1019 return true;
1020}
1021
1023 if (ClampIntrinsic == Intrinsic::dx_uclamp)
1024 return Intrinsic::umax;
1025 if (ClampIntrinsic == Intrinsic::dx_sclamp)
1026 return Intrinsic::smax;
1027 assert(ClampIntrinsic == Intrinsic::dx_nclamp);
1028 return Intrinsic::maxnum;
1029}
1030
1032 if (ClampIntrinsic == Intrinsic::dx_uclamp)
1033 return Intrinsic::umin;
1034 if (ClampIntrinsic == Intrinsic::dx_sclamp)
1035 return Intrinsic::smin;
1036 assert(ClampIntrinsic == Intrinsic::dx_nclamp);
1037 return Intrinsic::minnum;
1038}
1039
1041 Intrinsic::ID ClampIntrinsic) {
1042 Value *X = Orig->getOperand(0);
1043 Value *Min = Orig->getOperand(1);
1044 Value *Max = Orig->getOperand(2);
1045 Type *Ty = X->getType();
1046 IRBuilder<> Builder(Orig);
1047 auto *MaxCall = Builder.CreateIntrinsic(Ty, getMaxForClamp(ClampIntrinsic),
1048 {X, Min}, nullptr, "dx.max");
1049 return Builder.CreateIntrinsic(Ty, getMinForClamp(ClampIntrinsic),
1050 {MaxCall, Max}, nullptr, "dx.min");
1051}
1052
1054 Value *X = Orig->getOperand(0);
1055 Type *Ty = X->getType();
1056 IRBuilder<> Builder(Orig);
1057 Value *DegreesRatio = ConstantFP::get(Ty, 180.0 * llvm::numbers::inv_pi);
1058 return Builder.CreateFMul(X, DegreesRatio);
1059}
1060
1062 Value *X = Orig->getOperand(0);
1063 Type *Ty = X->getType();
1064 Type *ScalarTy = Ty->getScalarType();
1065 Type *RetTy = Orig->getType();
1066 Constant *Zero = Constant::getNullValue(Ty);
1067
1068 IRBuilder<> Builder(Orig);
1069
1070 Value *GT;
1071 Value *LT;
1072 if (ScalarTy->isFloatingPointTy()) {
1073 GT = Builder.CreateFCmpOLT(Zero, X);
1074 LT = Builder.CreateFCmpOLT(X, Zero);
1075 } else {
1076 assert(ScalarTy->isIntegerTy());
1077 GT = Builder.CreateICmpSLT(Zero, X);
1078 LT = Builder.CreateICmpSLT(X, Zero);
1079 }
1080
1081 Value *ZextGT = Builder.CreateZExt(GT, RetTy);
1082 Value *ZextLT = Builder.CreateZExt(LT, RetTy);
1083
1084 return Builder.CreateSub(ZextGT, ZextLT);
1085}
1086
1087// Expand llvm.matrix.multiply by extracting row/column vectors and computing
1088// dot products.
1089// Result[r,c] = dot(row_r(LHS), col_c(RHS))
1090// Element (r,c) is at index c*NumRows + r (column-major).
1092 Value *LHS = Orig->getArgOperand(0);
1093 Value *RHS = Orig->getArgOperand(1);
1094 unsigned LHSRows = cast<ConstantInt>(Orig->getArgOperand(2))->getZExtValue();
1095 unsigned LHSCols = cast<ConstantInt>(Orig->getArgOperand(3))->getZExtValue();
1096 unsigned RHSCols = cast<ConstantInt>(Orig->getArgOperand(4))->getZExtValue();
1097
1098 auto *RetTy = cast<FixedVectorType>(Orig->getType());
1099 Type *EltTy = RetTy->getElementType();
1100 bool IsFP = EltTy->isFloatingPointTy();
1101
1102 IRBuilder<> Builder(Orig);
1103
1104 // Column-major indexing:
1105 // LHS row R, element K: index = K * LHSRows + R
1106 // RHS col C, element K: index = C * LHSCols + K
1107 Value *Result = PoisonValue::get(RetTy);
1108
1109 // Extract all scalar elements from LHS and RHS once, then reuse them.
1110 unsigned LHSSize = LHSRows * LHSCols;
1111 unsigned RHSSize = LHSCols * RHSCols;
1112 SmallVector<Value *, 16> LHSElts(LHSSize);
1113 SmallVector<Value *, 16> RHSElts(RHSSize);
1114 for (unsigned I = 0; I < LHSSize; ++I)
1115 LHSElts[I] = Builder.CreateExtractElement(LHS, I);
1116 for (unsigned I = 0; I < RHSSize; ++I)
1117 RHSElts[I] = Builder.CreateExtractElement(RHS, I);
1118
1119 // Choose the appropriate scalar-arg dot intrinsic for floats.
1120 // K=1 and double types use scalar expansion instead.
1122 bool UseScalarFP = IsFP && (EltTy->isDoubleTy() || LHSCols == 1);
1123 if (IsFP && !UseScalarFP) {
1124 switch (LHSCols) {
1125 case 2:
1126 FloatDotID = Intrinsic::dx_dot2;
1127 break;
1128 case 3:
1129 FloatDotID = Intrinsic::dx_dot3;
1130 break;
1131 case 4:
1132 FloatDotID = Intrinsic::dx_dot4;
1133 break;
1134 default:
1136 "Invalid matrix inner dimension for dot product: must be 2-4");
1137 return nullptr;
1138 }
1139 }
1140
1141 for (unsigned C = 0; C < RHSCols; ++C) {
1142 for (unsigned R = 0; R < LHSRows; ++R) {
1143 // Gather row R from LHS and column C from RHS.
1144 SmallVector<Value *, 4> RowElts, ColElts;
1145 for (unsigned K = 0; K < LHSCols; ++K) {
1146 RowElts.push_back(LHSElts[K * LHSRows + R]);
1147 ColElts.push_back(RHSElts[C * LHSCols + K]);
1148 }
1149
1150 Value *Dot;
1151 if (UseScalarFP) {
1152 // Scalar fmul+fmuladd expansion for double types and K=1.
1153 Dot = Builder.CreateFMul(RowElts[0], ColElts[0]);
1154 for (unsigned K = 1; K < LHSCols; ++K)
1155 Dot = Builder.CreateIntrinsic(EltTy, Intrinsic::fmuladd,
1156 {RowElts[K], ColElts[K], Dot});
1157 } else if (IsFP) {
1158 // Emit scalar-arg DXIL dot directly (dx.dot2/dx.dot3/dx.dot4).
1160 Args.append(RowElts.begin(), RowElts.end());
1161 Args.append(ColElts.begin(), ColElts.end());
1162 Dot = Builder.CreateIntrinsic(EltTy, FloatDotID, Args);
1163 } else {
1164 // Integer: emit multiply + imad chain.
1165 Dot = Builder.CreateMul(RowElts[0], ColElts[0]);
1166 for (unsigned K = 1; K < LHSCols; ++K)
1167 Dot = Builder.CreateIntrinsic(EltTy, Intrinsic::dx_imad,
1168 {RowElts[K], ColElts[K], Dot});
1169 }
1170 unsigned ResIdx = C * LHSRows + R;
1171 Result = Builder.CreateInsertElement(Result, Dot, ResIdx);
1172 }
1173 }
1174 return Result;
1175}
1176
1177// Expand llvm.matrix.transpose as a shufflevector that permutes elements
1178// from column-major source to column-major transposed layout.
1179// Element (r,c) at index c*Rows + r moves to index r*Cols + c.
1181 Value *Mat = Orig->getArgOperand(0);
1182 unsigned Rows = cast<ConstantInt>(Orig->getArgOperand(1))->getZExtValue();
1183 unsigned Cols = cast<ConstantInt>(Orig->getArgOperand(2))->getZExtValue();
1184
1185 unsigned NumElts = Rows * Cols;
1186 SmallVector<int, 16> Mask(NumElts);
1187 for (unsigned I = 0; I < NumElts; ++I)
1188 Mask[I] = (I % Cols) * Rows + (I / Cols);
1189
1190 IRBuilder<> Builder(Orig);
1191 return Builder.CreateShuffleVector(Mat, Mask);
1192}
1193
1194// Scalarize a vector int_dx_store_output call into per-component scalar calls.
1195// The DXIL StoreOutput op is per-component; vector intrinsics are split here
1196// so that DXILOpLowering sees only scalar variants.
1197static bool expandStoreOutput(CallInst *Orig) {
1198 auto *VT = dyn_cast<FixedVectorType>(Orig->getArgOperand(4)->getType());
1199 if (!VT)
1200 return false; // already scalar, nothing to expand
1201
1202 IRBuilder<> Builder(Orig);
1203 Module *M = Orig->getModule();
1204 Type *Int8Ty = Builder.getInt8Ty();
1205 Type *Int32Ty = Builder.getInt32Ty();
1206 Type *ScalarTy = VT->getElementType();
1207 unsigned NumElems = VT->getNumElements();
1208
1209 Value *SigpointId = Orig->getArgOperand(0);
1210 Value *SigElementId = Orig->getArgOperand(1);
1211 Value *RowIndex = Orig->getArgOperand(2);
1212 Value *StartCol = Orig->getArgOperand(3); // i8
1213 Value *Data = Orig->getArgOperand(4);
1214 Value *StartColI32 = Builder.CreateZExt(StartCol, Int32Ty);
1215
1217 M, Intrinsic::dx_store_output, {ScalarTy});
1218
1219 for (unsigned I = 0; I < NumElems; ++I) {
1220 Value *Scalar =
1221 Builder.CreateExtractElement(Data, ConstantInt::get(Int32Ty, I));
1222 Value *ColIdx =
1223 Builder.CreateAdd(StartColI32, ConstantInt::get(Int32Ty, I));
1224 Value *ColI8 = Builder.CreateTrunc(ColIdx, Int8Ty);
1225 Builder.CreateCall(ScalarFn,
1226 {SigpointId, SigElementId, RowIndex, ColI8, Scalar});
1227 }
1228
1229 Orig->eraseFromParent();
1230 return true;
1231}
1232
1233// Scalarize a vector int_dx_load_input call into per-component scalar calls
1234// and reassemble the vector. The DXIL LoadInput op is per-component.
1236 auto *VT = dyn_cast<FixedVectorType>(Orig->getType());
1237 if (!VT)
1238 return nullptr; // already scalar, nothing to expand
1239
1240 IRBuilder<> Builder(Orig);
1241 Module *M = Orig->getModule();
1242 Type *Int8Ty = Builder.getInt8Ty();
1243 Type *Int32Ty = Builder.getInt32Ty();
1244 Type *ScalarTy = VT->getElementType();
1245 unsigned NumElems = VT->getNumElements();
1246
1247 Value *SigpointId = Orig->getArgOperand(0);
1248 Value *SigElementId = Orig->getArgOperand(1);
1249 Value *RowIndex = Orig->getArgOperand(2);
1250 Value *StartCol = Orig->getArgOperand(3); // i8
1251 Value *GsVertexOrPrimIndex = Orig->getArgOperand(4);
1252 Value *StartColI32 = Builder.CreateZExt(StartCol, Int32Ty);
1253
1255 M, Intrinsic::dx_load_input, {ScalarTy});
1256
1257 Value *Vec = PoisonValue::get(VT);
1258 for (unsigned I = 0; I < NumElems; ++I) {
1259 Value *ColIdx =
1260 Builder.CreateAdd(StartColI32, ConstantInt::get(Int32Ty, I));
1261 Value *ColI8 = Builder.CreateTrunc(ColIdx, Int8Ty);
1262 Value *Scalar =
1263 Builder.CreateCall(ScalarFn, {SigpointId, SigElementId, RowIndex, ColI8,
1264 GsVertexOrPrimIndex});
1265 Vec =
1266 Builder.CreateInsertElement(Vec, Scalar, ConstantInt::get(Int32Ty, I));
1267 }
1268
1269 return Vec;
1270}
1271
1272static bool expandIntrinsic(Function &F, CallInst *Orig) {
1273 Value *Result = nullptr;
1274 Intrinsic::ID IntrinsicId = F.getIntrinsicID();
1275 switch (IntrinsicId) {
1276 case Intrinsic::abs:
1277 Result = expandAbs(Orig);
1278 break;
1279 case Intrinsic::assume:
1280 Orig->eraseFromParent();
1281 return true;
1282 case Intrinsic::atan2:
1283 Result = expandAtan2Intrinsic(Orig);
1284 break;
1285 case Intrinsic::fshl:
1286 Result = expandFunnelShiftIntrinsic<true>(Orig);
1287 break;
1288 case Intrinsic::fshr:
1289 Result = expandFunnelShiftIntrinsic<false>(Orig);
1290 break;
1291 case Intrinsic::exp:
1292 Result = expandExpIntrinsic(Orig);
1293 break;
1294 case Intrinsic::is_fpclass:
1295 Result = expandIsFPClass(Orig);
1296 break;
1297 case Intrinsic::log:
1298 Result = expandLogIntrinsic(Orig);
1299 break;
1300 case Intrinsic::log10:
1301 Result = expandLog10Intrinsic(Orig);
1302 break;
1303 case Intrinsic::pow:
1304 case Intrinsic::powi:
1305 Result = expandPowIntrinsic(Orig, IntrinsicId);
1306 break;
1307 case Intrinsic::dx_all:
1308 case Intrinsic::dx_any:
1309 Result = expandAnyOrAllIntrinsic(Orig, IntrinsicId);
1310 break;
1311 case Intrinsic::dx_uclamp:
1312 case Intrinsic::dx_sclamp:
1313 case Intrinsic::dx_nclamp:
1314 Result = expandClampIntrinsic(Orig, IntrinsicId);
1315 break;
1316 case Intrinsic::dx_degrees:
1317 Result = expandDegreesIntrinsic(Orig);
1318 break;
1319 case Intrinsic::dx_isinf:
1320 Result = expand16BitIsInf(Orig);
1321 break;
1322 case Intrinsic::dx_isnan:
1323 Result = expand16BitIsNaN(Orig);
1324 break;
1325 case Intrinsic::dx_lerp:
1326 Result = expandLerpIntrinsic(Orig);
1327 break;
1328 case Intrinsic::dx_normalize:
1329 Result = expandNormalizeIntrinsic(Orig);
1330 break;
1331 case Intrinsic::dx_fdot:
1332 Result = expandFloatDotIntrinsic(Orig);
1333 break;
1334 case Intrinsic::dx_sdot:
1335 case Intrinsic::dx_udot:
1336 Result = expandIntegerDotIntrinsic(Orig, IntrinsicId);
1337 break;
1338 case Intrinsic::dx_sign:
1339 Result = expandSignIntrinsic(Orig);
1340 break;
1341 case Intrinsic::dx_radians:
1342 Result = expandRadiansIntrinsic(Orig);
1343 break;
1344 case Intrinsic::dx_load_input:
1345 Result = expandLoadInput(Orig);
1346 break;
1347 case Intrinsic::dx_store_output:
1348 if (expandStoreOutput(Orig))
1349 return true;
1350 break;
1351 case Intrinsic::dx_resource_load_rawbuffer:
1352 if (expandBufferLoadIntrinsic(Orig, /*IsRaw*/ true))
1353 return true;
1354 break;
1355 case Intrinsic::dx_resource_store_rawbuffer:
1356 if (expandBufferStoreIntrinsic(Orig, /*IsRaw*/ true))
1357 return true;
1358 break;
1359 case Intrinsic::dx_resource_load_typedbuffer:
1360 if (expandBufferLoadIntrinsic(Orig, /*IsRaw*/ false))
1361 return true;
1362 break;
1363 case Intrinsic::dx_resource_store_typedbuffer:
1364 if (expandBufferStoreIntrinsic(Orig, /*IsRaw*/ false))
1365 return true;
1366 break;
1367 case Intrinsic::usub_sat:
1368 Result = expandUsubSat(Orig);
1369 break;
1370 case Intrinsic::umul_with_overflow:
1371 case Intrinsic::smul_with_overflow:
1372 Result = expandMulWithOverflow(Orig, /*Signed=*/IntrinsicId ==
1373 Intrinsic::smul_with_overflow);
1374 break;
1375 case Intrinsic::vector_reduce_add:
1376 case Intrinsic::vector_reduce_fadd:
1377 Result = expandVecReduceAdd(Orig, IntrinsicId);
1378 break;
1379 case Intrinsic::matrix_multiply:
1380 Result = expandMatrixMultiply(Orig);
1381 break;
1382 case Intrinsic::matrix_transpose:
1383 Result = expandMatrixTranspose(Orig);
1384 break;
1385 }
1386 if (Result) {
1387 Orig->replaceAllUsesWith(Result);
1388 Orig->eraseFromParent();
1389 return true;
1390 }
1391 return false;
1392}
1393
1395 for (auto &F : make_early_inc_range(M.functions())) {
1396 if (!isIntrinsicExpansion(F))
1397 continue;
1398 bool IntrinsicExpanded = false;
1399 for (User *U : make_early_inc_range(F.users())) {
1400 auto *IntrinsicCall = dyn_cast<CallInst>(U);
1401 if (!IntrinsicCall)
1402 continue;
1403 IntrinsicExpanded = expandIntrinsic(F, IntrinsicCall);
1404 }
1405 if (F.user_empty() && IntrinsicExpanded)
1406 F.eraseFromParent();
1407 }
1408 return true;
1409}
1410
1417
1421
1423
1425 "DXIL Intrinsic Expansion", false, false)
1427 "DXIL Intrinsic Expansion", false, false)
1428
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
This file implements a class to represent arbitrary precision integral constant values and operations...
#define X(NUM, ENUM, NAME)
Definition ELF.h:856
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
This file contains the declarations for the subclasses of Constant, which represent the different fla...
static Value * expand16BitIsNormal(CallInst *Orig)
static Value * expandNormalizeIntrinsic(CallInst *Orig)
static Value * createMulHighUnsigned(IRBuilder<> &Builder, Value *A, Value *B, Type *Ty, unsigned BW)
static bool expandIntrinsic(Function &F, CallInst *Orig)
static Value * expandClampIntrinsic(CallInst *Orig, Intrinsic::ID ClampIntrinsic)
static Value * expand16BitIsInf(CallInst *Orig)
static bool expansionIntrinsics(Module &M)
static Value * expand16BitIsFinite(CallInst *Orig)
static Value * expandLoadInput(CallInst *Orig)
static Value * expandLerpIntrinsic(CallInst *Orig)
static Value * expandUsubSat(CallInst *Orig)
static Value * expandAnyOrAllIntrinsic(CallInst *Orig, Intrinsic::ID IntrinsicId)
static bool expandStoreOutput(CallInst *Orig)
static Value * expandMatrixTranspose(CallInst *Orig)
static Value * expandVecReduceAdd(CallInst *Orig, Intrinsic::ID IntrinsicId)
static Value * expandAtan2Intrinsic(CallInst *Orig)
static Value * expandLog10Intrinsic(CallInst *Orig)
static Intrinsic::ID getMinForClamp(Intrinsic::ID ClampIntrinsic)
static Value * expandIntegerDotIntrinsic(CallInst *Orig, Intrinsic::ID DotIntrinsic)
static bool expandBufferStoreIntrinsic(CallInst *Orig, bool IsRaw)
static Value * expandLogIntrinsic(CallInst *Orig, float LogConstVal=numbers::ln2f)
static Value * expandDegreesIntrinsic(CallInst *Orig)
static Value * expandMulWithOverflow(CallInst *Orig, bool Signed)
static Value * expandPowIntrinsic(CallInst *Orig, Intrinsic::ID IntrinsicId)
static bool resourceAccessNeeds64BitExpansion(Module *M, Type *OverloadTy, bool IsRaw)
static Value * expandExpIntrinsic(CallInst *Orig)
static Value * expand16BitIsNaN(CallInst *Orig)
static Value * expandSignIntrinsic(CallInst *Orig)
static Intrinsic::ID getMaxForClamp(Intrinsic::ID ClampIntrinsic)
static Value * expandAbs(CallInst *Orig)
static Value * expandFloatDotIntrinsic(CallInst *Orig, Value *A, Value *B)
static Value * expandRadiansIntrinsic(CallInst *Orig)
static bool isIntrinsicExpansion(Function &F)
static bool expandBufferLoadIntrinsic(CallInst *Orig, bool IsRaw)
static Value * expandMatrixMultiply(CallInst *Orig)
static Value * expandIsFPClass(CallInst *Orig)
static Value * expandFunnelShiftIntrinsic(CallInst *Orig)
#define DEBUG_TYPE
Module.h This file contains the declarations for the Module class.
This header defines various interfaces for pass management in LLVM.
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
#define T
#define INITIALIZE_PASS_END(passName, arg, name, cfg, analysis)
Definition PassSupport.h:44
#define INITIALIZE_PASS_BEGIN(passName, arg, name, cfg, analysis)
Definition PassSupport.h:39
const SmallVectorImpl< MachineOperand > & Cond
This file contains some templates that are useful if you are working with the STL at all.
This file defines the SmallVector class.
static TableGen::Emitter::Opt Y("gen-skeleton-entry", EmitSkeleton, "Generate example skeleton entry")
Value * RHS
Value * LHS
BinaryOperator * Mul
bool runOnModule(Module &M) override
runOnModule - Virtual method overriden by subclasses to process the module being operated on.
bool isZero() const
Definition APFloat.h:1571
static APInt getLowBitsSet(unsigned numBits, unsigned loBitsSet)
Constructs an APInt value that has the bottom loBitsSet bits set.
Definition APInt.h:307
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
size_t size() const
Get the array size.
Definition ArrayRef.h:141
void setAttributes(AttributeList A)
Set the attributes for this call.
Value * getArgOperand(unsigned i) const
FunctionType * getFunctionType() const
AttributeList getAttributes() const
Return the attributes for this call.
This class represents a function call, abstracting a target machine's calling convention.
bool isTailCall() const
void setTailCall(bool IsTc=true)
static LLVM_ABI Constant * getSplat(ElementCount EC, Constant *Elt)
Return a ConstantVector with the specified constant in each element.
This is an important base class in LLVM.
Definition Constant.h:43
bool isNullValue() const
Return true if this is the value that would be returned by getNullValue.
Definition Constant.h:64
static LLVM_ABI Constant * getNullValue(Type *Ty)
Constructor to create a '0' constant of arbitrary type.
PreservedAnalyses run(Module &M, ModuleAnalysisManager &)
static constexpr ElementCount getFixed(ScalarTy MinVal)
Definition TypeSize.h:309
static LLVM_ABI FixedVectorType * get(Type *ElementType, unsigned NumElts)
Definition Type.cpp:867
Type * getParamType(unsigned i) const
Parameter type accessors.
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
Definition IRBuilder.h:2893
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.
LLVM_ABI FastMathFlags getFastMathFlags() const LLVM_READONLY
Convenience function for getting all the fast-math flags, which must be an operator which supports th...
ModulePass class - This class is used to implement unstructured interprocedural optimizations and ana...
Definition Pass.h:255
ModulePass(char &pid)
Definition Pass.h:257
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.
A set of analyses that are preserved following a run of a transformation pass.
Definition Analysis.h:112
static PreservedAnalyses none()
Convenience factory function for the empty preserved set.
Definition Analysis.h:115
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition Analysis.h:118
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
static LLVM_ABI StructType * get(LLVMContext &Context, ArrayRef< Type * > Elements, bool isPacked=false)
This static method is the primary way to create a literal StructType.
Definition Type.cpp:477
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:46
LLVM_ABI Type * getStructElementType(unsigned N) const
bool isVectorTy() const
True if this is an instance of VectorType.
Definition Type.h:288
static LLVM_ABI IntegerType * getInt32Ty(LLVMContext &C)
Definition Type.cpp:309
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
LLVM_ABI TypeSize getPrimitiveSizeInBits() const LLVM_READONLY
Return the basic size of this type if it is a primitive type.
Definition Type.cpp:197
LLVM_ABI Type * getWithNewBitWidth(unsigned NewBitWidth) const
Given an integer or vector type, change the lane bitwidth to NewBitwidth, whilst keeping the old numb...
static LLVM_ABI IntegerType * getInt16Ty(LLVMContext &C)
Definition Type.cpp:308
bool isHalfTy() const
Return true if this is 'half', a 16-bit IEEE fp type.
Definition Type.h:144
bool isDoubleTy() const
Return true if this is 'double', a 64-bit IEEE fp type.
Definition Type.h:158
bool isFloatingPointTy() const
Return true if this is one of the floating-point types.
Definition Type.h:186
bool isIntegerTy() const
True if this is an instance of IntegerType.
Definition Type.h:257
static LLVM_ABI IntegerType * getIntNTy(LLVMContext &C, unsigned N)
Definition Type.cpp:313
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
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
static LLVM_ABI VectorType * get(Type *ElementType, ElementCount EC)
This static method is the primary way to construct an VectorType.
Represents a version number in the form major[.minor[.subminor[.build]]].
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
LLVM_ABI Function * getOrInsertDeclaration(Module *M, ID id, ArrayRef< Type * > OverloadTys={})
Look up the Function declaration of the intrinsic id in the Module M.
constexpr double inv_pi
constexpr float ln10f
Definition MathExtras.h:51
constexpr float log2ef
Definition MathExtras.h:52
constexpr double pi
constexpr float ln2f
Definition MathExtras.h:50
This is an optimization pass for GlobalISel generic memory operations.
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
@ Load
The value being inserted comes from a load (InsertElement only).
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
constexpr bool isPowerOf2_32(uint32_t Value)
Return true if the argument is a power of two > 0.
Definition MathExtras.h:280
ModulePass * createDXILIntrinsicExpansionLegacyPass()
Pass to expand intrinsic operations that lack DXIL opCodes.
@ Sub
Subtraction of integers.
constexpr unsigned BitWidth
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
AnalysisManager< Module > ModuleAnalysisManager
Convenience typedef for the Module analysis manager.
Definition MIRParser.h:39
LLVM_ABI void reportFatalUsageError(Error Err)
Report a fatal error that does not indicate a bug in LLVM.
Definition Error.cpp:177