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_isinf:
220 case Intrinsic::dx_isnan:
221 case Intrinsic::dx_normalize:
222 case Intrinsic::dx_fdot:
223 case Intrinsic::dx_sdot:
224 case Intrinsic::dx_udot:
225 case Intrinsic::dx_sign:
226 case Intrinsic::usub_sat:
227 case Intrinsic::vector_reduce_add:
228 case Intrinsic::vector_reduce_fadd:
229 case Intrinsic::matrix_multiply:
230 case Intrinsic::matrix_transpose:
231 case Intrinsic::umul_with_overflow:
232 case Intrinsic::smul_with_overflow:
233 case Intrinsic::dx_load_input:
234 case Intrinsic::dx_store_output:
235 return true;
236 case Intrinsic::dx_resource_load_rawbuffer:
238 F.getParent(), F.getReturnType()->getStructElementType(0),
239 /*IsRaw*/ true);
240 case Intrinsic::dx_resource_load_typedbuffer:
242 F.getParent(), F.getReturnType()->getStructElementType(0),
243 /*IsRaw*/ false);
244 case Intrinsic::dx_resource_store_rawbuffer:
246 F.getParent(), F.getFunctionType()->getParamType(3), /*IsRaw*/ true);
247 case Intrinsic::dx_resource_store_typedbuffer:
249 F.getParent(), F.getFunctionType()->getParamType(2), /*IsRaw*/ false);
250 }
251 return false;
252}
253
255 Value *A = Orig->getArgOperand(0);
256 Value *B = Orig->getArgOperand(1);
257 Type *Ty = A->getType();
258
259 IRBuilder<> Builder(Orig);
260
261 Value *Cmp = Builder.CreateICmpULT(A, B, "usub.cmp");
262 Value *Sub = Builder.CreateSub(A, B, "usub.sub");
263 Value *Zero = ConstantInt::get(Ty, 0);
264 return Builder.CreateSelect(Cmp, Zero, Sub, "usub.sat");
265}
266
267// Compute the high N bits of the 2N-bit unsigned product of two N-bit values
268// using only N-bit arithmetic, so we don't introduce a wider integer type that
269// may be unsupported in DXIL.
271 Type *Ty, unsigned BW) {
272 assert(BW % 2 == 0 && "high-half split needs symmetric halves");
273 unsigned Half = BW / 2;
274 Value *HalfShift = ConstantInt::get(Ty, Half);
275 Value *LoMask = ConstantInt::get(Ty, APInt::getLowBitsSet(BW, Half));
276
277 Value *U0 = Builder.CreateAnd(A, LoMask);
278 Value *U1 = Builder.CreateLShr(A, HalfShift);
279 Value *V0 = Builder.CreateAnd(B, LoMask);
280 Value *V1 = Builder.CreateLShr(B, HalfShift);
281
282 Value *W0 = Builder.CreateMul(U0, V0);
283 Value *T = Builder.CreateAdd(Builder.CreateMul(U1, V0),
284 Builder.CreateLShr(W0, HalfShift));
285 Value *W1 = Builder.CreateAnd(T, LoMask);
286 Value *W2 = Builder.CreateLShr(T, HalfShift);
287 W1 = Builder.CreateAdd(Builder.CreateMul(U0, V1), W1);
288 return Builder.CreateAdd(Builder.CreateAdd(Builder.CreateMul(U1, V1), W2),
289 Builder.CreateLShr(W1, HalfShift));
290}
291
292// Expand a {u,s}mul.with.overflow intrinsic. The low half of the result is a
293// plain multiply; overflow is derived from the high half of the double-width
294// product.
296 IRBuilder<> Builder(Orig);
297 Value *A = Orig->getArgOperand(0);
298 Value *B = Orig->getArgOperand(1);
299 Type *Ty = A->getType();
300 unsigned BW = Ty->getScalarSizeInBits();
301
302 Value *Lo;
303 Value *Ov;
304
305 // A plain double-width multiply is simplest, but we avoid it once it would
306 // introduce a 64-bit (or wider) integer, which DXIL does not always support.
307 // For i32 we use the native DXIL IMul/UMul ops, which return the full product
308 // as two i32s; wider types fall back to a same-width high-half computation.
309 if (2 * BW <= 32) {
310 Lo = Builder.CreateMul(A, B);
311 Type *WideTy = Ty->getWithNewBitWidth(2 * BW);
312 Value *WideA =
313 Signed ? Builder.CreateSExt(A, WideTy) : Builder.CreateZExt(A, WideTy);
314 Value *WideB =
315 Signed ? Builder.CreateSExt(B, WideTy) : Builder.CreateZExt(B, WideTy);
316 Value *Wide = Builder.CreateMul(WideA, WideB);
317 if (Signed) {
318 // Overflow when the full product doesn't fit back into BW signed bits.
319 Ov = Builder.CreateICmpNE(Wide, Builder.CreateSExt(Lo, WideTy));
320 } else {
321 Value *Hi = Builder.CreateLShr(Wide, ConstantInt::get(WideTy, BW));
322 Ov = Builder.CreateICmpNE(Hi, ConstantInt::get(WideTy, 0));
323 }
324 } else if (BW == 32) {
325 // IMul/UMul return {high, low}; index 0 is the high 32 bits.
326 Type *ResTy = StructType::get(Ty, Ty);
327 Intrinsic::ID IntrinsicID =
328 Signed ? Intrinsic::dx_imul : Intrinsic::dx_umul;
329 Value *Mul = Builder.CreateIntrinsic(ResTy, IntrinsicID, {A, B});
330 Value *Hi = Builder.CreateExtractValue(Mul, 0);
331 Lo = Builder.CreateExtractValue(Mul, 1);
332 if (Signed)
333 Ov = Builder.CreateICmpNE(
334 Hi, Builder.CreateAShr(Lo, ConstantInt::get(Ty, BW - 1)));
335 else
336 Ov = Builder.CreateICmpNE(Hi, ConstantInt::get(Ty, 0));
337 } else {
338 Lo = Builder.CreateMul(A, B);
339 Value *Hi = createMulHighUnsigned(Builder, A, B, Ty, BW);
340 if (Signed) {
341 // Turn the unsigned high half into the signed one, then overflow means it
342 // isn't the sign extension of the low half.
343 Value *SignShift = ConstantInt::get(Ty, BW - 1);
344 Value *ASign = Builder.CreateAShr(A, SignShift);
345 Value *BSign = Builder.CreateAShr(B, SignShift);
346 Hi = Builder.CreateSub(Hi, Builder.CreateAnd(ASign, B));
347 Hi = Builder.CreateSub(Hi, Builder.CreateAnd(BSign, A));
348 Ov = Builder.CreateICmpNE(Hi, Builder.CreateAShr(Lo, SignShift));
349 } else {
350 Ov = Builder.CreateICmpNE(Hi, ConstantInt::get(Ty, 0));
351 }
352 }
353
354 Value *Agg = PoisonValue::get(Orig->getType());
355 Agg = Builder.CreateInsertValue(Agg, Lo, 0);
356 return Builder.CreateInsertValue(Agg, Ov, 1);
357}
358
359static Value *expandVecReduceAdd(CallInst *Orig, Intrinsic::ID IntrinsicId) {
360 assert(IntrinsicId == Intrinsic::vector_reduce_add ||
361 IntrinsicId == Intrinsic::vector_reduce_fadd);
362
363 IRBuilder<> Builder(Orig);
364 bool IsFAdd = (IntrinsicId == Intrinsic::vector_reduce_fadd);
365
366 Value *X = Orig->getOperand(IsFAdd ? 1 : 0);
367 Type *Ty = X->getType();
368 auto *XVec = dyn_cast<FixedVectorType>(Ty);
369 unsigned XVecSize = XVec->getNumElements();
370 Value *Sum = Builder.CreateExtractElement(X, static_cast<uint64_t>(0));
371
372 // Handle the initial start value for floating-point addition.
373 if (IsFAdd) {
374 Constant *StartValue = dyn_cast<Constant>(Orig->getOperand(0));
375 if (StartValue && !StartValue->isNullValue())
376 Sum = Builder.CreateFAdd(Sum, StartValue);
377 }
378
379 // Accumulate the remaining vector elements.
380 for (unsigned I = 1; I < XVecSize; I++) {
381 Value *Elt = Builder.CreateExtractElement(X, I);
382 if (IsFAdd)
383 Sum = Builder.CreateFAdd(Sum, Elt);
384 else
385 Sum = Builder.CreateAdd(Sum, Elt);
386 }
387
388 return Sum;
389}
390
391static Value *expandAbs(CallInst *Orig) {
392 Value *X = Orig->getOperand(0);
393 IRBuilder<> Builder(Orig);
394 Type *Ty = X->getType();
395 Type *EltTy = Ty->getScalarType();
396 Constant *Zero = Ty->isVectorTy()
399 cast<FixedVectorType>(Ty)->getNumElements()),
400 ConstantInt::get(EltTy, 0))
401 : ConstantInt::get(EltTy, 0);
402 auto *V = Builder.CreateSub(Zero, X);
403 return Builder.CreateIntrinsic(Ty, Intrinsic::smax, {X, V}, nullptr,
404 "dx.max");
405}
406
407// Create appropriate DXIL float dot intrinsic for the given A and B operands
408// The appropriate opcode will be determined by the size of the operands
409// The dot product is placed in the position indicated by Orig
411 Type *ATy = A->getType();
412 [[maybe_unused]] Type *BTy = B->getType();
413 assert(ATy->isVectorTy() && BTy->isVectorTy());
414
415 IRBuilder<> Builder(Orig);
416
417 auto *AVec = dyn_cast<FixedVectorType>(ATy);
418
420
421 Intrinsic::ID DotIntrinsic = Intrinsic::dx_dot4;
422 int NumElts = AVec->getNumElements();
423 switch (NumElts) {
424 case 2:
425 DotIntrinsic = Intrinsic::dx_dot2;
426 break;
427 case 3:
428 DotIntrinsic = Intrinsic::dx_dot3;
429 break;
430 case 4:
431 DotIntrinsic = Intrinsic::dx_dot4;
432 break;
433 default:
435 "Invalid dot product input vector: length is outside 2-4");
436 return nullptr;
437 }
438
440 for (int I = 0; I < NumElts; ++I)
441 Args.push_back(Builder.CreateExtractElement(A, Builder.getInt32(I)));
442 for (int I = 0; I < NumElts; ++I)
443 Args.push_back(Builder.CreateExtractElement(B, Builder.getInt32(I)));
444 return Builder.CreateIntrinsic(ATy->getScalarType(), DotIntrinsic, Args,
445 nullptr, "dot");
446}
447
448// Create the appropriate DXIL float dot intrinsic for the operands of Orig
449// The appropriate opcode will be determined by the size of the operands
450// The dot product is placed in the position indicated by Orig
452 return expandFloatDotIntrinsic(Orig, Orig->getOperand(0),
453 Orig->getOperand(1));
454}
455
456// Expand integer dot product to multiply and add ops
458 Intrinsic::ID DotIntrinsic) {
459 assert(DotIntrinsic == Intrinsic::dx_sdot ||
460 DotIntrinsic == Intrinsic::dx_udot);
461 Value *A = Orig->getOperand(0);
462 Value *B = Orig->getOperand(1);
463 Type *ATy = A->getType();
464 [[maybe_unused]] Type *BTy = B->getType();
465 assert(ATy->isVectorTy() && BTy->isVectorTy());
466
467 IRBuilder<> Builder(Orig);
468
469 auto *AVec = dyn_cast<FixedVectorType>(ATy);
470
472
473 Value *Result;
474 Intrinsic::ID MadIntrinsic = DotIntrinsic == Intrinsic::dx_sdot
475 ? Intrinsic::dx_imad
476 : Intrinsic::dx_umad;
477 Value *Elt0 = Builder.CreateExtractElement(A, (uint64_t)0);
478 Value *Elt1 = Builder.CreateExtractElement(B, (uint64_t)0);
479 Result = Builder.CreateMul(Elt0, Elt1);
480 for (unsigned I = 1; I < AVec->getNumElements(); I++) {
481 Elt0 = Builder.CreateExtractElement(A, I);
482 Elt1 = Builder.CreateExtractElement(B, I);
483 Result = Builder.CreateIntrinsic(Result->getType(), MadIntrinsic,
484 ArrayRef<Value *>{Elt0, Elt1, Result},
485 nullptr, "dx.mad");
486 }
487 return Result;
488}
489
491 Value *X = Orig->getOperand(0);
492 IRBuilder<> Builder(Orig);
493 Type *Ty = X->getType();
494 Type *EltTy = Ty->getScalarType();
495 Constant *Log2eConst =
496 Ty->isVectorTy() ? ConstantVector::getSplat(
498 cast<FixedVectorType>(Ty)->getNumElements()),
499 ConstantFP::get(EltTy, numbers::log2ef))
500 : ConstantFP::get(EltTy, numbers::log2ef);
501 Value *NewX = Builder.CreateFMul(Log2eConst, X);
502 CallInst *Exp2Call = Builder.CreateIntrinsicWithoutFolding(
503 Ty, Intrinsic::exp2, {NewX}, nullptr, "dx.exp2");
504 Exp2Call->setTailCall(Orig->isTailCall());
505 Exp2Call->setAttributes(Orig->getAttributes());
506 return Exp2Call;
507}
508
510 Value *T = Orig->getArgOperand(1);
511 auto *TCI = dyn_cast<ConstantInt>(T);
512
513 // These FPClassTest cases have DXIL opcodes, so they will be handled in
514 // DXIL Op Lowering instead for all non f16 cases.
515 switch (TCI->getZExtValue()) {
517 return expand16BitIsInf(Orig);
519 return expand16BitIsNaN(Orig);
521 return expand16BitIsNormal(Orig);
523 return expand16BitIsFinite(Orig);
524 }
525
526 IRBuilder<> Builder(Orig);
527
528 Value *F = Orig->getArgOperand(0);
529 Type *FTy = F->getType();
530 unsigned FNumElem = 0; // 0 => F is not a vector
531
532 unsigned BitWidth; // Bit width of F or the ElemTy of F
533 Type *BitCastTy; // An IntNTy of the same bitwidth as F or ElemTy of F
534
535 if (auto *FVecTy = dyn_cast<FixedVectorType>(FTy)) {
536 Type *ElemTy = FVecTy->getElementType();
537 FNumElem = FVecTy->getNumElements();
538 BitWidth = ElemTy->getPrimitiveSizeInBits();
539 BitCastTy = FixedVectorType::get(Builder.getIntNTy(BitWidth), FNumElem);
540 } else {
542 BitCastTy = Builder.getIntNTy(BitWidth);
543 }
544
545 Value *FBitCast = Builder.CreateBitCast(F, BitCastTy);
546 switch (TCI->getZExtValue()) {
548 Value *NegZero =
549 ConstantInt::get(Builder.getIntNTy(BitWidth), 1 << (BitWidth - 1),
550 /*IsSigned=*/true);
551 Value *RetVal;
552 if (FNumElem) {
553 Value *NegZeroSplat = Builder.CreateVectorSplat(FNumElem, NegZero);
554 RetVal =
555 Builder.CreateICmpEQ(FBitCast, NegZeroSplat, "is.fpclass.negzero");
556 } else
557 RetVal = Builder.CreateICmpEQ(FBitCast, NegZero, "is.fpclass.negzero");
558 return RetVal;
559 }
560 default:
561 reportFatalUsageError("Unsupported FPClassTest");
562 }
563}
564
566 Intrinsic::ID IntrinsicId) {
567 Value *X = Orig->getOperand(0);
568 IRBuilder<> Builder(Orig);
569 Type *Ty = X->getType();
570 Type *EltTy = Ty->getScalarType();
571
572 auto ApplyOp = [&Builder](Intrinsic::ID IntrinsicId, Value *Result,
573 Value *Elt) {
574 if (IntrinsicId == Intrinsic::dx_any)
575 return Builder.CreateOr(Result, Elt);
576 assert(IntrinsicId == Intrinsic::dx_all);
577 return Builder.CreateAnd(Result, Elt);
578 };
579
580 Value *Result = nullptr;
581 if (!Ty->isVectorTy()) {
582 Result = EltTy->isFloatingPointTy()
583 ? Builder.CreateFCmpUNE(X, ConstantFP::get(EltTy, 0))
584 : Builder.CreateICmpNE(X, ConstantInt::get(EltTy, 0));
585 } else {
586 auto *XVec = dyn_cast<FixedVectorType>(Ty);
587 Value *Cond =
588 EltTy->isFloatingPointTy()
589 ? Builder.CreateFCmpUNE(
591 ElementCount::getFixed(XVec->getNumElements()),
592 ConstantFP::get(EltTy, 0)))
593 : Builder.CreateICmpNE(
595 ElementCount::getFixed(XVec->getNumElements()),
596 ConstantInt::get(EltTy, 0)));
597 Result = Builder.CreateExtractElement(Cond, (uint64_t)0);
598 for (unsigned I = 1; I < XVec->getNumElements(); I++) {
599 Value *Elt = Builder.CreateExtractElement(Cond, I);
600 Result = ApplyOp(IntrinsicId, Result, Elt);
601 }
602 }
603 return Result;
604}
605
607 float LogConstVal = numbers::ln2f) {
608 Value *X = Orig->getOperand(0);
609 IRBuilder<> Builder(Orig);
610 Type *Ty = X->getType();
611 Type *EltTy = Ty->getScalarType();
612 Constant *Ln2Const =
613 Ty->isVectorTy() ? ConstantVector::getSplat(
615 cast<FixedVectorType>(Ty)->getNumElements()),
616 ConstantFP::get(EltTy, LogConstVal))
617 : ConstantFP::get(EltTy, LogConstVal);
618 CallInst *Log2Call = Builder.CreateIntrinsicWithoutFolding(
619 Ty, Intrinsic::log2, {X}, nullptr, "elt.log2");
620 Log2Call->setTailCall(Orig->isTailCall());
621 Log2Call->setAttributes(Orig->getAttributes());
622 return Builder.CreateFMul(Ln2Const, Log2Call);
623}
627
628// Use dot product of vector operand with itself to calculate the length.
629// Divide the vector by that length to normalize it.
631 Value *X = Orig->getOperand(0);
632 Type *Ty = Orig->getType();
633 Type *EltTy = Ty->getScalarType();
634 IRBuilder<> Builder(Orig);
635
636 auto *XVec = dyn_cast<FixedVectorType>(Ty);
637 if (!XVec) {
638 if (auto *constantFP = dyn_cast<ConstantFP>(X)) {
639 const APFloat &fpVal = constantFP->getValueAPF();
640 if (fpVal.isZero())
641 reportFatalUsageError("Invalid input scalar: length is zero");
642 }
643 return Builder.CreateFDiv(X, X);
644 }
645
646 Value *DotProduct = expandFloatDotIntrinsic(Orig, X, X);
647
648 // verify that the length is non-zero
649 // (if the dot product is non-zero, then the length is non-zero)
650 if (auto *constantFP = dyn_cast<ConstantFP>(DotProduct)) {
651 const APFloat &fpVal = constantFP->getValueAPF();
652 if (fpVal.isZero())
653 reportFatalUsageError("Invalid input vector: length is zero");
654 }
655
656 Value *Multiplicand = Builder.CreateIntrinsic(EltTy, Intrinsic::dx_rsqrt,
657 ArrayRef<Value *>{DotProduct},
658 nullptr, "dx.rsqrt");
659
660 Value *MultiplicandVec =
661 Builder.CreateVectorSplat(XVec->getNumElements(), Multiplicand);
662 return Builder.CreateFMul(X, MultiplicandVec);
663}
664
666 Value *Y = Orig->getOperand(0);
667 Value *X = Orig->getOperand(1);
668 Type *Ty = X->getType();
669 IRBuilder<> Builder(Orig);
670 Builder.setFastMathFlags(Orig->getFastMathFlags());
671
672 Value *Tan = Builder.CreateFDiv(Y, X);
673
674 CallInst *Atan = Builder.CreateIntrinsicWithoutFolding(
675 Ty, Intrinsic::atan, {Tan}, nullptr, "Elt.Atan");
676 Atan->setTailCall(Orig->isTailCall());
677 Atan->setAttributes(Orig->getAttributes());
678
679 // Modify atan result based on https://en.wikipedia.org/wiki/Atan2.
680 Constant *Pi = ConstantFP::get(Ty, llvm::numbers::pi);
681 Constant *HalfPi = ConstantFP::get(Ty, llvm::numbers::pi / 2);
682 Constant *NegHalfPi = ConstantFP::get(Ty, -llvm::numbers::pi / 2);
683 Constant *Zero = ConstantFP::get(Ty, 0);
684 Value *AtanAddPi = Builder.CreateFAdd(Atan, Pi);
685 Value *AtanSubPi = Builder.CreateFSub(Atan, Pi);
686
687 // x > 0 -> atan.
688 Value *Result = Atan;
689 Value *XLt0 = Builder.CreateFCmpOLT(X, Zero);
690 Value *XEq0 = Builder.CreateFCmpOEQ(X, Zero);
691 Value *YGe0 = Builder.CreateFCmpOGE(Y, Zero);
692 Value *YLt0 = Builder.CreateFCmpOLT(Y, Zero);
693
694 // x < 0, y >= 0 -> atan + pi.
695 Value *XLt0AndYGe0 = Builder.CreateAnd(XLt0, YGe0);
696 Result = Builder.CreateSelect(XLt0AndYGe0, AtanAddPi, Result);
697
698 // x < 0, y < 0 -> atan - pi.
699 Value *XLt0AndYLt0 = Builder.CreateAnd(XLt0, YLt0);
700 Result = Builder.CreateSelect(XLt0AndYLt0, AtanSubPi, Result);
701
702 // x == 0, y < 0 -> -pi/2
703 Value *XEq0AndYLt0 = Builder.CreateAnd(XEq0, YLt0);
704 Result = Builder.CreateSelect(XEq0AndYLt0, NegHalfPi, Result);
705
706 // x == 0, y > 0 -> pi/2
707 Value *XEq0AndYGe0 = Builder.CreateAnd(XEq0, YGe0);
708 Result = Builder.CreateSelect(XEq0AndYGe0, HalfPi, Result);
709
710 return Result;
711}
712
713template <bool LeftFunnel>
715 Type *Ty = Orig->getType();
716 Value *A = Orig->getOperand(0);
717 Value *B = Orig->getOperand(1);
718 Value *Shift = Orig->getOperand(2);
719
720 IRBuilder<> Builder(Orig);
721
722 unsigned BitWidth = Ty->getScalarSizeInBits();
724 "Can't use Mask to compute modulo and inverse");
725
726 // Note: if (Shift % BitWidth) == 0 then (BitWidth - Shift) == BitWidth,
727 // shifting by the bitwidth for shl/lshr returns a poisoned result. As such,
728 // we implement the same formula as LegalizerHelper::lowerFunnelShiftAsShifts.
729 //
730 // The funnel shift is expanded like so:
731 // fshl
732 // -> msb_extract((concat(A, B) << (Shift % BitWidth)), BitWidth)
733 // -> A << (Shift % BitWidth) | B >> 1 >> (BitWidth - 1 - (Shift % BitWidth))
734 // fshr
735 // -> lsb_extract((concat(A, B) >> (Shift % BitWidth), BitWidth))
736 // -> A << 1 << (BitWidth - 1 - (Shift % BitWidth)) | B >> (Shift % BitWidth)
737
738 // (BitWidth - 1) -> Mask
739 Constant *Mask = ConstantInt::get(Ty, Ty->getScalarSizeInBits() - 1);
740
741 // Shift % BitWidth
742 // -> Shift & (BitWidth - 1)
743 // -> Shift & Mask
744 Value *MaskedShift = Builder.CreateAnd(Shift, Mask);
745
746 // (BitWidth - 1) - (Shift % BitWidth)
747 // -> ~Shift & (BitWidth - 1)
748 // -> ~Shift & Mask
749 Value *NotShift = Builder.CreateNot(Shift);
750 Value *InverseShift = Builder.CreateAnd(NotShift, Mask);
751
752 Constant *One = ConstantInt::get(Ty, 1);
753 Value *ShiftedA;
754 Value *ShiftedB;
755
756 if (LeftFunnel) {
757 ShiftedA = Builder.CreateShl(A, MaskedShift);
758 Value *ShiftB1 = Builder.CreateLShr(B, One);
759 ShiftedB = Builder.CreateLShr(ShiftB1, InverseShift);
760 } else {
761 Value *ShiftA1 = Builder.CreateShl(A, One);
762 ShiftedA = Builder.CreateShl(ShiftA1, InverseShift);
763 ShiftedB = Builder.CreateLShr(B, MaskedShift);
764 }
765
766 Value *Result = Builder.CreateOr(ShiftedA, ShiftedB);
767 return Result;
768}
769
770static Value *expandPowIntrinsic(CallInst *Orig, Intrinsic::ID IntrinsicId) {
771
772 Value *X = Orig->getOperand(0);
773 Value *Y = Orig->getOperand(1);
774 Type *Ty = X->getType();
775 IRBuilder<> Builder(Orig);
776
777 if (IntrinsicId == Intrinsic::powi)
778 Y = Builder.CreateSIToFP(Y, Ty);
779
780 Value *Log2Call =
781 Builder.CreateIntrinsic(Ty, Intrinsic::log2, {X}, nullptr, "elt.log2");
782 auto *Mul = Builder.CreateFMul(Log2Call, Y);
783 CallInst *Exp2Call = Builder.CreateIntrinsicWithoutFolding(
784 Ty, Intrinsic::exp2, {Mul}, nullptr, "elt.exp2");
785 Exp2Call->setTailCall(Orig->isTailCall());
786 Exp2Call->setAttributes(Orig->getAttributes());
787 return Exp2Call;
788}
789
790static bool expandBufferLoadIntrinsic(CallInst *Orig, bool IsRaw) {
791 IRBuilder<> Builder(Orig);
792
793 Type *BufferTy = Orig->getType()->getStructElementType(0);
794 Type *ScalarTy = BufferTy->getScalarType();
795 bool IsDouble = ScalarTy->isDoubleTy();
796 assert(IsDouble || ScalarTy->isIntegerTy(64) &&
797 "Only expand double or int64 scalars or vectors");
798 bool IsVector = false;
799 unsigned ExtractNum = 2;
800 if (auto *VT = dyn_cast<FixedVectorType>(BufferTy)) {
801 ExtractNum = 2 * VT->getNumElements();
802 IsVector = true;
803 assert(IsRaw || ExtractNum == 4 && "TypedBufferLoad vector must be size 2");
804 }
805
807 Value *Result = PoisonValue::get(BufferTy);
808 unsigned Base = 0;
809 // If we need to extract more than 4 i32; we need to break it up into
810 // more than one load. LoadNum tells us how many i32s we are loading in
811 // each load
812 while (ExtractNum > 0) {
813 unsigned LoadNum = std::min(ExtractNum, 4u);
814 Type *Ty = VectorType::get(Builder.getInt32Ty(), LoadNum, false);
815
816 Type *LoadType = StructType::get(Ty, Builder.getInt1Ty());
817 Intrinsic::ID LoadIntrinsic = Intrinsic::dx_resource_load_typedbuffer;
818 SmallVector<Value *, 3> Args = {Orig->getOperand(0), Orig->getOperand(1)};
819 if (IsRaw) {
820 LoadIntrinsic = Intrinsic::dx_resource_load_rawbuffer;
821 Value *Tmp = Builder.getInt32(4 * Base * 2);
822 Args.push_back(Builder.CreateAdd(Orig->getOperand(2), Tmp));
823 }
824
825 Value *Load = Builder.CreateIntrinsic(LoadType, LoadIntrinsic, Args);
826 Loads.push_back(Load);
827
828 // extract the buffer load's result
829 Value *Extract = Builder.CreateExtractValue(Load, {0});
830
831 SmallVector<Value *> ExtractElements;
832 for (unsigned I = 0; I < LoadNum; ++I)
833 ExtractElements.push_back(
834 Builder.CreateExtractElement(Extract, Builder.getInt32(I)));
835
836 // combine into double(s) or int64(s)
837 for (unsigned I = 0; I < LoadNum; I += 2) {
838 Value *Combined = nullptr;
839 if (IsDouble)
840 // For doubles, use dx_asdouble intrinsic
841 Combined = Builder.CreateIntrinsic(
842 Builder.getDoubleTy(), Intrinsic::dx_asdouble,
843 {ExtractElements[I], ExtractElements[I + 1]});
844 else {
845 // For int64, manually combine two int32s
846 // First, zero-extend both values to i64
847 Value *Lo =
848 Builder.CreateZExt(ExtractElements[I], Builder.getInt64Ty());
849 Value *Hi =
850 Builder.CreateZExt(ExtractElements[I + 1], Builder.getInt64Ty());
851 // Shift the high bits left by 32 bits
852 Value *ShiftedHi = Builder.CreateShl(Hi, Builder.getInt64(32));
853 // OR the high and low bits together
854 Combined = Builder.CreateOr(Lo, ShiftedHi);
855 }
856
857 if (IsVector)
858 Result = Builder.CreateInsertElement(Result, Combined,
859 Builder.getInt32((I / 2) + Base));
860 else
861 Result = Combined;
862 }
863
864 ExtractNum -= LoadNum;
865 Base += LoadNum / 2;
866 }
867
868 Value *CheckBit = nullptr;
869 for (User *U : make_early_inc_range(Orig->users())) {
870 // If it's not a ExtractValueInst, we don't know how to
871 // handle it
872 auto *EVI = dyn_cast<ExtractValueInst>(U);
873 if (!EVI)
874 llvm_unreachable("Unexpected user of typedbufferload");
875
876 ArrayRef<unsigned> Indices = EVI->getIndices();
877 assert(Indices.size() == 1);
878
879 if (Indices[0] == 0) {
880 // Use of the value(s)
881 EVI->replaceAllUsesWith(Result);
882 } else {
883 // Use of the check bit
884 assert(Indices[0] == 1 && "Unexpected type for typedbufferload");
885 // Note: This does not always match the historical behaviour of DXC.
886 // See https://github.com/microsoft/DirectXShaderCompiler/issues/7622
887 if (!CheckBit) {
888 SmallVector<Value *, 2> CheckBits;
889 for (Value *L : Loads)
890 CheckBits.push_back(Builder.CreateExtractValue(L, {1}));
891 CheckBit = Builder.CreateAnd(CheckBits);
892 }
893 EVI->replaceAllUsesWith(CheckBit);
894 }
895 EVI->eraseFromParent();
896 }
897 Orig->eraseFromParent();
898 return true;
899}
900
901static bool expandBufferStoreIntrinsic(CallInst *Orig, bool IsRaw) {
902 IRBuilder<> Builder(Orig);
903
904 unsigned ValIndex = IsRaw ? 3 : 2;
905 Type *BufferTy = Orig->getFunctionType()->getParamType(ValIndex);
906 Type *ScalarTy = BufferTy->getScalarType();
907 bool IsDouble = ScalarTy->isDoubleTy();
908 assert((IsDouble || ScalarTy->isIntegerTy(64)) &&
909 "Only expand double or int64 scalars or vectors");
910
911 // Determine if we're dealing with a vector or scalar
912 bool IsVector = false;
913 unsigned ExtractNum = 2;
914 unsigned VecLen = 0;
915 if (auto *VT = dyn_cast<FixedVectorType>(BufferTy)) {
916 VecLen = VT->getNumElements();
917 assert(IsRaw || VecLen == 2 && "TypedBufferStore vector must be size 2");
918 ExtractNum = VecLen * 2;
919 IsVector = true;
920 }
921
922 // Create the appropriate vector type for the result
923 Type *Int32Ty = Builder.getInt32Ty();
924 Type *ResultTy = VectorType::get(Int32Ty, ExtractNum, false);
925 Value *Val = PoisonValue::get(ResultTy);
926
927 Type *SplitElementTy = Int32Ty;
928 if (IsVector)
929 SplitElementTy = VectorType::get(SplitElementTy, VecLen, false);
930
931 Value *LowBits = nullptr;
932 Value *HighBits = nullptr;
933 // Split the 64-bit values into 32-bit components
934 if (IsDouble) {
935 auto *SplitTy = llvm::StructType::get(SplitElementTy, SplitElementTy);
936 Value *Split = Builder.CreateIntrinsic(SplitTy, Intrinsic::dx_splitdouble,
937 {Orig->getOperand(ValIndex)});
938 LowBits = Builder.CreateExtractValue(Split, 0);
939 HighBits = Builder.CreateExtractValue(Split, 1);
940 } else {
941 // Handle int64 type(s)
942 Value *InputVal = Orig->getOperand(ValIndex);
943 Constant *ShiftAmt = Builder.getInt64(32);
944 if (IsVector)
945 ShiftAmt =
947
948 // Split into low and high 32-bit parts
949 LowBits = Builder.CreateTrunc(InputVal, SplitElementTy);
950 Value *ShiftedVal = Builder.CreateLShr(InputVal, ShiftAmt);
951 HighBits = Builder.CreateTrunc(ShiftedVal, SplitElementTy);
952 }
953
954 if (IsVector) {
956 for (unsigned I = 0; I < VecLen; ++I) {
957 Mask.push_back(I);
958 Mask.push_back(I + VecLen);
959 }
960 Val = Builder.CreateShuffleVector(LowBits, HighBits, Mask);
961 } else {
962 Val = Builder.CreateInsertElement(Val, LowBits, Builder.getInt32(0));
963 Val = Builder.CreateInsertElement(Val, HighBits, Builder.getInt32(1));
964 }
965
966 // If we need to extract more than 4 i32; we need to break it up into
967 // more than one store. StoreNum tells us how many i32s we are storing in
968 // each store
969 unsigned Base = 0;
970 while (ExtractNum > 0) {
971 unsigned StoreNum = std::min(ExtractNum, 4u);
972
973 Intrinsic::ID StoreIntrinsic = Intrinsic::dx_resource_store_typedbuffer;
974 SmallVector<Value *, 4> Args = {Orig->getOperand(0), Orig->getOperand(1)};
975 if (IsRaw) {
976 StoreIntrinsic = Intrinsic::dx_resource_store_rawbuffer;
977 Value *Tmp = Builder.getInt32(4 * Base);
978 Args.push_back(Builder.CreateAdd(Orig->getOperand(2), Tmp));
979 }
980
982 for (unsigned I = 0; I < StoreNum; ++I) {
983 Mask.push_back(Base + I);
984 }
985
986 Value *SubVal = Val;
987 if (VecLen > 2)
988 SubVal = Builder.CreateShuffleVector(Val, Mask);
989
990 Args.push_back(SubVal);
991 // Create the final intrinsic call
992 Builder.CreateIntrinsic(Builder.getVoidTy(), StoreIntrinsic, Args);
993
994 ExtractNum -= StoreNum;
995 Base += StoreNum;
996 }
997 Orig->eraseFromParent();
998 return true;
999}
1000
1002 if (ClampIntrinsic == Intrinsic::dx_uclamp)
1003 return Intrinsic::umax;
1004 if (ClampIntrinsic == Intrinsic::dx_sclamp)
1005 return Intrinsic::smax;
1006 assert(ClampIntrinsic == Intrinsic::dx_nclamp);
1007 return Intrinsic::maxnum;
1008}
1009
1011 if (ClampIntrinsic == Intrinsic::dx_uclamp)
1012 return Intrinsic::umin;
1013 if (ClampIntrinsic == Intrinsic::dx_sclamp)
1014 return Intrinsic::smin;
1015 assert(ClampIntrinsic == Intrinsic::dx_nclamp);
1016 return Intrinsic::minnum;
1017}
1018
1020 Intrinsic::ID ClampIntrinsic) {
1021 Value *X = Orig->getOperand(0);
1022 Value *Min = Orig->getOperand(1);
1023 Value *Max = Orig->getOperand(2);
1024 Type *Ty = X->getType();
1025 IRBuilder<> Builder(Orig);
1026 auto *MaxCall = Builder.CreateIntrinsic(Ty, getMaxForClamp(ClampIntrinsic),
1027 {X, Min}, nullptr, "dx.max");
1028 return Builder.CreateIntrinsic(Ty, getMinForClamp(ClampIntrinsic),
1029 {MaxCall, Max}, nullptr, "dx.min");
1030}
1031
1033 Value *X = Orig->getOperand(0);
1034 Type *Ty = X->getType();
1035 Type *ScalarTy = Ty->getScalarType();
1036 Type *RetTy = Orig->getType();
1037 Constant *Zero = Constant::getNullValue(Ty);
1038
1039 IRBuilder<> Builder(Orig);
1040
1041 Value *GT;
1042 Value *LT;
1043 if (ScalarTy->isFloatingPointTy()) {
1044 GT = Builder.CreateFCmpOLT(Zero, X);
1045 LT = Builder.CreateFCmpOLT(X, Zero);
1046 } else {
1047 assert(ScalarTy->isIntegerTy());
1048 GT = Builder.CreateICmpSLT(Zero, X);
1049 LT = Builder.CreateICmpSLT(X, Zero);
1050 }
1051
1052 Value *ZextGT = Builder.CreateZExt(GT, RetTy);
1053 Value *ZextLT = Builder.CreateZExt(LT, RetTy);
1054
1055 return Builder.CreateSub(ZextGT, ZextLT);
1056}
1057
1058// Expand llvm.matrix.multiply by extracting row/column vectors and computing
1059// dot products.
1060// Result[r,c] = dot(row_r(LHS), col_c(RHS))
1061// Element (r,c) is at index c*NumRows + r (column-major).
1063 Value *LHS = Orig->getArgOperand(0);
1064 Value *RHS = Orig->getArgOperand(1);
1065 unsigned LHSRows = cast<ConstantInt>(Orig->getArgOperand(2))->getZExtValue();
1066 unsigned LHSCols = cast<ConstantInt>(Orig->getArgOperand(3))->getZExtValue();
1067 unsigned RHSCols = cast<ConstantInt>(Orig->getArgOperand(4))->getZExtValue();
1068
1069 auto *RetTy = cast<FixedVectorType>(Orig->getType());
1070 Type *EltTy = RetTy->getElementType();
1071 bool IsFP = EltTy->isFloatingPointTy();
1072
1073 IRBuilder<> Builder(Orig);
1074
1075 // Column-major indexing:
1076 // LHS row R, element K: index = K * LHSRows + R
1077 // RHS col C, element K: index = C * LHSCols + K
1078 Value *Result = PoisonValue::get(RetTy);
1079
1080 // Extract all scalar elements from LHS and RHS once, then reuse them.
1081 unsigned LHSSize = LHSRows * LHSCols;
1082 unsigned RHSSize = LHSCols * RHSCols;
1083 SmallVector<Value *, 16> LHSElts(LHSSize);
1084 SmallVector<Value *, 16> RHSElts(RHSSize);
1085 for (unsigned I = 0; I < LHSSize; ++I)
1086 LHSElts[I] = Builder.CreateExtractElement(LHS, I);
1087 for (unsigned I = 0; I < RHSSize; ++I)
1088 RHSElts[I] = Builder.CreateExtractElement(RHS, I);
1089
1090 // Choose the appropriate scalar-arg dot intrinsic for floats.
1091 // K=1 and double types use scalar expansion instead.
1093 bool UseScalarFP = IsFP && (EltTy->isDoubleTy() || LHSCols == 1);
1094 if (IsFP && !UseScalarFP) {
1095 switch (LHSCols) {
1096 case 2:
1097 FloatDotID = Intrinsic::dx_dot2;
1098 break;
1099 case 3:
1100 FloatDotID = Intrinsic::dx_dot3;
1101 break;
1102 case 4:
1103 FloatDotID = Intrinsic::dx_dot4;
1104 break;
1105 default:
1107 "Invalid matrix inner dimension for dot product: must be 2-4");
1108 return nullptr;
1109 }
1110 }
1111
1112 for (unsigned C = 0; C < RHSCols; ++C) {
1113 for (unsigned R = 0; R < LHSRows; ++R) {
1114 // Gather row R from LHS and column C from RHS.
1115 SmallVector<Value *, 4> RowElts, ColElts;
1116 for (unsigned K = 0; K < LHSCols; ++K) {
1117 RowElts.push_back(LHSElts[K * LHSRows + R]);
1118 ColElts.push_back(RHSElts[C * LHSCols + K]);
1119 }
1120
1121 Value *Dot;
1122 if (UseScalarFP) {
1123 // Scalar fmul+fmuladd expansion for double types and K=1.
1124 Dot = Builder.CreateFMul(RowElts[0], ColElts[0]);
1125 for (unsigned K = 1; K < LHSCols; ++K)
1126 Dot = Builder.CreateIntrinsic(EltTy, Intrinsic::fmuladd,
1127 {RowElts[K], ColElts[K], Dot});
1128 } else if (IsFP) {
1129 // Emit scalar-arg DXIL dot directly (dx.dot2/dx.dot3/dx.dot4).
1131 Args.append(RowElts.begin(), RowElts.end());
1132 Args.append(ColElts.begin(), ColElts.end());
1133 Dot = Builder.CreateIntrinsic(EltTy, FloatDotID, Args);
1134 } else {
1135 // Integer: emit multiply + imad chain.
1136 Dot = Builder.CreateMul(RowElts[0], ColElts[0]);
1137 for (unsigned K = 1; K < LHSCols; ++K)
1138 Dot = Builder.CreateIntrinsic(EltTy, Intrinsic::dx_imad,
1139 {RowElts[K], ColElts[K], Dot});
1140 }
1141 unsigned ResIdx = C * LHSRows + R;
1142 Result = Builder.CreateInsertElement(Result, Dot, ResIdx);
1143 }
1144 }
1145 return Result;
1146}
1147
1148// Expand llvm.matrix.transpose as a shufflevector that permutes elements
1149// from column-major source to column-major transposed layout.
1150// Element (r,c) at index c*Rows + r moves to index r*Cols + c.
1152 Value *Mat = Orig->getArgOperand(0);
1153 unsigned Rows = cast<ConstantInt>(Orig->getArgOperand(1))->getZExtValue();
1154 unsigned Cols = cast<ConstantInt>(Orig->getArgOperand(2))->getZExtValue();
1155
1156 unsigned NumElts = Rows * Cols;
1157 SmallVector<int, 16> Mask(NumElts);
1158 for (unsigned I = 0; I < NumElts; ++I)
1159 Mask[I] = (I % Cols) * Rows + (I / Cols);
1160
1161 IRBuilder<> Builder(Orig);
1162 return Builder.CreateShuffleVector(Mat, Mask);
1163}
1164
1165// Scalarize a vector int_dx_store_output call into per-component scalar calls.
1166// The DXIL StoreOutput op is per-component; vector intrinsics are split here
1167// so that DXILOpLowering sees only scalar variants.
1168static bool expandStoreOutput(CallInst *Orig) {
1169 auto *VT = dyn_cast<FixedVectorType>(Orig->getArgOperand(3)->getType());
1170 if (!VT)
1171 return false; // already scalar, nothing to expand
1172
1173 IRBuilder<> Builder(Orig);
1174 Module *M = Orig->getModule();
1175 Type *Int8Ty = Builder.getInt8Ty();
1176 Type *Int32Ty = Builder.getInt32Ty();
1177 Type *ScalarTy = VT->getElementType();
1178 unsigned NumElems = VT->getNumElements();
1179
1180 Value *SigElementId = Orig->getArgOperand(0);
1181 Value *RowIndex = Orig->getArgOperand(1);
1182 Value *StartCol = Orig->getArgOperand(2); // i8
1183 Value *Data = Orig->getArgOperand(3);
1184 Value *StartColI32 = Builder.CreateZExt(StartCol, Int32Ty);
1185
1187 M, Intrinsic::dx_store_output, {ScalarTy});
1188
1189 for (unsigned I = 0; I < NumElems; ++I) {
1190 Value *Scalar =
1191 Builder.CreateExtractElement(Data, ConstantInt::get(Int32Ty, I));
1192 Value *ColIdx =
1193 Builder.CreateAdd(StartColI32, ConstantInt::get(Int32Ty, I));
1194 Value *ColI8 = Builder.CreateTrunc(ColIdx, Int8Ty);
1195 Builder.CreateCall(ScalarFn, {SigElementId, RowIndex, ColI8, Scalar});
1196 }
1197
1198 Orig->eraseFromParent();
1199 return true;
1200}
1201
1202// Scalarize a vector int_dx_load_input call into per-component scalar calls
1203// and reassemble the vector. The DXIL LoadInput op is per-component.
1205 auto *VT = dyn_cast<FixedVectorType>(Orig->getType());
1206 if (!VT)
1207 return nullptr; // already scalar, nothing to expand
1208
1209 IRBuilder<> Builder(Orig);
1210 Module *M = Orig->getModule();
1211 Type *Int8Ty = Builder.getInt8Ty();
1212 Type *Int32Ty = Builder.getInt32Ty();
1213 Type *ScalarTy = VT->getElementType();
1214 unsigned NumElems = VT->getNumElements();
1215
1216 Value *SigElementId = Orig->getArgOperand(0);
1217 Value *RowIndex = Orig->getArgOperand(1);
1218 Value *StartCol = Orig->getArgOperand(2); // i8
1219 Value *GsVertexOrPrimIndex = Orig->getArgOperand(3);
1220 Value *StartColI32 = Builder.CreateZExt(StartCol, Int32Ty);
1221
1223 M, Intrinsic::dx_load_input, {ScalarTy});
1224
1225 Value *Vec = PoisonValue::get(VT);
1226 for (unsigned I = 0; I < NumElems; ++I) {
1227 Value *ColIdx =
1228 Builder.CreateAdd(StartColI32, ConstantInt::get(Int32Ty, I));
1229 Value *ColI8 = Builder.CreateTrunc(ColIdx, Int8Ty);
1230 Value *Scalar = Builder.CreateCall(
1231 ScalarFn, {SigElementId, RowIndex, ColI8, GsVertexOrPrimIndex});
1232 Vec =
1233 Builder.CreateInsertElement(Vec, Scalar, ConstantInt::get(Int32Ty, I));
1234 }
1235
1236 return Vec;
1237}
1238
1239static bool expandIntrinsic(Function &F, CallInst *Orig) {
1240 Value *Result = nullptr;
1241 Intrinsic::ID IntrinsicId = F.getIntrinsicID();
1242 switch (IntrinsicId) {
1243 case Intrinsic::abs:
1244 Result = expandAbs(Orig);
1245 break;
1246 case Intrinsic::assume:
1247 Orig->eraseFromParent();
1248 return true;
1249 case Intrinsic::atan2:
1250 Result = expandAtan2Intrinsic(Orig);
1251 break;
1252 case Intrinsic::fshl:
1253 Result = expandFunnelShiftIntrinsic<true>(Orig);
1254 break;
1255 case Intrinsic::fshr:
1256 Result = expandFunnelShiftIntrinsic<false>(Orig);
1257 break;
1258 case Intrinsic::exp:
1259 Result = expandExpIntrinsic(Orig);
1260 break;
1261 case Intrinsic::is_fpclass:
1262 Result = expandIsFPClass(Orig);
1263 break;
1264 case Intrinsic::log:
1265 Result = expandLogIntrinsic(Orig);
1266 break;
1267 case Intrinsic::log10:
1268 Result = expandLog10Intrinsic(Orig);
1269 break;
1270 case Intrinsic::pow:
1271 case Intrinsic::powi:
1272 Result = expandPowIntrinsic(Orig, IntrinsicId);
1273 break;
1274 case Intrinsic::dx_all:
1275 case Intrinsic::dx_any:
1276 Result = expandAnyOrAllIntrinsic(Orig, IntrinsicId);
1277 break;
1278 case Intrinsic::dx_uclamp:
1279 case Intrinsic::dx_sclamp:
1280 case Intrinsic::dx_nclamp:
1281 Result = expandClampIntrinsic(Orig, IntrinsicId);
1282 break;
1283 case Intrinsic::dx_isinf:
1284 Result = expand16BitIsInf(Orig);
1285 break;
1286 case Intrinsic::dx_isnan:
1287 Result = expand16BitIsNaN(Orig);
1288 break;
1289 case Intrinsic::dx_normalize:
1290 Result = expandNormalizeIntrinsic(Orig);
1291 break;
1292 case Intrinsic::dx_fdot:
1293 Result = expandFloatDotIntrinsic(Orig);
1294 break;
1295 case Intrinsic::dx_sdot:
1296 case Intrinsic::dx_udot:
1297 Result = expandIntegerDotIntrinsic(Orig, IntrinsicId);
1298 break;
1299 case Intrinsic::dx_sign:
1300 Result = expandSignIntrinsic(Orig);
1301 break;
1302 case Intrinsic::dx_load_input:
1303 Result = expandLoadInput(Orig);
1304 break;
1305 case Intrinsic::dx_store_output:
1306 if (expandStoreOutput(Orig))
1307 return true;
1308 break;
1309 case Intrinsic::dx_resource_load_rawbuffer:
1310 if (expandBufferLoadIntrinsic(Orig, /*IsRaw*/ true))
1311 return true;
1312 break;
1313 case Intrinsic::dx_resource_store_rawbuffer:
1314 if (expandBufferStoreIntrinsic(Orig, /*IsRaw*/ true))
1315 return true;
1316 break;
1317 case Intrinsic::dx_resource_load_typedbuffer:
1318 if (expandBufferLoadIntrinsic(Orig, /*IsRaw*/ false))
1319 return true;
1320 break;
1321 case Intrinsic::dx_resource_store_typedbuffer:
1322 if (expandBufferStoreIntrinsic(Orig, /*IsRaw*/ false))
1323 return true;
1324 break;
1325 case Intrinsic::usub_sat:
1326 Result = expandUsubSat(Orig);
1327 break;
1328 case Intrinsic::umul_with_overflow:
1329 case Intrinsic::smul_with_overflow:
1330 Result = expandMulWithOverflow(Orig, /*Signed=*/IntrinsicId ==
1331 Intrinsic::smul_with_overflow);
1332 break;
1333 case Intrinsic::vector_reduce_add:
1334 case Intrinsic::vector_reduce_fadd:
1335 Result = expandVecReduceAdd(Orig, IntrinsicId);
1336 break;
1337 case Intrinsic::matrix_multiply:
1338 Result = expandMatrixMultiply(Orig);
1339 break;
1340 case Intrinsic::matrix_transpose:
1341 Result = expandMatrixTranspose(Orig);
1342 break;
1343 }
1344 if (Result) {
1345 Orig->replaceAllUsesWith(Result);
1346 Orig->eraseFromParent();
1347 return true;
1348 }
1349 return false;
1350}
1351
1353 for (auto &F : make_early_inc_range(M.functions())) {
1354 if (!isIntrinsicExpansion(F))
1355 continue;
1356 bool IntrinsicExpanded = false;
1357 for (User *U : make_early_inc_range(F.users())) {
1358 auto *IntrinsicCall = dyn_cast<CallInst>(U);
1359 if (!IntrinsicCall)
1360 continue;
1361 IntrinsicExpanded = expandIntrinsic(F, IntrinsicCall);
1362 }
1363 if (F.user_empty() && IntrinsicExpanded)
1364 F.eraseFromParent();
1365 }
1366 return true;
1367}
1368
1375
1379
1381
1383 "DXIL Intrinsic Expansion", false, false)
1385 "DXIL Intrinsic Expansion", false, false)
1386
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 * 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 * 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 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 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