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