LLVM 24.0.0git
AMDGPUCodeGenPrepare.cpp
Go to the documentation of this file.
1//===-- AMDGPUCodeGenPrepare.cpp ------------------------------------------===//
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
10/// This pass does misc. AMDGPU optimizations on IR before instruction
11/// selection.
12//
13//===----------------------------------------------------------------------===//
14
15#include "AMDGPU.h"
16#include "AMDGPUMemoryUtils.h"
17#include "AMDGPUTargetMachine.h"
26#include "llvm/IR/Dominators.h"
27#include "llvm/IR/IRBuilder.h"
28#include "llvm/IR/InstVisitor.h"
29#include "llvm/IR/IntrinsicsAMDGPU.h"
32#include "llvm/Pass.h"
39
40#define DEBUG_TYPE "amdgpu-codegenprepare"
41
42using namespace llvm;
43using namespace llvm::PatternMatch;
44
45namespace {
46
47class AMDGPUCodeGenPrepareImpl
48 : public InstVisitor<AMDGPUCodeGenPrepareImpl, bool> {
49public:
50 const AMDGPUOptions &CLOpts;
51 Function &F;
52 const GCNSubtarget &ST;
53 const AMDGPUTargetMachine &TM;
56 const UniformityInfo &UA;
57 const DataLayout &DL;
59 const bool HasFP32DenormalFlush;
60 const bool ExpandDiv64InIR;
61 bool FlowChanged = false;
62 mutable Function *SqrtF32 = nullptr;
63 mutable Function *LdexpF32 = nullptr;
64 mutable SmallVector<WeakVH> DeadVals;
65
66 DenseMap<const PHINode *, bool> BreakPhiNodesCache;
67
68 AMDGPUCodeGenPrepareImpl(Function &F, const AMDGPUTargetMachine &TM,
71 const DominatorTree *DT, const UniformityInfo &UA,
72 bool ExpandDiv64InIR)
73 : CLOpts(TM.getCLOpts()), F(F), ST(TM.getSubtarget<GCNSubtarget>(F)),
74 TM(TM), TTI(TTI), TLI(TLI), UA(UA), DL(F.getDataLayout()),
75 SQ(DL, TLI, DT, AC),
76 HasFP32DenormalFlush(SIModeRegisterDefaults(F, ST).FP32Denormals ==
78 ExpandDiv64InIR(ExpandDiv64InIR) {}
79
80 Function *getSqrtF32() const {
81 if (SqrtF32)
82 return SqrtF32;
83
84 LLVMContext &Ctx = F.getContext();
86 F.getParent(), Intrinsic::amdgcn_sqrt, {Type::getFloatTy(Ctx)});
87 return SqrtF32;
88 }
89
90 Function *getLdexpF32() const {
91 if (LdexpF32)
92 return LdexpF32;
93
94 LLVMContext &Ctx = F.getContext();
96 F.getParent(), Intrinsic::ldexp,
97 {Type::getFloatTy(Ctx), Type::getInt32Ty(Ctx)});
98 return LdexpF32;
99 }
100
101 bool canBreakPHINode(const PHINode &I);
102
103 /// Return true if \p T is a legal scalar floating point type.
104 bool isLegalFloatingTy(const Type *T) const;
105
106 /// Wrapper to pass all the arguments to computeKnownFPClass
108 const Instruction *CtxI) const {
109 return llvm::computeKnownFPClass(V, Interested,
110 SQ.getWithInstruction(CtxI));
111 }
112
113 bool canIgnoreDenormalInput(const Value *V, const Instruction *CtxI) const {
114 return HasFP32DenormalFlush ||
116 }
117
118 /// \returns The minimum number of bits needed to store the value of \Op as an
119 /// unsigned integer. Truncating to this size and then zero-extending to
120 /// the original will not change the value.
121 unsigned numBitsUnsigned(Value *Op, const Instruction *CtxI) const;
122
123 /// \returns The minimum number of bits needed to store the value of \Op as a
124 /// signed integer. Truncating to this size and then sign-extending to
125 /// the original size will not change the value.
126 unsigned numBitsSigned(Value *Op, const Instruction *CtxI) const;
127
128 /// Replace mul instructions with llvm.amdgcn.mul.u24 or llvm.amdgcn.mul.s24.
129 /// SelectionDAG has an issue where an and asserting the bits are known
130 bool replaceMulWithMul24(BinaryOperator &I) const;
131
132 /// Perform same function as equivalently named function in DAGCombiner. Since
133 /// we expand some divisions here, we need to perform this before obscuring.
134 bool foldBinOpIntoSelect(BinaryOperator &I) const;
135
136 /// Fold select (X == 0 || Y == 0), +0.0, X * Y into fmul_legacy(X, Y).
137 bool foldSelectToFMulLegacy(SelectInst &I) const;
138
139 bool divHasSpecialOptimization(BinaryOperator &I,
140 Value *Num, Value *Den) const;
141 unsigned getDivNumBits(BinaryOperator &I, Value *Num, Value *Den,
142 unsigned MaxDivBits, bool Signed) const;
143
144 /// Expands div or rem by using floating-point operations.
145 /// Operands must be in the range [-0x400000,0x3FFFFF]
146 Value *expandDivRemToFloat(IRBuilder<> &Builder, BinaryOperator &I,
147 Value *Num, Value *Den, bool IsDiv,
148 bool IsSigned) const;
149
150 Value *expandDivRemToFloatImpl(IRBuilder<> &Builder, BinaryOperator &I,
151 Value *Num, Value *Den, unsigned NumBits,
152 bool IsDiv, bool IsSigned) const;
153
154 /// Expands 32 bit div or rem.
155 Value* expandDivRem32(IRBuilder<> &Builder, BinaryOperator &I,
156 Value *Num, Value *Den) const;
157
158 Value *shrinkDivRem64(IRBuilder<> &Builder, BinaryOperator &I,
159 Value *Num, Value *Den) const;
160 void expandDivRem64(BinaryOperator &I) const;
161
162 /// Widen a scalar load.
163 ///
164 /// \details \p Widen scalar load for uniform, small type loads from constant
165 // memory / to a full 32-bits and then truncate the input to allow a scalar
166 // load instead of a vector load.
167 //
168 /// \returns True.
169
170 bool canWidenScalarExtLoad(LoadInst &I) const;
171
172 Value *matchFractPatImpl(Value &V, const APFloat &C) const;
173 Value *matchFractPatNanAvoidant(Value &V);
174 Value *applyFractPat(IRBuilder<> &Builder, Value *FractArg);
175
176 bool canOptimizeWithRsq(FastMathFlags DivFMF, FastMathFlags SqrtFMF) const;
177
178 Value *optimizeWithRsq(IRBuilder<> &Builder, Value *Num, Value *Den,
179 FastMathFlags DivFMF, FastMathFlags SqrtFMF,
180 const Instruction *CtxI) const;
181
182 Value *optimizeWithRcp(IRBuilder<> &Builder, Value *Num, Value *Den,
183 FastMathFlags FMF, const Instruction *CtxI) const;
184 Value *optimizeWithFDivFast(IRBuilder<> &Builder, Value *Num, Value *Den,
185 float ReqdAccuracy) const;
186
187 Value *visitFDivElement(IRBuilder<> &Builder, Value *Num, Value *Den,
188 FastMathFlags DivFMF, FastMathFlags SqrtFMF,
189 Value *RsqOp, const Instruction *FDiv,
190 float ReqdAccuracy) const;
191
192 std::pair<Value *, Value *> getFrexpResults(IRBuilder<> &Builder,
193 Value *Src) const;
194
195 Value *emitRcpIEEE1ULP(IRBuilder<> &Builder, Value *Src,
196 bool IsNegative) const;
197 Value *emitFrexpDiv(IRBuilder<> &Builder, Value *LHS, Value *RHS,
198 FastMathFlags FMF) const;
199 Value *emitSqrtIEEE2ULP(IRBuilder<> &Builder, Value *Src,
200 FastMathFlags FMF) const;
201 Value *emitRsqF64(IRBuilder<> &Builder, Value *X, FastMathFlags SqrtFMF,
202 FastMathFlags DivFMF, const Instruction *CtxI,
203 bool IsNegative) const;
204
205 CallInst *createWorkitemIdX(IRBuilder<> &B) const;
206 void replaceWithWorkitemIdX(Instruction &I) const;
207 void replaceWithMaskedWorkitemIdX(Instruction &I, unsigned WaveSize) const;
208 bool tryReplaceWithWorkitemId(Instruction &I, unsigned Wave) const;
209
210 bool tryNarrowMathIfNoOverflow(Instruction *I);
211
212public:
213 bool visitFDiv(BinaryOperator &I);
214
215 bool visitInstruction(Instruction &I) { return false; }
216 bool visitBinaryOperator(BinaryOperator &I);
217 bool visitLoadInst(LoadInst &I);
218 bool visitSelectInst(SelectInst &I);
219 bool visitPHINode(PHINode &I);
220 bool visitAddrSpaceCastInst(AddrSpaceCastInst &I);
221
222 bool visitIntrinsicInst(IntrinsicInst &I);
223 bool visitFMinLike(IntrinsicInst &I);
224 bool visitSqrt(IntrinsicInst &I);
225 bool visitLog(FPMathOperator &Log, Intrinsic::ID IID);
226 bool visitMbcntLo(IntrinsicInst &I) const;
227 bool visitMbcntHi(IntrinsicInst &I) const;
228 bool visitVectorReduceAdd(IntrinsicInst &I);
229 bool visitSaturatingAdd(IntrinsicInst &I);
230 bool run();
231};
232
233class AMDGPUCodeGenPrepare : public FunctionPass {
234public:
235 static char ID;
236 explicit AMDGPUCodeGenPrepare(bool ExpandDiv64InIR = false)
237 : FunctionPass(ID), ExpandDiv64InIR(ExpandDiv64InIR) {}
238 void getAnalysisUsage(AnalysisUsage &AU) const override {
243
244 // FIXME: Division expansion needs to preserve the dominator tree.
245 if (!ExpandDiv64InIR)
246 AU.setPreservesAll();
247 }
248 bool runOnFunction(Function &F) override;
249 StringRef getPassName() const override { return "AMDGPU IR optimizations"; }
250
251private:
252 bool ExpandDiv64InIR;
253};
254
255} // end anonymous namespace
256
257bool AMDGPUCodeGenPrepareImpl::run() {
258 BreakPhiNodesCache.clear();
259 bool MadeChange = false;
260
261 // Need to use make_early_inc_range because integer division expansion is
262 // handled by Transform/Utils, and it can delete instructions such as the
263 // terminator of the BB.
264 for (BasicBlock &BB : reverse(F)) {
265 for (Instruction &I : make_early_inc_range(reverse(BB))) {
267 MadeChange |= visit(I);
268 }
269 }
270
271 while (!DeadVals.empty()) {
272 if (auto *I = dyn_cast_or_null<Instruction>(DeadVals.pop_back_val()))
274 }
275
276 return MadeChange;
277}
278
279bool AMDGPUCodeGenPrepareImpl::isLegalFloatingTy(const Type *Ty) const {
280 return Ty->isFloatTy() || Ty->isDoubleTy() ||
281 (Ty->isHalfTy() && ST.has16BitInsts());
282}
283
284bool AMDGPUCodeGenPrepareImpl::canWidenScalarExtLoad(LoadInst &I) const {
285 Type *Ty = I.getType();
286 int TySize = DL.getTypeSizeInBits(Ty);
287 Align Alignment = DL.getValueOrABITypeAlignment(I.getAlign(), Ty);
288
289 return I.isSimple() && TySize < 32 && Alignment >= 4 && UA.isUniformAtDef(&I);
290}
291
292unsigned
293AMDGPUCodeGenPrepareImpl::numBitsUnsigned(Value *Op,
294 const Instruction *CtxI) const {
295 return computeKnownBits(Op, SQ.getWithInstruction(CtxI)).countMaxActiveBits();
296}
297
298unsigned
299AMDGPUCodeGenPrepareImpl::numBitsSigned(Value *Op,
300 const Instruction *CtxI) const {
301 return ComputeMaxSignificantBits(Op, SQ.DL, SQ.AC, CtxI, SQ.DT);
302}
303
304static void extractValues(IRBuilder<> &Builder,
306 auto *VT = dyn_cast<FixedVectorType>(V->getType());
307 if (!VT) {
308 Values.push_back(V);
309 return;
310 }
311
312 for (int I = 0, E = VT->getNumElements(); I != E; ++I)
313 Values.push_back(Builder.CreateExtractElement(V, I));
314}
315
317 Type *Ty,
319 if (!Ty->isVectorTy()) {
320 assert(Values.size() == 1);
321 return Values[0];
322 }
323
324 Value *NewVal = PoisonValue::get(Ty);
325 for (int I = 0, E = Values.size(); I != E; ++I)
326 NewVal = Builder.CreateInsertElement(NewVal, Values[I], I);
327
328 return NewVal;
329}
330
331bool AMDGPUCodeGenPrepareImpl::replaceMulWithMul24(BinaryOperator &I) const {
332 if (I.getOpcode() != Instruction::Mul)
333 return false;
334
335 Type *Ty = I.getType();
336 unsigned Size = Ty->getScalarSizeInBits();
337 if (Size <= 16 && ST.has16BitInsts())
338 return false;
339
340 // Prefer scalar if this could be s_mul_i32
341 if (UA.isUniformAtDef(&I))
342 return false;
343
344 Value *LHS = I.getOperand(0);
345 Value *RHS = I.getOperand(1);
346 IRBuilder<> Builder(&I);
347 Builder.SetCurrentDebugLocation(I.getDebugLoc());
348
349 unsigned LHSBits = 0, RHSBits = 0;
350 bool IsSigned = false;
351
352 if (ST.hasMulU24() && (LHSBits = numBitsUnsigned(LHS, &I)) <= 24 &&
353 (RHSBits = numBitsUnsigned(RHS, &I)) <= 24) {
354 IsSigned = false;
355
356 } else if (ST.hasMulI24() && (LHSBits = numBitsSigned(LHS, &I)) <= 24 &&
357 (RHSBits = numBitsSigned(RHS, &I)) <= 24) {
358 IsSigned = true;
359
360 } else
361 return false;
362
363 SmallVector<Value *, 4> LHSVals;
364 SmallVector<Value *, 4> RHSVals;
365 SmallVector<Value *, 4> ResultVals;
366 extractValues(Builder, LHSVals, LHS);
367 extractValues(Builder, RHSVals, RHS);
368
369 IntegerType *I32Ty = Builder.getInt32Ty();
370 IntegerType *IntrinTy = Size > 32 ? Builder.getInt64Ty() : I32Ty;
371 Type *DstTy = LHSVals[0]->getType();
372
373 for (int I = 0, E = LHSVals.size(); I != E; ++I) {
374 Value *LHS = IsSigned ? Builder.CreateSExtOrTrunc(LHSVals[I], I32Ty)
375 : Builder.CreateZExtOrTrunc(LHSVals[I], I32Ty);
376 Value *RHS = IsSigned ? Builder.CreateSExtOrTrunc(RHSVals[I], I32Ty)
377 : Builder.CreateZExtOrTrunc(RHSVals[I], I32Ty);
379 IsSigned ? Intrinsic::amdgcn_mul_i24 : Intrinsic::amdgcn_mul_u24;
380 Value *Result = Builder.CreateIntrinsic(ID, {IntrinTy}, {LHS, RHS});
381 Result = IsSigned ? Builder.CreateSExtOrTrunc(Result, DstTy)
382 : Builder.CreateZExtOrTrunc(Result, DstTy);
383 ResultVals.push_back(Result);
384 }
385
386 Value *NewVal = insertValues(Builder, Ty, ResultVals);
387 NewVal->takeName(&I);
388 I.replaceAllUsesWith(NewVal);
389 DeadVals.push_back(&I);
390
391 return true;
392}
393
394// Find a select instruction, which may have been casted. This is mostly to deal
395// with cases where i16 selects were promoted here to i32.
397 Cast = nullptr;
399 return Sel;
400
401 if ((Cast = dyn_cast<CastInst>(V))) {
402 if (SelectInst *Sel = dyn_cast<SelectInst>(Cast->getOperand(0)))
403 return Sel;
404 }
405
406 return nullptr;
407}
408
409bool AMDGPUCodeGenPrepareImpl::foldBinOpIntoSelect(BinaryOperator &BO) const {
410 // Don't do this unless the old select is going away. We want to eliminate the
411 // binary operator, not replace a binop with a select.
412 int SelOpNo = 0;
413
414 CastInst *CastOp;
415
416 // TODO: Should probably try to handle some cases with multiple
417 // users. Duplicating the select may be profitable for division.
418 SelectInst *Sel = findSelectThroughCast(BO.getOperand(0), CastOp);
419 if (!Sel || !Sel->hasOneUse()) {
420 SelOpNo = 1;
421 Sel = findSelectThroughCast(BO.getOperand(1), CastOp);
422 }
423
424 if (!Sel || !Sel->hasOneUse())
425 return false;
426
429 Constant *CBO = dyn_cast<Constant>(BO.getOperand(SelOpNo ^ 1));
430 if (!CBO || !CT || !CF)
431 return false;
432
433 if (CastOp) {
434 if (!CastOp->hasOneUse())
435 return false;
436 CT = ConstantFoldCastOperand(CastOp->getOpcode(), CT, BO.getType(), DL);
437 CF = ConstantFoldCastOperand(CastOp->getOpcode(), CF, BO.getType(), DL);
438 }
439
440 // TODO: Handle special 0/-1 cases DAG combine does, although we only really
441 // need to handle divisions here.
442 Constant *FoldedT =
443 SelOpNo ? ConstantFoldBinaryOpOperands(BO.getOpcode(), CBO, CT, DL)
444 : ConstantFoldBinaryOpOperands(BO.getOpcode(), CT, CBO, DL);
445 if (!FoldedT || isa<ConstantExpr>(FoldedT))
446 return false;
447
448 Constant *FoldedF =
449 SelOpNo ? ConstantFoldBinaryOpOperands(BO.getOpcode(), CBO, CF, DL)
450 : ConstantFoldBinaryOpOperands(BO.getOpcode(), CF, CBO, DL);
451 if (!FoldedF || isa<ConstantExpr>(FoldedF))
452 return false;
453
454 IRBuilder<> Builder(&BO);
455 Builder.SetCurrentDebugLocation(BO.getDebugLoc());
456 if (const FPMathOperator *FPOp = dyn_cast<const FPMathOperator>(&BO))
457 Builder.setFastMathFlags(FPOp->getFastMathFlags());
458
459 Value *NewSelect = Builder.CreateSelect(Sel->getCondition(),
460 FoldedT, FoldedF);
461 NewSelect->takeName(&BO);
462 BO.replaceAllUsesWith(NewSelect);
463 DeadVals.push_back(&BO);
464 if (CastOp)
465 DeadVals.push_back(CastOp);
466 DeadVals.push_back(Sel);
467 return true;
468}
469
470std::pair<Value *, Value *>
471AMDGPUCodeGenPrepareImpl::getFrexpResults(IRBuilder<> &Builder,
472 Value *Src) const {
473 Type *Ty = Src->getType();
474 Value *Frexp = Builder.CreateIntrinsic(Intrinsic::frexp,
475 {Ty, Builder.getInt32Ty()}, Src);
476 Value *FrexpMant = Builder.CreateExtractValue(Frexp, {0});
477
478 // Bypass the bug workaround for the exponent result since it doesn't matter.
479 // TODO: Does the bug workaround even really need to consider the exponent
480 // result? It's unspecified by the spec.
481
482 Value *FrexpExp =
483 ST.hasFractBug()
484 ? Builder.CreateIntrinsic(Intrinsic::amdgcn_frexp_exp,
485 {Builder.getInt32Ty(), Ty}, Src)
486 : Builder.CreateExtractValue(Frexp, {1});
487 return {FrexpMant, FrexpExp};
488}
489
490/// Emit an expansion of 1.0 / Src good for 1ulp that supports denormals.
491Value *AMDGPUCodeGenPrepareImpl::emitRcpIEEE1ULP(IRBuilder<> &Builder,
492 Value *Src,
493 bool IsNegative) const {
494 // Same as for 1.0, but expand the sign out of the constant.
495 // -1.0 / x -> rcp (fneg x)
496 if (IsNegative)
497 Src = Builder.CreateFNeg(Src);
498
499 // The rcp instruction doesn't support denormals, so scale the input
500 // out of the denormal range and convert at the end.
501 //
502 // Expand as 2^-n * (1.0 / (x * 2^n))
503
504 // TODO: Skip scaling if input is known never denormal and the input
505 // range won't underflow to denormal. The hard part is knowing the
506 // result. We need a range check, the result could be denormal for
507 // 0x1p+126 < den <= 0x1p+127.
508 auto [FrexpMant, FrexpExp] = getFrexpResults(Builder, Src);
509 Value *ScaleFactor = Builder.CreateNeg(FrexpExp);
510 Value *Rcp = Builder.CreateUnaryIntrinsic(Intrinsic::amdgcn_rcp, FrexpMant);
511 return Builder.CreateCall(getLdexpF32(), {Rcp, ScaleFactor});
512}
513
514/// Emit a 2ulp expansion for fdiv by using frexp for input scaling.
515Value *AMDGPUCodeGenPrepareImpl::emitFrexpDiv(IRBuilder<> &Builder, Value *LHS,
516 Value *RHS,
517 FastMathFlags FMF) const {
518 // If we have have to work around the fract/frexp bug, we're worse off than
519 // using the fdiv.fast expansion. The full safe expansion is faster if we have
520 // fast FMA.
521 if (HasFP32DenormalFlush && ST.hasFractBug() && !ST.hasFastFMAF32() &&
522 (!FMF.noNaNs() || !FMF.noInfs()))
523 return nullptr;
524
525 // We're scaling the LHS to avoid a denormal input, and scale the denominator
526 // to avoid large values underflowing the result.
527 auto [FrexpMantRHS, FrexpExpRHS] = getFrexpResults(Builder, RHS);
528
529 Value *Rcp =
530 Builder.CreateUnaryIntrinsic(Intrinsic::amdgcn_rcp, FrexpMantRHS);
531
532 auto [FrexpMantLHS, FrexpExpLHS] = getFrexpResults(Builder, LHS);
533 Value *Mul = Builder.CreateFMul(FrexpMantLHS, Rcp);
534
535 // We multiplied by 2^N/2^M, so we need to multiply by 2^(N-M) to scale the
536 // result.
537 Value *ExpDiff = Builder.CreateSub(FrexpExpLHS, FrexpExpRHS);
538 return Builder.CreateCall(getLdexpF32(), {Mul, ExpDiff});
539}
540
541/// Emit a sqrt that handles denormals and is accurate to 2ulp.
542Value *AMDGPUCodeGenPrepareImpl::emitSqrtIEEE2ULP(IRBuilder<> &Builder,
543 Value *Src,
544 FastMathFlags FMF) const {
545 Type *Ty = Src->getType();
546 APFloat SmallestNormal =
548 Value *NeedScale =
549 Builder.CreateFCmpOLT(Src, ConstantFP::get(Ty, SmallestNormal));
550
551 ConstantInt *Zero = Builder.getInt32(0);
552 Value *InputScaleFactor =
553 Builder.CreateSelect(NeedScale, Builder.getInt32(32), Zero);
554
555 Value *Scaled = Builder.CreateCall(getLdexpF32(), {Src, InputScaleFactor});
556
557 Value *Sqrt = Builder.CreateCall(getSqrtF32(), Scaled);
558
559 Value *OutputScaleFactor =
560 Builder.CreateSelect(NeedScale, Builder.getInt32(-16), Zero);
561 return Builder.CreateCall(getLdexpF32(), {Sqrt, OutputScaleFactor});
562}
563
564/// Emit an expansion of 1.0 / sqrt(Src) good for 1ulp that supports denormals.
565static Value *emitRsqIEEE1ULP(IRBuilder<> &Builder, Value *Src,
566 bool IsNegative) {
567 // bool need_scale = x < 0x1p-126f;
568 // float input_scale = need_scale ? 0x1.0p+24f : 1.0f;
569 // float output_scale = need_scale ? 0x1.0p+12f : 1.0f;
570 // rsq(x * input_scale) * output_scale;
571
572 Type *Ty = Src->getType();
573 APFloat SmallestNormal =
574 APFloat::getSmallestNormalized(Ty->getFltSemantics());
575 Value *NeedScale =
576 Builder.CreateFCmpOLT(Src, ConstantFP::get(Ty, SmallestNormal));
577 Constant *One = ConstantFP::get(Ty, 1.0);
578 Constant *InputScale = ConstantFP::get(Ty, 0x1.0p+24);
579 Constant *OutputScale =
580 ConstantFP::get(Ty, IsNegative ? -0x1.0p+12 : 0x1.0p+12);
581
582 Value *InputScaleFactor = Builder.CreateSelect(NeedScale, InputScale, One);
583
584 Value *ScaledInput = Builder.CreateFMul(Src, InputScaleFactor);
585 Value *Rsq = Builder.CreateUnaryIntrinsic(Intrinsic::amdgcn_rsq, ScaledInput);
586 Value *OutputScaleFactor = Builder.CreateSelect(
587 NeedScale, OutputScale, IsNegative ? ConstantFP::get(Ty, -1.0) : One);
588
589 return Builder.CreateFMul(Rsq, OutputScaleFactor);
590}
591
592/// Emit inverse sqrt expansion for f64 with a correction sequence on top of
593/// v_rsq_f64. This should give a 1ulp result.
594Value *AMDGPUCodeGenPrepareImpl::emitRsqF64(IRBuilder<> &Builder, Value *X,
595 FastMathFlags SqrtFMF,
596 FastMathFlags DivFMF,
597 const Instruction *CtxI,
598 bool IsNegative) const {
599 // rsq(x):
600 // double y0 = BUILTIN_AMDGPU_RSQRT_F64(x);
601 // double e = MATH_MAD(-y0 * (x == PINF_F64 || x == 0.0 ? y0 : x), y0, 1.0);
602 // return MATH_MAD(y0*e, MATH_MAD(e, 0.375, 0.5), y0);
603 //
604 // -rsq(x):
605 // double y0 = BUILTIN_AMDGPU_RSQRT_F64(x);
606 // double e = MATH_MAD(-y0 * (x == PINF_F64 || x == 0.0 ? y0 : x), y0, 1.0);
607 // return MATH_MAD(-y0*e, MATH_MAD(e, 0.375, 0.5), -y0);
608 //
609 // The rsq instruction handles the special cases correctly. We need to check
610 // for the edge case conditions to ensure the special case propagates through
611 // the later instructions.
612
613 Value *Y0 = Builder.CreateUnaryIntrinsic(Intrinsic::amdgcn_rsq, X);
614
615 // Try to elide the edge case check.
616 //
617 // Fast math flags imply:
618 // sqrt ninf => !isinf(x)
619 // fdiv ninf => x != 0, !isinf(x)
620 bool MaybePosInf = !SqrtFMF.noInfs() && !DivFMF.noInfs();
621 bool MaybeZero = !DivFMF.noInfs();
622
623 DenormalMode DenormMode;
624 FPClassTest Interested = fcNone;
625 if (MaybePosInf)
626 Interested = fcPosInf;
627 if (MaybeZero)
628 Interested |= fcZero;
629
630 if (Interested != fcNone) {
631 KnownFPClass KnownSrc = computeKnownFPClass(X, Interested, CtxI);
632 if (KnownSrc.isKnownNeverPosInfinity())
633 MaybePosInf = false;
634
635 DenormMode = F.getDenormalMode(X->getType()->getFltSemantics());
636 if (KnownSrc.isKnownNeverLogicalZero(DenormMode))
637 MaybeZero = false;
638 }
639
640 Value *SpecialOrRsq = X;
641 if (MaybeZero || MaybePosInf) {
642 Value *Cond;
643 if (MaybePosInf && MaybeZero) {
644 if (DenormMode.Input != DenormalMode::DenormalModeKind::Dynamic) {
645 FPClassTest TestMask = fcPosInf | fcZero;
646 if (DenormMode.inputsAreZero())
647 TestMask |= fcSubnormal;
648
649 Cond = Builder.createIsFPClass(X, TestMask);
650 } else {
651 // Avoid using llvm.is.fpclass for dynamic denormal mode, since it
652 // doesn't respect the floating-point environment.
653 Value *IsZero =
654 Builder.CreateFCmpOEQ(X, ConstantFP::getZero(X->getType()));
655 Value *IsInf =
656 Builder.CreateFCmpOEQ(X, ConstantFP::getInfinity(X->getType()));
657 Cond = Builder.CreateOr(IsZero, IsInf);
658 }
659 } else if (MaybeZero) {
660 Cond = Builder.CreateFCmpOEQ(X, ConstantFP::getZero(X->getType()));
661 } else {
662 Cond = Builder.CreateFCmpOEQ(X, ConstantFP::getInfinity(X->getType()));
663 }
664
665 SpecialOrRsq = Builder.CreateSelect(Cond, Y0, X);
666 }
667
668 Value *NegY0 = Builder.CreateFNeg(Y0);
669 Value *NegXY0 = Builder.CreateFMul(SpecialOrRsq, NegY0);
670
671 // Could be fmuladd, but isFMAFasterThanFMulAndFAdd is always true for f64.
672 Value *E = Builder.CreateFMA(NegXY0, Y0, ConstantFP::get(X->getType(), 1.0));
673
674 Value *Y0E = Builder.CreateFMul(E, IsNegative ? NegY0 : Y0);
675
676 Value *EFMA = Builder.CreateFMA(E, ConstantFP::get(X->getType(), 0.375),
677 ConstantFP::get(X->getType(), 0.5));
678
679 return Builder.CreateFMA(Y0E, EFMA, IsNegative ? NegY0 : Y0);
680}
681
682bool AMDGPUCodeGenPrepareImpl::canOptimizeWithRsq(FastMathFlags DivFMF,
683 FastMathFlags SqrtFMF) const {
684 // The rsqrt contraction increases accuracy from ~2ulp to ~1ulp for f32 and
685 // f64.
686 return DivFMF.allowContract() && SqrtFMF.allowContract();
687}
688
689Value *AMDGPUCodeGenPrepareImpl::optimizeWithRsq(
690 IRBuilder<> &Builder, Value *Num, Value *Den, const FastMathFlags DivFMF,
691 const FastMathFlags SqrtFMF, const Instruction *CtxI) const {
692 // The rsqrt contraction increases accuracy from ~2ulp to ~1ulp.
693 assert(DivFMF.allowContract() && SqrtFMF.allowContract());
694
695 // rsq_f16 is accurate to 0.51 ulp.
696 // rsq_f32 is accurate for !fpmath >= 1.0ulp and denormals are flushed.
697 // rsq_f64 is never accurate.
698 const ConstantFP *CLHS = dyn_cast<ConstantFP>(Num);
699 if (!CLHS)
700 return nullptr;
701
702 bool IsNegative = false;
703
704 // TODO: Handle other numerator values with arcp.
705 if (CLHS->isOne() || (IsNegative = CLHS->isMinusOne())) {
706 // Add sqrt flags, but require both ninf and nsz from the div and the
707 // sqrt: sqrt's ninf/nsz don't say anything about the quotient.
708 IRBuilder<>::FastMathFlagGuard Guard(Builder);
709 FastMathFlags NewFMF = DivFMF | SqrtFMF;
710 FastMathFlags ValueFMF = FastMathFlags::intersectValue(DivFMF, SqrtFMF);
711 NewFMF.setNoInfs(ValueFMF.noInfs());
712 NewFMF.setNoSignedZeros(ValueFMF.noSignedZeros());
713 Builder.setFastMathFlags(NewFMF);
714
715 if (Den->getType()->isFloatTy()) {
716 if ((DivFMF.approxFunc() && SqrtFMF.approxFunc()) ||
717 canIgnoreDenormalInput(Den, CtxI)) {
718 Value *Result =
719 Builder.CreateUnaryIntrinsic(Intrinsic::amdgcn_rsq, Den);
720 // -1.0 / sqrt(x) -> fneg(rsq(x))
721 return IsNegative ? Builder.CreateFNeg(Result) : Result;
722 }
723
724 return emitRsqIEEE1ULP(Builder, Den, IsNegative);
725 }
726
727 if (Den->getType()->isDoubleTy())
728 return emitRsqF64(Builder, Den, SqrtFMF, DivFMF, CtxI, IsNegative);
729 }
730
731 return nullptr;
732}
733
734// Optimize fdiv with rcp:
735//
736// 1/x -> rcp(x) when rcp is sufficiently accurate or inaccurate rcp is
737// allowed with afn.
738//
739// a/b -> a*rcp(b) when arcp is allowed, and we only need provide ULP 1.0
740Value *
741AMDGPUCodeGenPrepareImpl::optimizeWithRcp(IRBuilder<> &Builder, Value *Num,
742 Value *Den, FastMathFlags FMF,
743 const Instruction *CtxI) const {
744 // rcp_f16 is accurate to 0.51 ulp.
745 // rcp_f32 is accurate for !fpmath >= 1.0ulp and denormals are flushed.
746 // rcp_f64 is never accurate.
747 assert(Den->getType()->isFloatTy());
748
749 if (const ConstantFP *CLHS = dyn_cast<ConstantFP>(Num)) {
750 bool IsNegative = false;
751 if (CLHS->isOne() || (IsNegative = CLHS->isMinusOne())) {
752 Value *Src = Den;
753
754 if (HasFP32DenormalFlush || FMF.approxFunc()) {
755 // -1.0 / x -> 1.0 / fneg(x)
756 if (IsNegative)
757 Src = Builder.CreateFNeg(Src);
758
759 // v_rcp_f32 and v_rsq_f32 do not support denormals, and according to
760 // the CI documentation has a worst case error of 1 ulp.
761 // OpenCL requires <= 2.5 ulp for 1.0 / x, so it should always be OK
762 // to use it as long as we aren't trying to use denormals.
763 //
764 // v_rcp_f16 and v_rsq_f16 DO support denormals.
765
766 // NOTE: v_sqrt and v_rcp will be combined to v_rsq later. So we don't
767 // insert rsq intrinsic here.
768
769 // 1.0 / x -> rcp(x)
770 return Builder.CreateUnaryIntrinsic(Intrinsic::amdgcn_rcp, Src);
771 }
772
773 // TODO: If the input isn't denormal, and we know the input exponent isn't
774 // big enough to introduce a denormal we can avoid the scaling.
775 return emitRcpIEEE1ULP(Builder, Src, IsNegative);
776 }
777 }
778
779 if (FMF.allowReciprocal()) {
780 // x / y -> x * (1.0 / y)
781
782 // TODO: Could avoid denormal scaling and use raw rcp if we knew the output
783 // will never underflow.
784 if (HasFP32DenormalFlush || FMF.approxFunc()) {
785 Value *Recip = Builder.CreateUnaryIntrinsic(Intrinsic::amdgcn_rcp, Den);
786 return Builder.CreateFMul(Num, Recip);
787 }
788
789 Value *Recip = emitRcpIEEE1ULP(Builder, Den, false);
790 return Builder.CreateFMul(Num, Recip);
791 }
792
793 return nullptr;
794}
795
796// optimize with fdiv.fast:
797//
798// a/b -> fdiv.fast(a, b) when !fpmath >= 2.5ulp with denormals flushed.
799//
800// 1/x -> fdiv.fast(1,x) when !fpmath >= 2.5ulp.
801//
802// NOTE: optimizeWithRcp should be tried first because rcp is the preference.
803Value *AMDGPUCodeGenPrepareImpl::optimizeWithFDivFast(
804 IRBuilder<> &Builder, Value *Num, Value *Den, float ReqdAccuracy) const {
805 // fdiv.fast can achieve 2.5 ULP accuracy.
806 if (ReqdAccuracy < 2.5f)
807 return nullptr;
808
809 // Only have fdiv.fast for f32.
810 assert(Den->getType()->isFloatTy());
811
812 bool NumIsOne = false;
813 if (const ConstantFP *CNum = dyn_cast<ConstantFP>(Num)) {
814 if (CNum->isOne() || CNum->isMinusOne())
815 NumIsOne = true;
816 }
817
818 // fdiv does not support denormals. But 1.0/x is always fine to use it.
819 //
820 // TODO: This works for any value with a specific known exponent range, don't
821 // just limit to constant 1.
822 if (!HasFP32DenormalFlush && !NumIsOne)
823 return nullptr;
824
825 return Builder.CreateIntrinsic(Intrinsic::amdgcn_fdiv_fast, {Num, Den});
826}
827
828Value *AMDGPUCodeGenPrepareImpl::visitFDivElement(
829 IRBuilder<> &Builder, Value *Num, Value *Den, FastMathFlags DivFMF,
830 FastMathFlags SqrtFMF, Value *RsqOp, const Instruction *FDivInst,
831 float ReqdDivAccuracy) const {
832 if (RsqOp) {
833 Value *Rsq =
834 optimizeWithRsq(Builder, Num, RsqOp, DivFMF, SqrtFMF, FDivInst);
835 if (Rsq)
836 return Rsq;
837 }
838
839 if (!Num->getType()->isFloatTy())
840 return nullptr;
841
842 Value *Rcp = optimizeWithRcp(Builder, Num, Den, DivFMF, FDivInst);
843 if (Rcp)
844 return Rcp;
845
846 // In the basic case fdiv_fast has the same instruction count as the frexp div
847 // expansion. Slightly prefer fdiv_fast since it ends in an fmul that can
848 // potentially be fused into a user. Also, materialization of the constants
849 // can be reused for multiple instances.
850 Value *FDivFast = optimizeWithFDivFast(Builder, Num, Den, ReqdDivAccuracy);
851 if (FDivFast)
852 return FDivFast;
853
854 return emitFrexpDiv(Builder, Num, Den, DivFMF);
855}
856
857// Optimizations is performed based on fpmath, fast math flags as well as
858// denormals to optimize fdiv with either rcp or fdiv.fast.
859//
860// With rcp:
861// 1/x -> rcp(x) when rcp is sufficiently accurate or inaccurate rcp is
862// allowed with afn.
863//
864// a/b -> a*rcp(b) when inaccurate rcp is allowed with afn.
865//
866// With fdiv.fast:
867// a/b -> fdiv.fast(a, b) when !fpmath >= 2.5ulp with denormals flushed.
868//
869// 1/x -> fdiv.fast(1,x) when !fpmath >= 2.5ulp.
870//
871// NOTE: rcp is the preference in cases that both are legal.
872bool AMDGPUCodeGenPrepareImpl::visitFDiv(BinaryOperator &FDiv) {
873 if (!CLOpts.codegenprepare_fdiv_expansion)
874 return false;
875
876 Type *Ty = FDiv.getType()->getScalarType();
877 const bool IsFloat = Ty->isFloatTy();
878 if (!IsFloat && !Ty->isDoubleTy())
879 return false;
880
881 // The f64 rcp/rsq approximations are pretty inaccurate. We can do an
882 // expansion around them in codegen. f16 is good enough to always use.
883
884 const FPMathOperator *FPOp = cast<const FPMathOperator>(&FDiv);
885 const FastMathFlags DivFMF = FPOp->getFastMathFlags();
886 const float ReqdAccuracy = FPOp->getFPAccuracy();
887
888 FastMathFlags SqrtFMF;
889
890 Value *Num = FDiv.getOperand(0);
891 Value *Den = FDiv.getOperand(1);
892
893 Value *RsqOp = nullptr;
894 auto *DenII = dyn_cast<IntrinsicInst>(Den);
895 if (DenII && DenII->getIntrinsicID() == Intrinsic::sqrt &&
896 DenII->hasOneUse()) {
897 const auto *SqrtOp = cast<FPMathOperator>(DenII);
898 SqrtFMF = SqrtOp->getFastMathFlags();
899 if (canOptimizeWithRsq(DivFMF, SqrtFMF))
900 RsqOp = SqrtOp->getOperand(0);
901 }
902
903 // rcp path not yet implemented for f64.
904 if (!IsFloat && !RsqOp)
905 return false;
906
907 // Inaccurate rcp is allowed with afn.
908 //
909 // Defer to codegen to handle this.
910 //
911 // TODO: Decide on an interpretation for interactions between afn + arcp +
912 // !fpmath, and make it consistent between here and codegen. For now, defer
913 // expansion of afn to codegen. The current interpretation is so aggressive we
914 // don't need any pre-consideration here when we have better information. A
915 // more conservative interpretation could use handling here.
916 const bool AllowInaccurateRcp = DivFMF.approxFunc();
917 if (!RsqOp && AllowInaccurateRcp)
918 return false;
919
920 // Defer the correct implementations to codegen.
921 if (IsFloat && ReqdAccuracy < 1.0f)
922 return false;
923
924 IRBuilder<> Builder(std::next(FDiv.getIterator()));
925 Builder.setFastMathFlags(DivFMF);
926 Builder.SetCurrentDebugLocation(FDiv.getDebugLoc());
927
928 SmallVector<Value *, 4> NumVals;
929 SmallVector<Value *, 4> DenVals;
930 SmallVector<Value *, 4> RsqDenVals;
931 extractValues(Builder, NumVals, Num);
932 extractValues(Builder, DenVals, Den);
933
934 if (RsqOp)
935 extractValues(Builder, RsqDenVals, RsqOp);
936
937 SmallVector<Value *, 4> ResultVals(NumVals.size());
938 for (int I = 0, E = NumVals.size(); I != E; ++I) {
939 Value *NumElt = NumVals[I];
940 Value *DenElt = DenVals[I];
941 Value *RsqDenElt = RsqOp ? RsqDenVals[I] : nullptr;
942
943 Value *NewElt =
944 visitFDivElement(Builder, NumElt, DenElt, DivFMF, SqrtFMF, RsqDenElt,
945 cast<Instruction>(FPOp), ReqdAccuracy);
946 if (!NewElt) {
947 // Keep the original, but scalarized.
948
949 // This has the unfortunate side effect of sometimes scalarizing when
950 // we're not going to do anything.
951 NewElt = Builder.CreateFDiv(NumElt, DenElt);
952 if (auto *NewEltInst = dyn_cast<Instruction>(NewElt))
953 NewEltInst->copyMetadata(FDiv);
954 }
955
956 ResultVals[I] = NewElt;
957 }
958
959 Value *NewVal = insertValues(Builder, FDiv.getType(), ResultVals);
960
961 if (NewVal) {
962 FDiv.replaceAllUsesWith(NewVal);
963 NewVal->takeName(&FDiv);
964 DeadVals.push_back(&FDiv);
965 }
966
967 return true;
968}
969
970static std::pair<Value*, Value*> getMul64(IRBuilder<> &Builder,
971 Value *LHS, Value *RHS) {
972 Type *I32Ty = Builder.getInt32Ty();
973 Type *I64Ty = Builder.getInt64Ty();
974
975 Value *LHS_EXT64 = Builder.CreateZExt(LHS, I64Ty);
976 Value *RHS_EXT64 = Builder.CreateZExt(RHS, I64Ty);
977 Value *MUL64 = Builder.CreateMul(LHS_EXT64, RHS_EXT64);
978 Value *Lo = Builder.CreateTrunc(MUL64, I32Ty);
979 Value *Hi = Builder.CreateLShr(MUL64, Builder.getInt64(32));
980 Hi = Builder.CreateTrunc(Hi, I32Ty);
981 return std::pair(Lo, Hi);
982}
983
984static Value* getMulHu(IRBuilder<> &Builder, Value *LHS, Value *RHS) {
985 return getMul64(Builder, LHS, RHS).second;
986}
987
988/// Figure out how many bits are really needed for this division.
989/// \p MaxDivBits is an optimization hint to bypass the second
990/// ComputeNumSignBits/computeKnownBits call if the first one is
991/// insufficient.
992unsigned AMDGPUCodeGenPrepareImpl::getDivNumBits(BinaryOperator &I, Value *Num,
993 Value *Den,
994 unsigned MaxDivBits,
995 bool IsSigned) const {
997 Den->getType()->getScalarSizeInBits());
998 unsigned SSBits = Num->getType()->getScalarSizeInBits();
999 if (IsSigned) {
1000 unsigned RHSSignBits = ComputeNumSignBits(Den, SQ.DL, SQ.AC, &I, SQ.DT);
1001 // A sign bit needs to be reserved for shrinking.
1002 unsigned DivBits = SSBits - RHSSignBits + 1;
1003 if (DivBits > MaxDivBits)
1004 return SSBits;
1005
1006 unsigned LHSSignBits = ComputeNumSignBits(Num, SQ.DL, SQ.AC, &I);
1007
1008 unsigned SignBits = std::min(LHSSignBits, RHSSignBits);
1009 DivBits = SSBits - SignBits + 1;
1010 return DivBits;
1011 }
1012
1013 // All bits are used for unsigned division for Num or Den in range
1014 // (SignedMax, UnsignedMax].
1015 KnownBits Known = computeKnownBits(Den, SQ.getWithInstruction(&I));
1016 unsigned RHSBits = Known.countMaxActiveBits();
1017 if (RHSBits > MaxDivBits)
1018 return SSBits;
1019
1021 unsigned LHSBits = Known.countMaxActiveBits();
1022
1023 unsigned DivBits = std::max(LHSBits, RHSBits);
1024 return DivBits;
1025}
1026
1027Value *AMDGPUCodeGenPrepareImpl::expandDivRemToFloat(IRBuilder<> &Builder,
1028 BinaryOperator &I,
1029 Value *Num, Value *Den,
1030 bool IsDiv,
1031 bool IsSigned) const {
1032 unsigned DivBits = getDivNumBits(I, Num, Den, 23, IsSigned);
1033
1034 if (DivBits > (IsSigned ? 23u : 22u))
1035 return nullptr;
1036 return expandDivRemToFloatImpl(Builder, I, Num, Den, DivBits, IsDiv,
1037 IsSigned);
1038}
1039
1040Value *AMDGPUCodeGenPrepareImpl::expandDivRemToFloatImpl(
1041 IRBuilder<> &Builder, BinaryOperator &I, Value *Num, Value *Den,
1042 unsigned DivBits, bool IsDiv, bool IsSigned) const {
1043
1044 // v_rcp_f32(float(X)) can have an error of 1 ulp.
1045 // This would cause incorrect calculation of Y/X if:
1046 // Y = (0x7FFFFF/X)*(X-0)-1
1047 // were allowed.
1048 //
1049 // For example,
1050 // (0x7FF6D3/0x000FE7) would erroneously produce 2060 instead of 2059.
1051 // (0x7FF8F5/0x007EFB) would erroneously produce 258 instead of 257.
1052 //
1053 // Thus, we conservatively restrict expandDivRemToFloatImpl to
1054 // [-0x400000,0x3FFFFF] for IsSigned
1055 // [ 0x000000,0x3FFFFF] for !IsSigned.
1056 assert(0 < DivBits && DivBits <= (IsSigned ? 23u : 22u) &&
1057 "abs(Num) must be <= 0x400000 for expandDivRemToFloatImpl to work "
1058 "correctly");
1059
1060 Type *I32Ty = Builder.getInt32Ty();
1061 Num = Builder.CreateTrunc(Num, I32Ty);
1062 Den = Builder.CreateTrunc(Den, I32Ty);
1063
1064 Type *F32Ty = Builder.getFloatTy();
1065 ConstantInt *One = Builder.getInt32(1);
1066
1067 // int ia = (int)LHS;
1068 Value *IA = Num;
1069
1070 // int ib, (int)RHS;
1071 Value *IB = Den;
1072
1073 // float fa = (float)ia;
1074 Value *FA = IsSigned ? Builder.CreateSIToFP(IA, F32Ty)
1075 : Builder.CreateUIToFP(IA, F32Ty);
1076
1077 // float fb = (float)ib;
1078 Value *FB = IsSigned ? Builder.CreateSIToFP(IB, F32Ty)
1079 : Builder.CreateUIToFP(IB, F32Ty);
1080
1081 Value *RCP = Builder.CreateIntrinsic(Intrinsic::amdgcn_rcp,
1082 Builder.getFloatTy(), {FB});
1083
1084 // The calculation:
1085 // fq = fa*recip(fb)
1086 // may be too small due to the 1ulp accuracy in the recip
1087 // operation and rounding issues. Since fq is truncated to produce
1088 // an integer value it may be too small by one. This is
1089 // dealt with by incrementing fa by 1ulp:
1090 // fq = (fa+1ulp)*recip(fb)
1091 // This will increase fa's magnitude by at most 0.5
1092 // (i.e. when fabs(fa)==0x400000 the LSB of the mantissa represents 0.5).
1093 // Thus, this method is safe since fa must be incremented by at least 1.0
1094 // for the quotient to increase by one.
1095
1096 Value *FABits = Builder.CreateBitCast(FA, I32Ty);
1097 Value *FABitsInc = Builder.CreateAdd(FABits, One);
1098 FA = Builder.CreateBitCast(FABitsInc, F32Ty);
1099
1100 Value *FQM = Builder.CreateFMul(FA, RCP);
1101
1102 // fq = trunc(fqm);
1103 Value *FQ = Builder.CreateUnaryIntrinsic(Intrinsic::trunc, FQM);
1104
1105 // int iq = (int)fq;
1106 Value *IQ = IsSigned ? Builder.CreateFPToSI(FQ, I32Ty)
1107 : Builder.CreateFPToUI(FQ, I32Ty);
1108
1109 Value *Res = IQ;
1110 if (!IsDiv) {
1111 // Rem needs compensation, it's easier to recompute it
1112 Value *Rem = Builder.CreateMul(IQ, Den);
1113 Res = Builder.CreateSub(Num, Rem);
1114 }
1115
1116 return Res;
1117}
1118
1119// Try to recognize special cases the DAG will emit special, better expansions
1120// than the general expansion we do here.
1121
1122// TODO: It would be better to just directly handle those optimizations here.
1123bool AMDGPUCodeGenPrepareImpl::divHasSpecialOptimization(BinaryOperator &I,
1124 Value *Num,
1125 Value *Den) const {
1126 if (Constant *C = dyn_cast<Constant>(Den)) {
1127 // Arbitrary constants get a better expansion as long as a wider mulhi is
1128 // legal.
1129 if (C->getType()->getScalarSizeInBits() <= 32)
1130 return true;
1131
1132 // TODO: Sdiv check for not exact for some reason.
1133
1134 // If there's no wider mulhi, there's only a better expansion for powers of
1135 // two.
1136 // TODO: Should really know for each vector element.
1138 return true;
1139
1140 return false;
1141 }
1142
1143 if (BinaryOperator *BinOpDen = dyn_cast<BinaryOperator>(Den)) {
1144 // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2
1145 if (BinOpDen->getOpcode() == Instruction::Shl &&
1146 isa<Constant>(BinOpDen->getOperand(0)) &&
1147 isKnownToBeAPowerOfTwo(BinOpDen->getOperand(0), true,
1148 SQ.getWithInstruction(&I))) {
1149 return true;
1150 }
1151 }
1152
1153 return false;
1154}
1155
1156static Value *getSign32(Value *V, IRBuilder<> &Builder, const DataLayout DL) {
1157 // Check whether the sign can be determined statically.
1159 if (Known.isNegative())
1160 return Constant::getAllOnesValue(V->getType());
1161 if (Known.isNonNegative())
1162 return Constant::getNullValue(V->getType());
1163 return Builder.CreateAShr(V, Builder.getInt32(31));
1164}
1165
1166Value *AMDGPUCodeGenPrepareImpl::expandDivRem32(IRBuilder<> &Builder,
1167 BinaryOperator &I, Value *X,
1168 Value *Y) const {
1169 Instruction::BinaryOps Opc = I.getOpcode();
1170 assert(Opc == Instruction::URem || Opc == Instruction::UDiv ||
1171 Opc == Instruction::SRem || Opc == Instruction::SDiv);
1172
1173 FastMathFlags FMF;
1174 FMF.setFast();
1175 Builder.setFastMathFlags(FMF);
1176
1177 if (divHasSpecialOptimization(I, X, Y))
1178 return nullptr; // Keep it for later optimization.
1179
1180 bool IsDiv = Opc == Instruction::UDiv || Opc == Instruction::SDiv;
1181 bool IsSigned = Opc == Instruction::SRem || Opc == Instruction::SDiv;
1182
1183 Type *Ty = X->getType();
1184 Type *I32Ty = Builder.getInt32Ty();
1185 Type *F32Ty = Builder.getFloatTy();
1186
1187 if (Ty->getScalarSizeInBits() != 32) {
1188 if (IsSigned) {
1189 X = Builder.CreateSExtOrTrunc(X, I32Ty);
1190 Y = Builder.CreateSExtOrTrunc(Y, I32Ty);
1191 } else {
1192 X = Builder.CreateZExtOrTrunc(X, I32Ty);
1193 Y = Builder.CreateZExtOrTrunc(Y, I32Ty);
1194 }
1195 }
1196
1197 if (Value *Res = expandDivRemToFloat(Builder, I, X, Y, IsDiv, IsSigned)) {
1198 return IsSigned ? Builder.CreateSExtOrTrunc(Res, Ty) :
1199 Builder.CreateZExtOrTrunc(Res, Ty);
1200 }
1201
1202 ConstantInt *Zero = Builder.getInt32(0);
1203 ConstantInt *One = Builder.getInt32(1);
1204
1205 Value *Sign = nullptr;
1206 if (IsSigned) {
1207 Value *SignX = getSign32(X, Builder, DL);
1208 Value *SignY = getSign32(Y, Builder, DL);
1209 // Remainder sign is the same as LHS
1210 Sign = IsDiv ? Builder.CreateXor(SignX, SignY) : SignX;
1211
1212 X = Builder.CreateAdd(X, SignX);
1213 Y = Builder.CreateAdd(Y, SignY);
1214
1215 X = Builder.CreateXor(X, SignX);
1216 Y = Builder.CreateXor(Y, SignY);
1217 }
1218
1219 // The algorithm here is based on ideas from "Software Integer Division", Tom
1220 // Rodeheffer, August 2008.
1221 //
1222 // unsigned udiv(unsigned x, unsigned y) {
1223 // // Initial estimate of inv(y). The constant is less than 2^32 to ensure
1224 // // that this is a lower bound on inv(y), even if some of the calculations
1225 // // round up.
1226 // unsigned z = (unsigned)((4294967296.0 - 512.0) * v_rcp_f32((float)y));
1227 //
1228 // // One round of UNR (Unsigned integer Newton-Raphson) to improve z.
1229 // // Empirically this is guaranteed to give a "two-y" lower bound on
1230 // // inv(y).
1231 // z += umulh(z, -y * z);
1232 //
1233 // // Quotient/remainder estimate.
1234 // unsigned q = umulh(x, z);
1235 // unsigned r = x - q * y;
1236 //
1237 // // Two rounds of quotient/remainder refinement.
1238 // if (r >= y) {
1239 // ++q;
1240 // r -= y;
1241 // }
1242 // if (r >= y) {
1243 // ++q;
1244 // r -= y;
1245 // }
1246 //
1247 // return q;
1248 // }
1249
1250 // Initial estimate of inv(y).
1251 Value *FloatY = Builder.CreateUIToFP(Y, F32Ty);
1252 Value *RcpY = Builder.CreateIntrinsic(Intrinsic::amdgcn_rcp, F32Ty, {FloatY});
1253 Constant *Scale = ConstantFP::get(F32Ty, llvm::bit_cast<float>(0x4F7FFFFE));
1254 Value *ScaledY = Builder.CreateFMul(RcpY, Scale);
1255 Value *Z = Builder.CreateFPToUI(ScaledY, I32Ty);
1256
1257 // One round of UNR.
1258 Value *NegY = Builder.CreateSub(Zero, Y);
1259 Value *NegYZ = Builder.CreateMul(NegY, Z);
1260 Z = Builder.CreateAdd(Z, getMulHu(Builder, Z, NegYZ));
1261
1262 // Quotient/remainder estimate.
1263 Value *Q = getMulHu(Builder, X, Z);
1264 Value *R = Builder.CreateSub(X, Builder.CreateMul(Q, Y));
1265
1266 // First quotient/remainder refinement.
1267 Value *Cond = Builder.CreateICmpUGE(R, Y);
1268 if (IsDiv)
1269 Q = Builder.CreateSelect(Cond, Builder.CreateAdd(Q, One), Q);
1270 R = Builder.CreateSelect(Cond, Builder.CreateSub(R, Y), R);
1271
1272 // Second quotient/remainder refinement.
1273 Cond = Builder.CreateICmpUGE(R, Y);
1274 Value *Res;
1275 if (IsDiv)
1276 Res = Builder.CreateSelect(Cond, Builder.CreateAdd(Q, One), Q);
1277 else
1278 Res = Builder.CreateSelect(Cond, Builder.CreateSub(R, Y), R);
1279
1280 if (IsSigned) {
1281 Res = Builder.CreateXor(Res, Sign);
1282 Res = Builder.CreateSub(Res, Sign);
1283 Res = Builder.CreateSExtOrTrunc(Res, Ty);
1284 } else {
1285 Res = Builder.CreateZExtOrTrunc(Res, Ty);
1286 }
1287 return Res;
1288}
1289
1290Value *AMDGPUCodeGenPrepareImpl::shrinkDivRem64(IRBuilder<> &Builder,
1291 BinaryOperator &I, Value *Num,
1292 Value *Den) const {
1293 if (!ExpandDiv64InIR && divHasSpecialOptimization(I, Num, Den))
1294 return nullptr; // Keep it for later optimization.
1295
1296 Instruction::BinaryOps Opc = I.getOpcode();
1297
1298 bool IsDiv = Opc == Instruction::SDiv || Opc == Instruction::UDiv;
1299 bool IsSigned = Opc == Instruction::SDiv || Opc == Instruction::SRem;
1300
1301 unsigned NumDivBits = getDivNumBits(I, Num, Den, 32, IsSigned);
1302 if (NumDivBits > 32)
1303 return nullptr;
1304
1305 Value *Narrowed = nullptr;
1306 if (NumDivBits <= (IsSigned ? 23u : 22u)) {
1307 Narrowed = expandDivRemToFloatImpl(Builder, I, Num, Den, NumDivBits, IsDiv,
1308 IsSigned);
1309 } else if (NumDivBits <= (IsSigned ? 31u : 32u)) {
1310 // Do not use 32-bit division if dividend may be -2147483648.
1311 // Otherwise 32-bit division cannot be used safely.
1312 // -2147483648/1 and -2147483648/-1 are not equal,
1313 // but they produce the same lower 32-bit result.
1314 Narrowed = expandDivRem32(Builder, I, Num, Den);
1315 }
1316
1317 if (Narrowed) {
1318 return IsSigned ? Builder.CreateSExt(Narrowed, Num->getType()) :
1319 Builder.CreateZExt(Narrowed, Num->getType());
1320 }
1321
1322 return nullptr;
1323}
1324
1325void AMDGPUCodeGenPrepareImpl::expandDivRem64(BinaryOperator &I) const {
1326 Instruction::BinaryOps Opc = I.getOpcode();
1327 // Do the general expansion.
1328 if (Opc == Instruction::UDiv || Opc == Instruction::SDiv) {
1330 return;
1331 }
1332
1333 if (Opc == Instruction::URem || Opc == Instruction::SRem) {
1335 return;
1336 }
1337
1338 llvm_unreachable("not a division");
1339}
1340
1341/*
1342This will cause non-byte load in consistency, for example:
1343```
1344 %load = load i1, ptr addrspace(4) %arg, align 4
1345 %zext = zext i1 %load to
1346 i64 %add = add i64 %zext
1347```
1348Instead of creating `s_and_b32 s0, s0, 1`,
1349it will create `s_and_b32 s0, s0, 0xff`.
1350We accept this change since the non-byte load assumes the upper bits
1351within the byte are all 0.
1352*/
1353bool AMDGPUCodeGenPrepareImpl::tryNarrowMathIfNoOverflow(Instruction *I) {
1354 unsigned Opc = I->getOpcode();
1355
1356 if (Opc != Instruction::Add && Opc != Instruction::Mul)
1357 return false;
1358
1359 Type *OldType = I->getType();
1360 unsigned OrigBit = OldType->getScalarSizeInBits();
1361 unsigned MaxBitsNeeded = computeKnownBits(I, DL).countMaxActiveBits();
1362
1363 MaxBitsNeeded = std::max<unsigned>(bit_ceil(MaxBitsNeeded), 8);
1364 Type *NewType = DL.getSmallestLegalIntType(I->getContext(), MaxBitsNeeded);
1365 if (!NewType)
1366 return false;
1367 unsigned NewBit = NewType->getIntegerBitWidth();
1368 if (NewBit >= OrigBit)
1369 return false;
1370 NewType = I->getType()->getWithNewBitWidth(NewBit);
1371
1372 // Old cost
1373 InstructionCost OldCost =
1375 // New cost of new op
1376 InstructionCost NewCost =
1378 // New cost of narrowing 2 operands (use trunc)
1379 int NumOfNonConstOps = 2;
1380 if (isa<Constant>(I->getOperand(0)) || isa<Constant>(I->getOperand(1))) {
1381 // Cannot be both constant, should be propagated
1382 NumOfNonConstOps = 1;
1383 }
1384 NewCost += NumOfNonConstOps * TTI.getCastInstrCost(Instruction::Trunc,
1385 NewType, OldType,
1388 // New cost of zext narrowed result to original type
1389 NewCost +=
1390 TTI.getCastInstrCost(Instruction::ZExt, OldType, NewType,
1392 if (NewCost >= OldCost)
1393 return false;
1394
1395 IRBuilder<> Builder(I);
1396 Value *Trunc0 = Builder.CreateTrunc(I->getOperand(0), NewType);
1397 Value *Trunc1 = Builder.CreateTrunc(I->getOperand(1), NewType);
1398 Value *Arith =
1399 Builder.CreateBinOp((Instruction::BinaryOps)Opc, Trunc0, Trunc1);
1400
1401 Value *Zext = Builder.CreateZExt(Arith, OldType);
1402 I->replaceAllUsesWith(Zext);
1403 DeadVals.push_back(I);
1404 return true;
1405}
1406
1407bool AMDGPUCodeGenPrepareImpl::visitBinaryOperator(BinaryOperator &I) {
1408 if (foldBinOpIntoSelect(I))
1409 return true;
1410
1411 if (CLOpts.codegenprepare_mul24 && replaceMulWithMul24(I))
1412 return true;
1413 if (tryNarrowMathIfNoOverflow(&I))
1414 return true;
1415
1416 bool Changed = false;
1417 Instruction::BinaryOps Opc = I.getOpcode();
1418 Type *Ty = I.getType();
1419 Value *NewDiv = nullptr;
1420 unsigned ScalarSize = Ty->getScalarSizeInBits();
1421
1423
1424 if ((Opc == Instruction::URem || Opc == Instruction::UDiv ||
1425 Opc == Instruction::SRem || Opc == Instruction::SDiv) &&
1426 ScalarSize <= 64 && CLOpts.codegenprepare_idiv_expansion) {
1427 Value *Num = I.getOperand(0);
1428 Value *Den = I.getOperand(1);
1429 IRBuilder<> Builder(&I);
1430 Builder.SetCurrentDebugLocation(I.getDebugLoc());
1431
1432 if (auto *VT = dyn_cast<FixedVectorType>(Ty)) {
1433 NewDiv = PoisonValue::get(VT);
1434
1435 for (unsigned N = 0, E = VT->getNumElements(); N != E; ++N) {
1436 Value *NumEltN = Builder.CreateExtractElement(Num, N);
1437 Value *DenEltN = Builder.CreateExtractElement(Den, N);
1438
1439 Value *NewElt;
1440 if (ScalarSize <= 32) {
1441 NewElt = expandDivRem32(Builder, I, NumEltN, DenEltN);
1442 if (!NewElt)
1443 NewElt = Builder.CreateBinOp(Opc, NumEltN, DenEltN);
1444 } else {
1445 // See if this 64-bit division can be shrunk to 32/24-bits before
1446 // producing the general expansion.
1447 NewElt = shrinkDivRem64(Builder, I, NumEltN, DenEltN);
1448 if (!NewElt) {
1449 // The general 64-bit expansion introduces control flow and doesn't
1450 // return the new value. Just insert a scalar copy and defer
1451 // expanding it.
1452 NewElt = Builder.CreateBinOp(Opc, NumEltN, DenEltN);
1453 // CreateBinOp does constant folding. If the operands are constant,
1454 // it will return a Constant instead of a BinaryOperator.
1455 if (auto *NewEltBO = dyn_cast<BinaryOperator>(NewElt))
1456 Div64ToExpand.push_back(NewEltBO);
1457 }
1458 }
1459
1460 if (auto *NewEltI = dyn_cast<Instruction>(NewElt))
1461 NewEltI->copyIRFlags(&I);
1462
1463 NewDiv = Builder.CreateInsertElement(NewDiv, NewElt, N);
1464 }
1465 } else {
1466 if (ScalarSize <= 32)
1467 NewDiv = expandDivRem32(Builder, I, Num, Den);
1468 else {
1469 NewDiv = shrinkDivRem64(Builder, I, Num, Den);
1470 if (!NewDiv && ExpandDiv64InIR) {
1471 // The expansion erases its input. Expand a copy so that I is erased
1472 // through DeadVals.
1473 auto *Copy = cast<BinaryOperator>(Builder.Insert(I.clone()));
1474 Div64ToExpand.push_back(Copy);
1475 NewDiv = Copy;
1476 }
1477 }
1478 }
1479
1480 if (NewDiv) {
1481 I.replaceAllUsesWith(NewDiv);
1482 DeadVals.push_back(&I);
1483 Changed = true;
1484 }
1485 }
1486
1487 if (ExpandDiv64InIR) {
1488 // TODO: We get much worse code in specially handled constant cases.
1489 for (BinaryOperator *Div : Div64ToExpand) {
1490 expandDivRem64(*Div);
1491 FlowChanged = true;
1492 Changed = true;
1493 }
1494 }
1495
1496 return Changed;
1497}
1498
1499bool AMDGPUCodeGenPrepareImpl::visitLoadInst(LoadInst &I) {
1500 if (!CLOpts.codegenprepare_widen_constant_loads)
1501 return false;
1502
1503 if ((I.getPointerAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS ||
1504 I.getPointerAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT) &&
1505 canWidenScalarExtLoad(I)) {
1506 IRBuilder<> Builder(&I);
1507 Builder.SetCurrentDebugLocation(I.getDebugLoc());
1508
1509 Type *I32Ty = Builder.getInt32Ty();
1510 LoadInst *WidenLoad = Builder.CreateLoad(I32Ty, I.getPointerOperand());
1512
1513 // The widened load reads the original bytes in the low bits, so a !range
1514 // lower bound still holds. Convert it to the new type and don't make
1515 // assumptions about the high bits.
1516 if (auto *Range = I.getMetadata(LLVMContext::MD_range)) {
1517 ConstantInt *Lower = mdconst::extract<ConstantInt>(Range->getOperand(0));
1518
1519 if (!Lower->isNullValue()) {
1520 Metadata *LowAndHigh[] = {
1521 ConstantAsMetadata::get(ConstantInt::get(I32Ty, Lower->getValue().zext(32))),
1522 // Don't make assumptions about the high bits.
1523 ConstantAsMetadata::get(ConstantInt::get(I32Ty, 0))
1524 };
1525
1526 WidenLoad->setMetadata(LLVMContext::MD_range,
1527 MDNode::get(F.getContext(), LowAndHigh));
1528 }
1529 }
1530
1531 int TySize = DL.getTypeSizeInBits(I.getType());
1532 Type *IntNTy = Builder.getIntNTy(TySize);
1533 Value *ValTrunc = Builder.CreateTrunc(WidenLoad, IntNTy);
1534 Value *ValOrig = Builder.CreateBitCast(ValTrunc, I.getType());
1535 I.replaceAllUsesWith(ValOrig);
1536 DeadVals.push_back(&I);
1537 return true;
1538 }
1539
1540 return false;
1541}
1542
1543// select (X == 0 || Y == 0), +0.0, (X * Y) -> fmul_legacy(X, Y)
1544bool AMDGPUCodeGenPrepareImpl::foldSelectToFMulLegacy(SelectInst &I) const {
1545 if (!I.getType()->isFloatTy())
1546 return false;
1547
1548 // Inverted form: select (X != 0 && Y != 0), X * Y, +0.0.
1549 bool Inverted = match(I.getFalseValue(), m_PosZeroFP());
1550 if (!Inverted && !match(I.getTrueValue(), m_PosZeroFP()))
1551 return false;
1552
1553 Value *Mul = Inverted ? I.getTrueValue() : I.getFalseValue();
1554 Value *X, *Y;
1555 if (!match(Mul, m_OneUse(m_FMul(m_Value(X), m_Value(Y)))))
1556 return false;
1557
1558 // The condition must zero-test both fmul operands:
1559 // select (A == 0 || B == 0), +0.0, X * Y
1560 // select (A != 0 && B != 0), X * Y, +0.0
1561 // X * X only needs one compare, so B = A.
1562 FCmpInst::Predicate ZeroCmpPred =
1563 Inverted ? FCmpInst::FCMP_UNE : FCmpInst::FCMP_OEQ;
1564 Value *A, *B;
1565 auto ZeroCmpA = m_SpecificFCmp(ZeroCmpPred, m_Value(A), m_AnyZeroFP());
1566 auto ZeroCmpB = m_SpecificFCmp(ZeroCmpPred, m_Value(B), m_AnyZeroFP());
1567 Value *Cond = I.getCondition();
1568 if (Inverted ? !match(Cond, m_And(ZeroCmpA, ZeroCmpB))
1569 : !match(Cond, m_Or(ZeroCmpA, ZeroCmpB))) {
1570 if (!match(Cond, ZeroCmpA))
1571 return false;
1572 B = A;
1573 }
1574
1575 Value *SA = InstCombiner::stripSignOnlyFPOps(A);
1576 Value *SB = InstCombiner::stripSignOnlyFPOps(B);
1577 Value *SX = InstCombiner::stripSignOnlyFPOps(X);
1578 Value *SY = InstCombiner::stripSignOnlyFPOps(Y);
1579 if (!((SA == SX && SB == SY) || (SA == SY && SB == SX)))
1580 return false;
1581
1582 // A stripped nnan/ninf op could create poison that the select hides.
1583 if (!impliesPoison(X, SX) || !impliesPoison(Y, SY))
1584 return false;
1585
1586 // The select may hide NaN, Inf or a signed zero from the fmul.
1587 FastMathFlags FMF = cast<Instruction>(Mul)->getFastMathFlags();
1588 FMF.setNoNaNs(false);
1589 FMF.setNoInfs(false);
1590 FMF.setNoSignedZeros(I.hasNoSignedZeros());
1591
1592 IRBuilder<> Builder(&I);
1593 Value *LegacyMul =
1594 Builder.CreateIntrinsic(Intrinsic::amdgcn_fmul_legacy, {X, Y}, FMF);
1595 LegacyMul->takeName(&I);
1596 I.replaceAllUsesWith(LegacyMul);
1597 DeadVals.push_back(&I);
1598 return true;
1599}
1600
1601bool AMDGPUCodeGenPrepareImpl::visitSelectInst(SelectInst &I) {
1602 FPMathOperator *FPOp = dyn_cast<FPMathOperator>(&I);
1603 if (!FPOp)
1604 return false;
1605
1606 if (foldSelectToFMulLegacy(I))
1607 return true;
1608
1609 Value *X;
1610 Value *Fract = nullptr;
1611
1612 // Match:
1613 // (x - floor(x)) >= MIN_CONSTANT ? MIN_CONSTANT : (x - floor(x))
1614 //
1615 // This is the preferred way to implement fract.
1616 // TODO: Could also match with compare against 1.0
1617 const APFloat *C;
1619 Value *FractSrc = matchFractPatImpl(*X, *C);
1620 if (!FractSrc)
1621 return false;
1622 IRBuilder<> Builder(&I);
1623 Builder.setFastMathFlags(FPOp->getFastMathFlags());
1624 Fract = applyFractPat(Builder, FractSrc);
1625 } else {
1626 // Match patterns which may appear in legacy implementations of the fract()
1627 // function, built around the nan-avoidant minnum intrinsic. These are the
1628 // core pattern plus additional clamping of inf and nan values on the
1629 // result.
1630 Value *Cond = I.getCondition();
1631 Value *TrueVal = I.getTrueValue();
1632 Value *FalseVal = I.getFalseValue();
1633 Value *CmpVal;
1634 CmpPredicate IsNanPred;
1635
1636 // Match fract pattern with nan check.
1637 if (!match(Cond, m_FCmp(IsNanPred, m_Value(CmpVal), m_NonNaN())))
1638 return false;
1639
1640 IRBuilder<> Builder(&I);
1641 Builder.setFastMathFlags(FPOp->getFastMathFlags());
1642
1643 if (IsNanPred == FCmpInst::FCMP_UNO && TrueVal == CmpVal &&
1644 CmpVal == matchFractPatNanAvoidant(*FalseVal)) {
1645 // isnan(x) ? x : fract(x)
1646 Fract = applyFractPat(Builder, CmpVal);
1647 } else if (IsNanPred == FCmpInst::FCMP_ORD && FalseVal == CmpVal) {
1648 if (CmpVal == matchFractPatNanAvoidant(*TrueVal)) {
1649 // !isnan(x) ? fract(x) : x
1650 Fract = applyFractPat(Builder, CmpVal);
1651 } else {
1652 // Match an intermediate clamp infinity to 0 pattern. i.e.
1653 // !isnan(x) ? (!isinf(x) ? fract(x) : 0.0) : x
1654 CmpPredicate PredInf;
1655 Value *IfNotInf;
1656
1657 if (!match(TrueVal, m_Select(m_FCmp(PredInf, m_FAbs(m_Specific(CmpVal)),
1658 m_PosInf()),
1659 m_Value(IfNotInf), m_PosZeroFP())) ||
1660 PredInf != FCmpInst::FCMP_UNE ||
1661 CmpVal != matchFractPatNanAvoidant(*IfNotInf))
1662 return false;
1663
1664 SelectInst *ClampInfSelect = cast<SelectInst>(TrueVal);
1665
1666 // Insert before the fabs
1667 Value *InsertPt =
1668 cast<Instruction>(ClampInfSelect->getCondition())->getOperand(0);
1669
1671 Value *NewFract = applyFractPat(Builder, CmpVal);
1672 NewFract->takeName(TrueVal);
1673
1674 // Thread the new fract into the inf clamping sequence.
1675 DeadVals.push_back(ClampInfSelect->getOperand(1));
1676 ClampInfSelect->setOperand(1, NewFract);
1677
1678 // The outer select nan handling is also absorbed into the fract.
1679 Fract = ClampInfSelect;
1680 }
1681 } else
1682 return false;
1683 }
1684
1685 Fract->takeName(&I);
1686 I.replaceAllUsesWith(Fract);
1687 DeadVals.push_back(&I);
1688 return true;
1689}
1690
1691static bool areInSameBB(const Value *A, const Value *B) {
1692 const auto *IA = dyn_cast<Instruction>(A);
1693 const auto *IB = dyn_cast<Instruction>(B);
1694 return IA && IB && IA->getParent() == IB->getParent();
1695}
1696
1697// Helper for breaking large PHIs that returns true when an extractelement on V
1698// is likely to be folded away by the DAG combiner.
1700 const auto *FVT = dyn_cast<FixedVectorType>(V->getType());
1701 if (!FVT)
1702 return false;
1703
1704 const Value *CurVal = V;
1705
1706 // Check for insertelements, keeping track of the elements covered.
1707 BitVector EltsCovered(FVT->getNumElements());
1708 while (const auto *IE = dyn_cast<InsertElementInst>(CurVal)) {
1709 const auto *Idx = dyn_cast<ConstantInt>(IE->getOperand(2));
1710
1711 // Non constant index/out of bounds index -> folding is unlikely.
1712 // The latter is more of a sanity check because canonical IR should just
1713 // have replaced those with poison.
1714 if (!Idx || Idx->getZExtValue() >= FVT->getNumElements())
1715 return false;
1716
1717 const auto *VecSrc = IE->getOperand(0);
1718
1719 // If the vector source is another instruction, it must be in the same basic
1720 // block. Otherwise, the DAGCombiner won't see the whole thing and is
1721 // unlikely to be able to do anything interesting here.
1722 if (isa<Instruction>(VecSrc) && !areInSameBB(VecSrc, IE))
1723 return false;
1724
1725 CurVal = VecSrc;
1726 EltsCovered.set(Idx->getZExtValue());
1727
1728 // All elements covered.
1729 if (EltsCovered.all())
1730 return true;
1731 }
1732
1733 // We either didn't find a single insertelement, or the insertelement chain
1734 // ended before all elements were covered. Check for other interesting values.
1735
1736 // Constants are always interesting because we can just constant fold the
1737 // extractelements.
1738 if (isa<Constant>(CurVal))
1739 return true;
1740
1741 // shufflevector is likely to be profitable if either operand is a constant,
1742 // or if either source is in the same block.
1743 // This is because shufflevector is most often lowered as a series of
1744 // insert/extract elements anyway.
1745 if (const auto *SV = dyn_cast<ShuffleVectorInst>(CurVal)) {
1746 return isa<Constant>(SV->getOperand(1)) ||
1747 areInSameBB(SV, SV->getOperand(0)) ||
1748 areInSameBB(SV, SV->getOperand(1));
1749 }
1750
1751 return false;
1752}
1753
1754static void collectPHINodes(const PHINode &I,
1756 const auto [It, Inserted] = SeenPHIs.insert(&I);
1757 if (!Inserted)
1758 return;
1759
1760 for (const Value *Inc : I.incoming_values()) {
1761 if (const auto *PhiInc = dyn_cast<PHINode>(Inc))
1762 collectPHINodes(*PhiInc, SeenPHIs);
1763 }
1764
1765 for (const User *U : I.users()) {
1766 if (const auto *PhiU = dyn_cast<PHINode>(U))
1767 collectPHINodes(*PhiU, SeenPHIs);
1768 }
1769}
1770
1771bool AMDGPUCodeGenPrepareImpl::canBreakPHINode(const PHINode &I) {
1772 // Check in the cache first.
1773 if (const auto It = BreakPhiNodesCache.find(&I);
1774 It != BreakPhiNodesCache.end())
1775 return It->second;
1776
1777 // We consider PHI nodes as part of "chains", so given a PHI node I, we
1778 // recursively consider all its users and incoming values that are also PHI
1779 // nodes. We then make a decision about all of those PHIs at once. Either they
1780 // all get broken up, or none of them do. That way, we avoid cases where a
1781 // single PHI is/is not broken and we end up reforming/exploding a vector
1782 // multiple times, or even worse, doing it in a loop.
1783 SmallPtrSet<const PHINode *, 8> WorkList;
1784 collectPHINodes(I, WorkList);
1785
1786#ifndef NDEBUG
1787 // Check that none of the PHI nodes in the worklist are in the map. If some of
1788 // them are, it means we're not good enough at collecting related PHIs.
1789 for (const PHINode *WLP : WorkList) {
1790 assert(BreakPhiNodesCache.count(WLP) == 0);
1791 }
1792#endif
1793
1794 // To consider a PHI profitable to break, we need to see some interesting
1795 // incoming values. At least 2/3rd (rounded up) of all PHIs in the worklist
1796 // must have one to consider all PHIs breakable.
1797 //
1798 // This threshold has been determined through performance testing.
1799 //
1800 // Note that the computation below is equivalent to
1801 //
1802 // (unsigned)ceil((K / 3.0) * 2)
1803 //
1804 // It's simply written this way to avoid mixing integral/FP arithmetic.
1805 const auto Threshold = (alignTo(WorkList.size() * 2, 3) / 3);
1806 unsigned NumBreakablePHIs = 0;
1807 bool CanBreak = false;
1808 for (const PHINode *Cur : WorkList) {
1809 // Don't break PHIs that have no interesting incoming values. That is, where
1810 // there is no clear opportunity to fold the "extractelement" instructions
1811 // we would add.
1812 //
1813 // Note: IC does not run after this pass, so we're only interested in the
1814 // foldings that the DAG combiner can do.
1815 if (any_of(Cur->incoming_values(), isInterestingPHIIncomingValue)) {
1816 if (++NumBreakablePHIs >= Threshold) {
1817 CanBreak = true;
1818 break;
1819 }
1820 }
1821 }
1822
1823 for (const PHINode *Cur : WorkList)
1824 BreakPhiNodesCache[Cur] = CanBreak;
1825
1826 return CanBreak;
1827}
1828
1829/// Helper class for "break large PHIs" (visitPHINode).
1830///
1831/// This represents a slice of a PHI's incoming value, which is made up of:
1832/// - The type of the slice (Ty)
1833/// - The index in the incoming value's vector where the slice starts (Idx)
1834/// - The number of elements in the slice (NumElts).
1835/// It also keeps track of the NewPHI node inserted for this particular slice.
1836///
1837/// Slice examples:
1838/// <4 x i64> -> Split into four i64 slices.
1839/// -> [i64, 0, 1], [i64, 1, 1], [i64, 2, 1], [i64, 3, 1]
1840/// <5 x i16> -> Split into 2 <2 x i16> slices + a i16 tail.
1841/// -> [<2 x i16>, 0, 2], [<2 x i16>, 2, 2], [i16, 4, 1]
1843public:
1844 VectorSlice(Type *Ty, unsigned Idx, unsigned NumElts)
1845 : Ty(Ty), Idx(Idx), NumElts(NumElts) {}
1846
1847 Type *Ty = nullptr;
1848 unsigned Idx = 0;
1849 unsigned NumElts = 0;
1850 PHINode *NewPHI = nullptr;
1851
1852 /// Slice \p Inc according to the information contained within this slice.
1853 /// This is cached, so if called multiple times for the same \p BB & \p Inc
1854 /// pair, it returns the same Sliced value as well.
1855 ///
1856 /// Note this *intentionally* does not return the same value for, say,
1857 /// [%bb.0, %0] & [%bb.1, %0] as:
1858 /// - It could cause issues with dominance (e.g. if bb.1 is seen first, then
1859 /// the value in bb.1 may not be reachable from bb.0 if it's its
1860 /// predecessor.)
1861 /// - We also want to make our extract instructions as local as possible so
1862 /// the DAG has better chances of folding them out. Duplicating them like
1863 /// that is beneficial in that regard.
1864 ///
1865 /// This is both a minor optimization to avoid creating duplicate
1866 /// instructions, but also a requirement for correctness. It is not forbidden
1867 /// for a PHI node to have the same [BB, Val] pair multiple times. If we
1868 /// returned a new value each time, those previously identical pairs would all
1869 /// have different incoming values (from the same block) and it'd cause a "PHI
1870 /// node has multiple entries for the same basic block with different incoming
1871 /// values!" verifier error.
1872 Value *getSlicedVal(BasicBlock *BB, Value *Inc, StringRef NewValName) {
1873 Value *&Res = SlicedVals[{BB, Inc}];
1874 if (Res)
1875 return Res;
1876
1878 if (Instruction *IncInst = dyn_cast<Instruction>(Inc))
1879 B.SetCurrentDebugLocation(IncInst->getDebugLoc());
1880
1881 if (NumElts > 1) {
1883 for (unsigned K = Idx; K < (Idx + NumElts); ++K)
1884 Mask.push_back(K);
1885 Res = B.CreateShuffleVector(Inc, Mask, NewValName);
1886 } else
1887 Res = B.CreateExtractElement(Inc, Idx, NewValName);
1888
1889 return Res;
1890 }
1891
1892private:
1894};
1895
1896bool AMDGPUCodeGenPrepareImpl::visitPHINode(PHINode &I) {
1897 // Break-up fixed-vector PHIs into smaller pieces.
1898 // Default threshold is 32, so it breaks up any vector that's >32 bits into
1899 // its elements, or into 32-bit pieces (for 8/16 bit elts).
1900 //
1901 // This is only helpful for DAGISel because it doesn't handle large PHIs as
1902 // well as GlobalISel. DAGISel lowers PHIs by using CopyToReg/CopyFromReg.
1903 // With large, odd-sized PHIs we may end up needing many `build_vector`
1904 // operations with most elements being "undef". This inhibits a lot of
1905 // optimization opportunities and can result in unreasonably high register
1906 // pressure and the inevitable stack spilling.
1907 if (!CLOpts.codegenprepare_break_large_phis ||
1908 getCGPassBuilderOption(TM).EnableGlobalISelOption ==
1909 cl::boolOrDefault::BOU_TRUE)
1910 return false;
1911
1912 FixedVectorType *FVT = dyn_cast<FixedVectorType>(I.getType());
1913 if (!FVT || FVT->getNumElements() == 1 ||
1914 DL.getTypeSizeInBits(FVT) <=
1915 CLOpts.codegenprepare_break_large_phis_threshold)
1916 return false;
1917
1918 if (!CLOpts.codegenprepare_force_break_large_phis && !canBreakPHINode(I))
1919 return false;
1920
1921 std::vector<VectorSlice> Slices;
1922
1923 Type *EltTy = FVT->getElementType();
1924 {
1925 unsigned Idx = 0;
1926 // For 8/16 bits type, don't scalarize fully but break it up into as many
1927 // 32-bit slices as we can, and scalarize the tail.
1928 const unsigned EltSize = DL.getTypeSizeInBits(EltTy);
1929 const unsigned NumElts = FVT->getNumElements();
1930 if (EltSize == 8 || EltSize == 16) {
1931 const unsigned SubVecSize = (32 / EltSize);
1932 Type *SubVecTy = FixedVectorType::get(EltTy, SubVecSize);
1933 for (unsigned End = alignDown(NumElts, SubVecSize); Idx < End;
1934 Idx += SubVecSize)
1935 Slices.emplace_back(SubVecTy, Idx, SubVecSize);
1936 }
1937
1938 // Scalarize all remaining elements.
1939 for (; Idx < NumElts; ++Idx)
1940 Slices.emplace_back(EltTy, Idx, 1);
1941 }
1942
1943 assert(Slices.size() > 1);
1944
1945 // Create one PHI per vector piece. The "VectorSlice" class takes care of
1946 // creating the necessary instruction to extract the relevant slices of each
1947 // incoming value.
1948 IRBuilder<> B(I.getParent());
1949 B.SetCurrentDebugLocation(I.getDebugLoc());
1950
1951 unsigned IncNameSuffix = 0;
1952 for (VectorSlice &S : Slices) {
1953 // We need to reset the build on each iteration, because getSlicedVal may
1954 // have inserted something into I's BB.
1955 B.SetInsertPoint(I.getParent()->getFirstNonPHIIt());
1956 S.NewPHI = B.CreatePHI(S.Ty, I.getNumIncomingValues());
1957
1958 for (const auto &[Idx, BB] : enumerate(I.blocks())) {
1959 S.NewPHI->addIncoming(S.getSlicedVal(BB, I.getIncomingValue(Idx),
1960 "largephi.extractslice" +
1961 std::to_string(IncNameSuffix++)),
1962 BB);
1963 }
1964 }
1965
1966 // And replace this PHI with a vector of all the previous PHI values.
1967 Value *Vec = PoisonValue::get(FVT);
1968 unsigned NameSuffix = 0;
1969 for (VectorSlice &S : Slices) {
1970 const auto ValName = "largephi.insertslice" + std::to_string(NameSuffix++);
1971 if (S.NumElts > 1)
1972 Vec = B.CreateInsertVector(FVT, Vec, S.NewPHI, S.Idx, ValName);
1973 else
1974 Vec = B.CreateInsertElement(Vec, S.NewPHI, S.Idx, ValName);
1975 }
1976
1977 I.replaceAllUsesWith(Vec);
1978 DeadVals.push_back(&I);
1979 return true;
1980}
1981
1982/// \param V Value to check
1983/// \param DL DataLayout
1984/// \param TM TargetMachine (TODO: remove once DL contains nullptr values)
1985/// \param AS Target Address Space
1986/// \return true if \p V cannot be the null value of \p AS, false otherwise.
1987static bool isPtrKnownNeverNull(const Value *V, const DataLayout &DL,
1988 const AMDGPUTargetMachine &TM, unsigned AS) {
1989 // Pointer cannot be null if it's a block address, GV or alloca.
1990 // NOTE: We don't support extern_weak, but if we did, we'd need to check for
1991 // it as the symbol could be null in such cases.
1993 return true;
1994
1995 // Check nonnull arguments.
1996 if (const auto *Arg = dyn_cast<Argument>(V); Arg && Arg->hasNonNullAttr())
1997 return true;
1998
1999 // Check nonnull loads.
2000 if (const auto *Load = dyn_cast<LoadInst>(V);
2001 Load && Load->hasMetadata(LLVMContext::MD_nonnull))
2002 return true;
2003
2004 // getUnderlyingObject may have looked through another addrspacecast, although
2005 // the optimizable situations most likely folded out by now.
2006 if (AS != cast<PointerType>(V->getType())->getAddressSpace())
2007 return false;
2008
2009 // TODO: Calls that return nonnull?
2010
2011 // For all other things, use KnownBits.
2012 // We either use 0 or all bits set to indicate null, so check whether the
2013 // value can be zero or all ones.
2014 //
2015 // TODO: Use ValueTracking's isKnownNeverNull if it becomes aware that some
2016 // address spaces have non-zero null values.
2017 auto SrcPtrKB = computeKnownBits(V, DL);
2018 const auto NullVal = AMDGPU::getNullPointerValue(AS);
2019
2020 assert(SrcPtrKB.getBitWidth() == DL.getPointerSizeInBits(AS));
2021 assert((NullVal == 0 || NullVal == -1) &&
2022 "don't know how to check for this null value!");
2023 return NullVal ? !SrcPtrKB.getMaxValue().isAllOnes() : SrcPtrKB.isNonZero();
2024}
2025
2026bool AMDGPUCodeGenPrepareImpl::visitAddrSpaceCastInst(AddrSpaceCastInst &I) {
2027 // TODO: This is target-independent reasoning about the source pointer being
2028 // non-null, and would fit better in a generic pass such as
2029 // AggressiveInstCombine. It lives here for now because proving the source is
2030 // not the null value requires knowing the numeric null pointer value of the
2031 // source address space, which is not yet a first-class IR concept.
2032
2033 // If the flag is already set there is nothing to do.
2034 if (I.hasNonNull())
2035 return false;
2036
2037 // It is often difficult to prove that a vector of pointers cannot have any
2038 // nulls in it, so it's unclear if it's worth supporting.
2039 if (I.getType()->isVectorTy())
2040 return false;
2041
2042 // The nonnull flag only affects the lowering of casts from/to priv/local to
2043 // flat, so only bother proving non-null for those.
2044 const unsigned SrcAS = I.getSrcAddressSpace();
2045 const unsigned DstAS = I.getDestAddressSpace();
2046
2047 bool CanLower = false;
2048 if (SrcAS == AMDGPUAS::FLAT_ADDRESS)
2049 CanLower = (DstAS == AMDGPUAS::LOCAL_ADDRESS ||
2050 DstAS == AMDGPUAS::PRIVATE_ADDRESS);
2051 else if (DstAS == AMDGPUAS::FLAT_ADDRESS)
2052 CanLower = (SrcAS == AMDGPUAS::LOCAL_ADDRESS ||
2053 SrcAS == AMDGPUAS::PRIVATE_ADDRESS);
2054 if (!CanLower)
2055 return false;
2056
2058 getUnderlyingObjects(I.getOperand(0), WorkList);
2059 if (!all_of(WorkList, [&](const Value *V) {
2060 return isPtrKnownNeverNull(V, DL, TM, SrcAS);
2061 }))
2062 return false;
2063
2064 I.setNonNull();
2065 return true;
2066}
2067
2068bool AMDGPUCodeGenPrepareImpl::visitIntrinsicInst(IntrinsicInst &I) {
2069 Intrinsic::ID IID = I.getIntrinsicID();
2070 switch (IID) {
2071 case Intrinsic::minnum:
2072 case Intrinsic::minimumnum:
2073 case Intrinsic::minimum:
2074 return visitFMinLike(I);
2075 case Intrinsic::sqrt:
2076 return visitSqrt(I);
2077 case Intrinsic::log:
2078 case Intrinsic::log10:
2079 return visitLog(cast<FPMathOperator>(I), IID);
2080 case Intrinsic::log2:
2081 // No reason to handle log2.
2082 return false;
2083 case Intrinsic::amdgcn_mbcnt_lo:
2084 return visitMbcntLo(I);
2085 case Intrinsic::amdgcn_mbcnt_hi:
2086 return visitMbcntHi(I);
2087 case Intrinsic::vector_reduce_add:
2088 return visitVectorReduceAdd(I);
2089 case Intrinsic::uadd_sat:
2090 case Intrinsic::sadd_sat:
2091 return visitSaturatingAdd(I);
2092 default:
2093 return false;
2094 }
2095}
2096
2097/// Match the core sequence in the fract pattern (x - floor(x), which doesn't
2098/// need to consider edge case handling.
2099Value *AMDGPUCodeGenPrepareImpl::matchFractPatImpl(Value &FractSrc,
2100 const APFloat &C) const {
2101 if (ST.hasFractBug())
2102 return nullptr;
2103
2104 Type *Ty = FractSrc.getType();
2105 if (!isLegalFloatingTy(Ty->getScalarType()))
2106 return nullptr;
2107
2108 APFloat OneNextDown = APFloat::getOne(C.getSemantics());
2109 OneNextDown.next(true);
2110
2111 // Match nextafter(1.0, -1)
2112 if (OneNextDown != C)
2113 return nullptr;
2114
2115 Value *FloorSrc;
2116 if (match(&FractSrc, m_FSub(m_Value(FloorSrc), m_Intrinsic<Intrinsic::floor>(
2117 m_Deferred(FloorSrc)))))
2118 return FloorSrc;
2119 return nullptr;
2120}
2121
2122/// Match non-nan fract pattern.
2123// MIN_CONSTANT = nextafter(1.0, -1.0)
2124/// minnum(fsub(x, floor(x)), MIN_CONSTANT)
2125/// minimumnum(fsub(x, floor(x)), MIN_CONSTANT)
2126/// minimum(fsub(x, floor(x)), MIN_CONSTANT)
2127
2128// x_sub_floor >= MIN_CONSTANT ? MIN_CONSTANT : x_sub_floor;
2129///
2130/// If fract is a useful instruction for the subtarget. Does not account for the
2131/// nan handling; the instruction has a nan check on the input value.
2132Value *AMDGPUCodeGenPrepareImpl::matchFractPatNanAvoidant(Value &V) {
2133 Value *Arg0;
2134 const APFloat *C;
2135
2136 // The value is only used in contexts where we know the input isn't a nan, so
2137 // any of the fmin variants are fine.
2138 if (!match(&V,
2142 return nullptr;
2143
2144 return matchFractPatImpl(*Arg0, *C);
2145}
2146
2147Value *AMDGPUCodeGenPrepareImpl::applyFractPat(IRBuilder<> &Builder,
2148 Value *FractArg) {
2149 SmallVector<Value *, 4> FractVals;
2150 extractValues(Builder, FractVals, FractArg);
2151
2152 SmallVector<Value *, 4> ResultVals(FractVals.size());
2153
2154 Type *Ty = FractArg->getType()->getScalarType();
2155 for (unsigned I = 0, E = FractVals.size(); I != E; ++I) {
2156 ResultVals[I] =
2157 Builder.CreateIntrinsic(Intrinsic::amdgcn_fract, {Ty}, {FractVals[I]});
2158 }
2159
2160 return insertValues(Builder, FractArg->getType(), ResultVals);
2161}
2162
2163bool AMDGPUCodeGenPrepareImpl::visitFMinLike(IntrinsicInst &I) {
2164 const APFloat *C;
2165 Value *FractArg;
2166
2167 // minimum(x - floor(x), MIN_CONSTANT)
2168 Value *X;
2169 if (!ST.hasFractBug() &&
2171 FractArg = matchFractPatImpl(*X, *C);
2172 if (!FractArg)
2173 return false;
2174 } else {
2175 // minnum(x - floor(x), MIN_CONSTANT)
2176 FractArg = matchFractPatNanAvoidant(I);
2177 if (!FractArg)
2178 return false;
2179
2180 // Match pattern for fract intrinsic in contexts where the nan check has
2181 // been optimized out (and hope the knowledge the source can't be nan wasn't
2182 // lost).
2183 if (!I.hasNoNaNs() && !isKnownNeverNaN(FractArg, SQ.getWithInstruction(&I)))
2184 return false;
2185 }
2186
2187 IRBuilder<> Builder(&I);
2188 FastMathFlags FMF = I.getFastMathFlags();
2189 FMF.setNoNaNs();
2190 Builder.setFastMathFlags(FMF);
2191
2192 Value *Fract = applyFractPat(Builder, FractArg);
2193 Fract->takeName(&I);
2194 I.replaceAllUsesWith(Fract);
2195 DeadVals.push_back(&I);
2196 return true;
2197}
2198
2199// Expand llvm.sqrt.f32 calls with !fpmath metadata in a semi-fast way.
2200bool AMDGPUCodeGenPrepareImpl::visitSqrt(IntrinsicInst &Sqrt) {
2201 Type *Ty = Sqrt.getType()->getScalarType();
2202 if (!Ty->isFloatTy())
2203 return false;
2204
2205 const FPMathOperator *FPOp = cast<const FPMathOperator>(&Sqrt);
2206 FastMathFlags SqrtFMF = FPOp->getFastMathFlags();
2207
2208 // We're trying to handle the fast-but-not-that-fast case only. The lowering
2209 // of fast llvm.sqrt will give the raw instruction anyway.
2210 if (SqrtFMF.approxFunc())
2211 return false;
2212
2213 const float ReqdAccuracy = FPOp->getFPAccuracy();
2214
2215 // Defer correctly rounded expansion to codegen.
2216 if (ReqdAccuracy < 1.0f)
2217 return false;
2218
2219 Value *SrcVal = Sqrt.getOperand(0);
2220 bool CanTreatAsDAZ = canIgnoreDenormalInput(SrcVal, &Sqrt);
2221
2222 // The raw instruction is 1 ulp, but the correction for denormal handling
2223 // brings it to 2.
2224 if (!CanTreatAsDAZ && ReqdAccuracy < 2.0f)
2225 return false;
2226
2227 IRBuilder<> Builder(&Sqrt);
2228 SmallVector<Value *, 4> SrcVals;
2229 extractValues(Builder, SrcVals, SrcVal);
2230
2231 SmallVector<Value *, 4> ResultVals(SrcVals.size());
2232 for (int I = 0, E = SrcVals.size(); I != E; ++I) {
2233 if (CanTreatAsDAZ)
2234 ResultVals[I] = Builder.CreateCall(getSqrtF32(), SrcVals[I]);
2235 else
2236 ResultVals[I] = emitSqrtIEEE2ULP(Builder, SrcVals[I], SqrtFMF);
2237 }
2238
2239 Value *NewSqrt = insertValues(Builder, Sqrt.getType(), ResultVals);
2240 NewSqrt->takeName(&Sqrt);
2241 Sqrt.replaceAllUsesWith(NewSqrt);
2242 DeadVals.push_back(&Sqrt);
2243 return true;
2244}
2245
2246/// Replace log and log10 intrinsic calls based on fpmath metadata.
2247bool AMDGPUCodeGenPrepareImpl::visitLog(FPMathOperator &Log,
2248 Intrinsic::ID IID) {
2249 Type *Ty = Log.getType();
2250 if (!Ty->getScalarType()->isHalfTy() || !ST.has16BitInsts())
2251 return false;
2252
2253 FastMathFlags FMF = Log.getFastMathFlags();
2254
2255 // Defer fast math cases to codegen.
2256 if (FMF.approxFunc())
2257 return false;
2258
2259 // Limit experimentally determined from OpenCL conformance test (1.79)
2260 if (Log.getFPAccuracy() < 1.80f)
2261 return false;
2262
2263 IRBuilder<> Builder(&cast<CallInst>(Log));
2264
2265 // Use the generic intrinsic for convenience in the vector case. Codegen will
2266 // recognize the denormal handling is not necessary from the fpext.
2267 // TODO: Move to generic code
2268 Value *Log2 =
2269 Builder.CreateUnaryIntrinsic(Intrinsic::log2, Log.getOperand(0), FMF);
2270
2271 double Log2BaseInverted =
2272 IID == Intrinsic::log10 ? numbers::ln2 / numbers::ln10 : numbers::ln2;
2273 Value *Mul =
2274 Builder.CreateFMulFMF(Log2, ConstantFP::get(Ty, Log2BaseInverted), FMF);
2275
2276 Mul->takeName(&Log);
2277
2278 Log.replaceAllUsesWith(Mul);
2279 DeadVals.push_back(&Log);
2280 return true;
2281}
2282
2283bool AMDGPUCodeGenPrepare::runOnFunction(Function &F) {
2284 if (skipFunction(F))
2285 return false;
2286
2287 auto *TPC = getAnalysisIfAvailable<TargetPassConfig>();
2288 if (!TPC)
2289 return false;
2290
2291 const AMDGPUTargetMachine &TM = TPC->getTM<AMDGPUTargetMachine>();
2292 const TargetTransformInfo &TTI =
2293 getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
2294 const TargetLibraryInfo *TLI =
2295 &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(F);
2296 AssumptionCache *AC =
2297 &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
2298 auto *DTWP = getAnalysisIfAvailable<DominatorTreeWrapperPass>();
2299 const DominatorTree *DT = DTWP ? &DTWP->getDomTree() : nullptr;
2300 const UniformityInfo &UA =
2301 getAnalysis<UniformityInfoWrapperPass>().getUniformityInfo();
2302 return AMDGPUCodeGenPrepareImpl(F, TM, TTI, TLI, AC, DT, UA, ExpandDiv64InIR)
2303 .run();
2304}
2305
2308 const AMDGPUTargetMachine &ATM = static_cast<const AMDGPUTargetMachine &>(TM);
2309 const TargetTransformInfo &TTI = FAM.getResult<TargetIRAnalysis>(F);
2310 const TargetLibraryInfo *TLI = &FAM.getResult<TargetLibraryAnalysis>(F);
2311 AssumptionCache *AC = &FAM.getResult<AssumptionAnalysis>(F);
2312 const DominatorTree *DT = FAM.getCachedResult<DominatorTreeAnalysis>(F);
2313 const UniformityInfo &UA = FAM.getResult<UniformityInfoAnalysis>(F);
2314 AMDGPUCodeGenPrepareImpl Impl(F, ATM, TTI, TLI, AC, DT, UA,
2315 ATM.getCLOpts().codegenprepare_expand_div64);
2316 if (!Impl.run())
2317 return PreservedAnalyses::all();
2319 if (!Impl.FlowChanged)
2321 return PA;
2322}
2323
2324INITIALIZE_PASS_BEGIN(AMDGPUCodeGenPrepare, DEBUG_TYPE,
2325 "AMDGPU IR optimizations", false, false)
2330INITIALIZE_PASS_END(AMDGPUCodeGenPrepare, DEBUG_TYPE, "AMDGPU IR optimizations",
2332
2333/// Create a workitem.id.x intrinsic call with range metadata.
2334CallInst *AMDGPUCodeGenPrepareImpl::createWorkitemIdX(IRBuilder<> &B) const {
2335 CallInst *Tid =
2336 B.CreateIntrinsicWithoutFolding(Intrinsic::amdgcn_workitem_id_x, {});
2337 ST.makeLIDRangeMetadata(Tid);
2338 return Tid;
2339}
2340
2341/// Replace the instruction with a direct workitem.id.x call.
2342void AMDGPUCodeGenPrepareImpl::replaceWithWorkitemIdX(Instruction &I) const {
2343 IRBuilder<> B(&I);
2344 CallInst *Tid = createWorkitemIdX(B);
2346 ReplaceInstWithValue(BI, Tid);
2347}
2348
2349/// Replace the instruction with (workitem.id.x & mask).
2350void AMDGPUCodeGenPrepareImpl::replaceWithMaskedWorkitemIdX(
2351 Instruction &I, unsigned WaveSize) const {
2352 IRBuilder<> B(&I);
2353 CallInst *Tid = createWorkitemIdX(B);
2354 Constant *Mask = ConstantInt::get(Tid->getType(), WaveSize - 1);
2355 Value *AndInst = B.CreateAnd(Tid, Mask);
2357 ReplaceInstWithValue(BI, AndInst);
2358}
2359
2360/// Try to optimize mbcnt instruction by replacing with workitem.id.x when
2361/// work group size allows direct computation of lane ID.
2362/// Returns true if optimization was applied, false otherwise.
2363bool AMDGPUCodeGenPrepareImpl::tryReplaceWithWorkitemId(Instruction &I,
2364 unsigned Wave) const {
2365 std::optional<unsigned> MaybeX = ST.getReqdWorkGroupSize(F, 0);
2366 if (!MaybeX)
2367 return false;
2368
2369 // When work group size == wave_size, each work group contains exactly one
2370 // wave, so the instruction can be replaced with workitem.id.x directly.
2371 if (*MaybeX == Wave) {
2372 replaceWithWorkitemIdX(I);
2373 return true;
2374 }
2375
2376 // When work group evenly splits into waves, compute lane ID within wave
2377 // using bit masking: lane_id = workitem.id.x & (wave_size - 1).
2378 if (ST.hasWavefrontsEvenlySplittingXDim(F, /*RequiresUniformYZ=*/true)) {
2379 replaceWithMaskedWorkitemIdX(I, Wave);
2380 return true;
2381 }
2382
2383 return false;
2384}
2385
2386/// Optimize mbcnt.lo calls on wave32 architectures for lane ID computation.
2387bool AMDGPUCodeGenPrepareImpl::visitMbcntLo(IntrinsicInst &I) const {
2388 // This optimization only applies to wave32 targets where mbcnt.lo operates on
2389 // the full execution mask.
2390 if (!ST.isWave32())
2391 return false;
2392
2393 // Only optimize the pattern mbcnt.lo(~0, 0) which counts active lanes with
2394 // lower IDs.
2395 if (!match(&I,
2397 return false;
2398
2399 return tryReplaceWithWorkitemId(I, ST.getWavefrontSize());
2400}
2401
2402/// Optimize mbcnt.hi calls for lane ID computation.
2403bool AMDGPUCodeGenPrepareImpl::visitMbcntHi(IntrinsicInst &I) const {
2404 // Abort if wave size is not known at compile time.
2405 if (!ST.isWaveSizeKnown())
2406 return false;
2407
2408 unsigned Wave = ST.getWavefrontSize();
2409
2410 // On wave32, the upper 32 bits of execution mask are always 0, so
2411 // mbcnt.hi(mask, val) always returns val unchanged.
2412 if (ST.isWave32()) {
2414 ReplaceInstWithValue(BI, I.getArgOperand(1));
2415 return true;
2416 }
2417
2418 // Optimize the complete lane ID computation pattern:
2419 // mbcnt.hi(~0, mbcnt.lo(~0, 0)) which counts all active lanes with lower IDs
2420 // across the full execution mask.
2421 using namespace PatternMatch;
2422
2423 // Check for pattern: mbcnt.hi(~0, mbcnt.lo(~0, 0))
2426 m_AllOnes(), m_Zero()))))
2427 return false;
2428
2429 return tryReplaceWithWorkitemId(I, Wave);
2430}
2431
2432/// Check if type is <4 x i8>.
2433static bool isV4I8(Type *Ty) {
2435 return VTy && VTy->getNumElements() == 4 &&
2436 VTy->getElementType()->isIntegerTy(8);
2437}
2438
2439/// Helper to match the dot4 pattern: mul(zext/sext <4 x i8>, zext/sext <4 x
2440/// i8>) Returns true if pattern matches and signedness matches IsSigned.
2441/// Sets A, B to the <4 x i8> sources.
2442static bool matchDot4Pattern(Value *MulOp, Value *&A, Value *&B,
2443 bool IsSigned) {
2444 Value *Src0, *Src1;
2445 if (!match(MulOp, m_Mul(m_Value(Src0), m_Value(Src1))))
2446 return false;
2447
2448 // Check that result type is <4 x i32>
2450 if (!MulTy || MulTy->getNumElements() != 4 ||
2451 !MulTy->getElementType()->isIntegerTy(32))
2452 return false;
2453
2454 // Match zext or sext based on IsSigned
2455 Value *ExtSrc0, *ExtSrc1;
2456 if (IsSigned) {
2457 if (!match(Src0, m_SExt(m_Value(ExtSrc0))) || !isV4I8(ExtSrc0->getType()))
2458 return false;
2459 if (!match(Src1, m_SExt(m_Value(ExtSrc1))) || !isV4I8(ExtSrc1->getType()))
2460 return false;
2461 } else {
2462 if (!match(Src0, m_ZExt(m_Value(ExtSrc0))) || !isV4I8(ExtSrc0->getType()))
2463 return false;
2464 if (!match(Src1, m_ZExt(m_Value(ExtSrc1))) || !isV4I8(ExtSrc1->getType()))
2465 return false;
2466 }
2467
2468 A = ExtSrc0;
2469 B = ExtSrc1;
2470 return true;
2471}
2472
2473/// Try to convert vector.reduce.add(mul(zext/sext <4 x i8>, zext/sext <4 x
2474/// i8>)) to a dot4 intrinsic call (non-saturating case only).
2475bool AMDGPUCodeGenPrepareImpl::visitVectorReduceAdd(IntrinsicInst &I) {
2476 // Check if we have dot4 instructions available
2477 if (!ST.hasDot7Insts() || (!ST.hasDot1Insts() && !ST.hasDot8Insts()))
2478 return false;
2479
2480 Value *A = nullptr, *B = nullptr;
2481
2482 // Try unsigned first, then signed
2483 bool IsSigned = false;
2484 if (!matchDot4Pattern(I.getArgOperand(0), A, B, /*IsSigned=*/false)) {
2485 if (!matchDot4Pattern(I.getArgOperand(0), A, B, /*IsSigned=*/true))
2486 return false;
2487 IsSigned = true;
2488 }
2489
2490 LLVMContext &Ctx = I.getContext();
2491 Type *I32Ty = Type::getInt32Ty(Ctx);
2492 IRBuilder<> Builder(&I);
2493
2494 // Bitcast <4 x i8> to i32
2495 Value *ASrc = Builder.CreateBitCast(A, I32Ty);
2496 Value *BSrc = Builder.CreateBitCast(B, I32Ty);
2497
2498 // Non-saturating case: accumulator is 0, clamp is false
2499 Value *Acc = ConstantInt::get(I32Ty, 0);
2500 Value *Clamp = ConstantInt::getFalse(Ctx);
2501
2502 Intrinsic::ID DotIID =
2503 IsSigned ? Intrinsic::amdgcn_sdot4 : Intrinsic::amdgcn_udot4;
2504
2505 Value *Dot = Builder.CreateIntrinsic(DotIID, {}, {ASrc, BSrc, Acc, Clamp});
2506 Dot->takeName(&I);
2507
2508 I.replaceAllUsesWith(Dot);
2509 DeadVals.push_back(&I);
2510
2511 return true;
2512}
2513
2514/// Try to convert uadd.sat/sadd.sat(vector.reduce.add(mul(...)), c) to a
2515/// saturating dot4 intrinsic. This combine starts at the root (saturating add)
2516/// and looks at its operands.
2517bool AMDGPUCodeGenPrepareImpl::visitSaturatingAdd(IntrinsicInst &I) {
2518 // Check if we have dot4 instructions available
2519 if (!ST.hasDot7Insts() || (!ST.hasDot1Insts() && !ST.hasDot8Insts()))
2520 return false;
2521
2522 Intrinsic::ID IID = I.getIntrinsicID();
2523 bool IsSigned = (IID == Intrinsic::sadd_sat);
2524
2525 // Look for vector.reduce.add as one of the operands (commutative match)
2526 Value *Op0 = I.getArgOperand(0);
2527 Value *Op1 = I.getArgOperand(1);
2528 Value *MulOp = nullptr;
2529 Value *Accum = nullptr;
2530 IntrinsicInst *ReduceInst = nullptr;
2531
2533 ReduceInst = cast<IntrinsicInst>(Op0);
2534 Accum = Op1;
2535 } else if (match(Op1,
2537 ReduceInst = cast<IntrinsicInst>(Op1);
2538 Accum = Op0;
2539 } else {
2540 return false;
2541 }
2542
2543 Value *A = nullptr, *B = nullptr;
2544
2545 if (!matchDot4Pattern(MulOp, A, B, IsSigned))
2546 return false;
2547
2548 LLVMContext &Ctx = I.getContext();
2549 Type *I32Ty = Type::getInt32Ty(Ctx);
2550 IRBuilder<> Builder(&I);
2551
2552 // Bitcast <4 x i8> to i32
2553 Value *ASrc = Builder.CreateBitCast(A, I32Ty);
2554 Value *BSrc = Builder.CreateBitCast(B, I32Ty);
2555
2556 // Saturating case: use the accumulator and set clamp to true
2557 Value *Clamp = ConstantInt::getTrue(Ctx);
2558
2559 Intrinsic::ID DotIID =
2560 IsSigned ? Intrinsic::amdgcn_sdot4 : Intrinsic::amdgcn_udot4;
2561
2562 Value *Dot = Builder.CreateIntrinsic(DotIID, {}, {ASrc, BSrc, Accum, Clamp});
2563 Dot->takeName(&I);
2564
2565 I.replaceAllUsesWith(Dot);
2566 DeadVals.push_back(&I);
2567 // The reduce.add will be dead after this and cleaned up later
2568 if (ReduceInst->use_empty())
2569 DeadVals.push_back(ReduceInst);
2570
2571 return true;
2572}
2573
2574char AMDGPUCodeGenPrepare::ID = 0;
2575
2577 return new AMDGPUCodeGenPrepare(ExpandDiv64InIR);
2578}
const TargetLowering & TLI
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
const AArch64InstrInfo MachineBasicBlock::iterator InsertPt
static Value * insertValues(IRBuilder<> &Builder, Type *Ty, SmallVectorImpl< Value * > &Values)
static void extractValues(IRBuilder<> &Builder, SmallVectorImpl< Value * > &Values, Value *V)
static Value * getMulHu(IRBuilder<> &Builder, Value *LHS, Value *RHS)
static bool isInterestingPHIIncomingValue(const Value *V)
static SelectInst * findSelectThroughCast(Value *V, CastInst *&Cast)
static bool matchDot4Pattern(Value *MulOp, Value *&A, Value *&B, bool IsSigned)
Helper to match the dot4 pattern: mul(zext/sext <4 x i8>, zext/sext <4 x i8>) Returns true if pattern...
static bool isV4I8(Type *Ty)
Check if type is <4 x i8>.
static std::pair< Value *, Value * > getMul64(IRBuilder<> &Builder, Value *LHS, Value *RHS)
static Value * emitRsqIEEE1ULP(IRBuilder<> &Builder, Value *Src, bool IsNegative)
Emit an expansion of 1.0 / sqrt(Src) good for 1ulp that supports denormals.
static Value * getSign32(Value *V, IRBuilder<> &Builder, const DataLayout DL)
static void collectPHINodes(const PHINode &I, SmallPtrSet< const PHINode *, 8 > &SeenPHIs)
static bool isPtrKnownNeverNull(const Value *V, const DataLayout &DL, const AMDGPUTargetMachine &TM, unsigned AS)
static bool areInSameBB(const Value *A, const Value *B)
The AMDGPU TargetMachine interface definition for hw codegen targets.
@ Scaled
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
bpf unwind BPF Unwind Lower
#define X(NUM, ENUM, NAME)
Definition ELF.h:665
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< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
dxil translate DXIL Translate Metadata
static bool runOnFunction(Function &F, bool PostInlining)
#define DEBUG_TYPE
This file provides the interface for the instcombine pass implementation.
SmallVector< MachineOperand, 4 > Cond
unsigned Opc
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
#define T
ConstantRange Range(APInt(BitWidth, Low), APInt(BitWidth, High))
FunctionAnalysisManager FAM
#define INITIALIZE_PASS_DEPENDENCY(depName)
Definition PassSupport.h:42
#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
MachineInstr *& Lo
static void visit(BasicBlock &Start, std::function< bool(BasicBlock *)> op)
static TableGen::Emitter::Opt Y("gen-skeleton-entry", EmitSkeleton, "Generate example skeleton entry")
Target-Independent Code Generator Pass Configuration Options pass.
This pass exposes codegen information to IR-level passes.
LLVM IR instance of the generic uniformity analysis.
Value * RHS
Value * LHS
BinaryOperator * Mul
VectorSlice(Type *Ty, unsigned Idx, unsigned NumElts)
Value * getSlicedVal(BasicBlock *BB, Value *Inc, StringRef NewValName)
Slice Inc according to the information contained within this slice.
PreservedAnalyses run(Function &, FunctionAnalysisManager &)
std::optional< unsigned > getReqdWorkGroupSize(const Function &F, unsigned Dim) const
unsigned getWavefrontSize() const
bool hasWavefrontsEvenlySplittingXDim(const Function &F, bool RequiresUniformYZ=false) const
const AMDGPUOptions & getCLOpts() const
static APFloat getOne(const fltSemantics &Sem, bool Negative=false)
Factory for Positive and Negative One.
Definition APFloat.h:1225
static APFloat getSmallestNormalized(const fltSemantics &Sem, bool Negative=false)
Returns the smallest (by magnitude) normalized finite number in the given semantics.
Definition APFloat.h:1295
opStatus next(bool nextDown)
Definition APFloat.h:1391
This class represents a conversion between pointers from one address space to another.
Represent the analysis usage information of a pass.
AnalysisUsage & addRequired()
void setPreservesAll()
Set by analyses that do not transform their input at all.
A function analysis which provides an AssumptionCache.
An immutable pass that tracks lazily created AssumptionCache objects.
A cache of @llvm.assume calls within a function.
LLVM Basic Block Representation.
Definition BasicBlock.h:61
InstListType::iterator iterator
Instruction iterators...
Definition BasicBlock.h:169
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction; assumes that the block is well-formed.
Definition BasicBlock.h:236
BinaryOps getOpcode() const
Definition InstrTypes.h:409
BitVector & set()
Set all bits in the bitvector.
Definition BitVector.h:367
bool all() const
Returns true if all bits are set.
Definition BitVector.h:195
Represents analyses that only rely on functions' control flow.
Definition Analysis.h:73
This class represents a function call, abstracting a target machine's calling convention.
This is the base class for all instructions that perform data casts.
Definition InstrTypes.h:512
Instruction::CastOps getOpcode() const
Return the opcode of this CastInst.
Definition InstrTypes.h:674
static ConstantAsMetadata * get(Constant *C)
Definition Metadata.h:549
bool isMinusOne() const
Returns true if this value is exactly -1.0.
Definition Constants.h:488
static LLVM_ABI ConstantFP * getZero(Type *Ty, bool Negative=false)
bool isOne() const
Returns true if this value is exactly +1.0.
Definition Constants.h:485
static LLVM_ABI ConstantFP * getInfinity(Type *Ty, bool Negative=false)
static LLVM_ABI ConstantInt * getTrue(LLVMContext &Context)
static LLVM_ABI ConstantInt * getFalse(LLVMContext &Context)
This is an important base class in LLVM.
Definition Constant.h:44
static LLVM_ABI Constant * getAllOnesValue(Type *Ty)
static LLVM_ABI Constant * getNullValue(Type *Ty)
Constructor to create a '0' constant of arbitrary type.
A parsed version of the target data layout string in and methods for querying it.
Definition DataLayout.h:63
Analysis pass which computes a DominatorTree.
Definition Dominators.h:241
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree.
Definition Dominators.h:122
Utility class for floating point operations which can have information about relaxed accuracy require...
Definition Operator.h:202
Convenience struct for specifying and reasoning about fast-math flags.
Definition FMF.h:23
void setFast(bool B=true)
Definition FMF.h:96
bool noSignedZeros() const
Definition FMF.h:67
static FastMathFlags intersectValue(FastMathFlags LHS, FastMathFlags RHS)
Intersect value flags.
Definition FMF.h:130
bool noInfs() const
Definition FMF.h:66
bool allowReciprocal() const
Definition FMF.h:68
void setNoSignedZeros(bool B=true)
Definition FMF.h:84
bool approxFunc() const
Definition FMF.h:70
void setNoNaNs(bool B=true)
Definition FMF.h:78
bool noNaNs() const
Definition FMF.h:65
void setNoInfs(bool B=true)
Definition FMF.h:81
bool allowContract() const
Definition FMF.h:69
Class to represent fixed width SIMD vectors.
unsigned getNumElements() const
static LLVM_ABI FixedVectorType * get(Type *ElementType, unsigned NumElts)
Definition Type.cpp:838
FunctionPass class - This class is used to implement most global optimizations.
Definition Pass.h:312
bool isWave32() const
bool isWaveSizeKnown() const
Returns if the wavesize of this subtarget is known reliable.
bool hasFractBug() const
bool isUniformAtDef(ConstValueRefT V) const
Whether V is uniform/non-divergent at its definition.
Value * CreateInsertElement(Type *VecTy, Value *NewElt, Value *Idx, const Twine &Name="")
Definition IRBuilder.h:2748
Value * CreateFDiv(Value *L, Value *R, const Twine &Name="", MDNode *FPMD=nullptr)
Definition IRBuilder.h:1695
Value * CreateExtractElement(Value *Vec, Value *Idx, const Twine &Name="")
Definition IRBuilder.h:2736
IntegerType * getIntNTy(unsigned N)
Fetch the type representing an N-bit integer.
Definition IRBuilder.h:541
Value * CreateZExtOrTrunc(Value *V, Type *DestTy, const Twine &Name="")
Create a ZExt or Trunc from the integer value V to DestTy.
Definition IRBuilder.h:2215
Value * CreateExtractValue(Value *Agg, ArrayRef< unsigned > Idxs, const Twine &Name="")
Definition IRBuilder.h:2795
LLVM_ABI Value * CreateSelect(Value *C, Value *True, Value *False, const Twine &Name="", Instruction *MDFrom=nullptr)
Value * CreateFPToUI(Value *V, Type *DestTy, const Twine &Name="")
Definition IRBuilder.h:2243
Value * CreateSExt(Value *V, Type *DestTy, const Twine &Name="")
Definition IRBuilder.h:2209
void SetCurrentDebugLocation(const DebugLoc &L)
Set location information used by debugging information.
Definition IRBuilder.h:229
IntegerType * getInt32Ty()
Fetch the type representing a 32-bit integer.
Definition IRBuilder.h:528
Value * CreateUIToFP(Value *V, Type *DestTy, const Twine &Name="", bool IsNonNeg=false, MDNode *FPMathTag=nullptr)
Definition IRBuilder.h:2257
void setFastMathFlags(FastMathFlags NewFMF)
Set the fast-math flags to be used with generated fp-math operators.
Definition IRBuilder.h:289
Value * CreateFCmpOLT(Value *LHS, Value *RHS, const Twine &Name="", MDNode *FPMathTag=nullptr)
Definition IRBuilder.h:2513
Value * CreateNeg(Value *V, const Twine &Name="", bool HasNSW=false)
Definition IRBuilder.h:1832
LLVM_ABI Value * createIsFPClass(Value *FPNum, unsigned Test)
ConstantInt * getInt32(uint32_t C)
Get a constant 32-bit value.
Definition IRBuilder.h:471
InstTy * Insert(InstTy *I, const Twine &Name="") const
Insert and return the specified instruction.
Definition IRBuilder.h:148
Value * CreateSub(Value *LHS, Value *RHS, const Twine &Name="", bool HasNUW=false, bool HasNSW=false)
Definition IRBuilder.h:1441
Value * CreateFMA(Value *Factor1, Value *Factor2, Value *Summand, FMFSource FMFSource={}, const Twine &Name="")
Create call to the fma intrinsic.
Definition IRBuilder.h:1094
Value * CreateBitCast(Value *V, Type *DestTy, const Twine &Name="")
Definition IRBuilder.h:2319
LoadInst * CreateLoad(Type *Ty, Value *Ptr, const char *Name)
Provided to resolve 'CreateLoad(Ty, Ptr, "...")' correctly, instead of converting the string to 'bool...
Definition IRBuilder.h:1913
Value * CreateZExt(Value *V, Type *DestTy, const Twine &Name="", bool IsNonNeg=false)
Definition IRBuilder.h:2197
Value * CreateFCmpOEQ(Value *LHS, Value *RHS, const Twine &Name="", MDNode *FPMathTag=nullptr)
Definition IRBuilder.h:2498
LLVM_ABI Value * CreateIntrinsic(Intrinsic::ID ID, ArrayRef< Type * > OverloadTypes, ArrayRef< Value * > Args, FMFSource FMFSource={}, const Twine &Name="", ArrayRef< OperandBundleDef > OpBundles={}, function_ref< void(CallInst *)> SetFn=[](CallInst *) {})
Variant to create a possibly constant-folded intrinsic.
Value * CreateAdd(Value *LHS, Value *RHS, const Twine &Name="", bool HasNUW=false, bool HasNSW=false)
Definition IRBuilder.h:1424
Type * getFloatTy()
Fetch the type representing a 32-bit floating point value.
Definition IRBuilder.h:556
CallInst * CreateCall(FunctionType *FTy, Value *Callee, ArrayRef< Value * > Args={}, const Twine &Name="", MDNode *FPMathTag=nullptr)
Definition IRBuilder.h:2640
Value * CreateTrunc(Value *V, Type *DestTy, const Twine &Name="", bool IsNUW=false, bool IsNSW=false)
Definition IRBuilder.h:2183
Value * CreateBinOp(Instruction::BinaryOps Opc, Value *LHS, Value *RHS, const Twine &Name="", MDNode *FPMathTag=nullptr)
Definition IRBuilder.h:1733
Value * CreateICmpUGE(Value *LHS, Value *RHS, const Twine &Name="")
Definition IRBuilder.h:2470
void SetInsertPoint(BasicBlock *TheBB)
This specifies that created instructions should be appended to the end of the specified block.
Definition IRBuilder.h:197
Value * CreateXor(Value *LHS, Value *RHS, const Twine &Name="")
Definition IRBuilder.h:1624
Value * CreateSIToFP(Value *V, Type *DestTy, const Twine &Name="", MDNode *FPMathTag=nullptr)
Definition IRBuilder.h:2269
Value * CreateFMul(Value *L, Value *R, const Twine &Name="", MDNode *FPMD=nullptr)
Definition IRBuilder.h:1676
Value * CreateFNeg(Value *V, const Twine &Name="", MDNode *FPMathTag=nullptr)
Definition IRBuilder.h:1841
Value * CreateOr(Value *LHS, Value *RHS, const Twine &Name="", bool IsDisjoint=false)
Definition IRBuilder.h:1594
Value * CreateSExtOrTrunc(Value *V, Type *DestTy, const Twine &Name="")
Create a SExt or Trunc from the integer value V to DestTy.
Definition IRBuilder.h:2230
Value * CreateFMulFMF(Value *L, Value *R, FMFSource FMFSource, const Twine &Name="", MDNode *FPMD=nullptr)
Definition IRBuilder.h:1681
Value * CreateMul(Value *LHS, Value *RHS, const Twine &Name="", bool HasNUW=false, bool HasNSW=false)
Definition IRBuilder.h:1458
LLVM_ABI Value * CreateUnaryIntrinsic(Intrinsic::ID ID, Value *Op, FMFSource FMFSource={}, const Twine &Name="")
Create a call to intrinsic ID with 1 operand which is mangled on its type.
Value * CreateFPToSI(Value *V, Type *DestTy, const Twine &Name="")
Definition IRBuilder.h:2250
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
Definition IRBuilder.h:2990
Base class for instruction visitors.
Definition InstVisitor.h:78
const DebugLoc & getDebugLoc() const
Return the debug location for this node as a DebugLoc.
A wrapper class for inspecting calls to intrinsic functions.
bool isKnownNeverSubnormal() const
Return true if it's known this can never be a subnormal.
LLVM_ABI bool isKnownNeverLogicalZero(DenormalMode Mode) const
Return true if it's known this can never be interpreted as a zero.
bool isKnownNeverPosInfinity() const
Return true if it's known this can never be +infinity.
This is an important class for using LLVM in a threaded context.
Definition LLVMContext.h:76
An instruction for reading from memory.
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Definition Metadata.h:1588
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
PreservedAnalyses & preserveSet()
Mark an analysis set as preserved.
Definition Analysis.h:151
This class represents the LLVM 'select' instruction.
const Value * getFalseValue() const
const Value * getCondition() const
const Value * getTrueValue() const
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
Analysis pass providing the TargetTransformInfo.
Analysis pass providing the TargetLibraryInfo.
Provides information about what library functions are available for the current target.
const STC & getSubtarget(const Function &F) const
This method returns a pointer to the specified type of TargetSubtargetInfo.
Wrapper pass for TargetTransformInfo.
This pass provides access to the codegen interfaces that are needed for IR-level transformations.
static LLVM_ABI CastContextHint getCastContextHint(const Instruction *I)
Calculates a CastContextHint from I.
LLVM_ABI InstructionCost getCastInstrCost(unsigned Opcode, Type *Dst, Type *Src, TTI::CastContextHint CCH, TTI::TargetCostKind CostKind, const Instruction *I=nullptr) const
@ TCK_RecipThroughput
Reciprocal throughput.
LLVM_ABI InstructionCost getArithmeticInstrCost(unsigned Opcode, Type *Ty, TTI::TargetCostKind CostKind, TTI::OperandValueInfo Opd1Info={TTI::OK_AnyValue, TTI::OP_None}, TTI::OperandValueInfo Opd2Info={TTI::OK_AnyValue, TTI::OP_None}, ArrayRef< const Value * > Args={}, const Instruction *CtxI=nullptr, const TargetLibraryInfo *TLibInfo=nullptr, ArrayRef< const Value * > Scalars={}) const
This is an approximation of reciprocal throughput of a math/logic op.
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:46
static LLVM_ABI IntegerType * getInt64Ty(LLVMContext &C)
Definition Type.cpp:295
LLVM_ABI unsigned getIntegerBitWidth() const
static LLVM_ABI IntegerType * getInt32Ty(LLVMContext &C)
Definition Type.cpp:294
bool isFloatTy() const
Return true if this is 'float', a 32-bit IEEE fp type.
Definition Type.h:155
unsigned getScalarSizeInBits() const LLVM_READONLY
If this is a vector type, return the getPrimitiveSizeInBits value for the element type.
Definition Type.h:354
Type * getScalarType() const
If this is a vector type, return the element type, otherwise return 'this'.
Definition Type.h:370
LLVM_ABI Type * getWithNewBitWidth(unsigned NewBitWidth) const
Given an integer or vector type, change the lane bitwidth to NewBitwidth, whilst keeping the old numb...
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 isIntegerTy() const
True if this is an instance of IntegerType.
Definition Type.h:252
LLVM_ABI const fltSemantics & getFltSemantics() const
Definition Type.cpp:96
Analysis pass which computes UniformityInfo.
Legacy analysis pass which computes a CycleInfo.
void setOperand(unsigned i, Value *Val)
Definition User.h:212
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:257
bool hasOneUse() const
Return true if there is exactly one use of this value.
Definition Value.h:441
LLVM_ABI void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
Definition Value.cpp:548
bool use_empty() const
Definition Value.h:348
LLVM_ABI void takeName(Value *V)
Transfer the name from V to this value.
Definition Value.cpp:395
Type * getElementType() const
self_iterator getIterator()
Definition ilist_node.h:123
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
@ CONSTANT_ADDRESS_32BIT
Address space for 32-bit constant memory.
@ LOCAL_ADDRESS
Address space for local memory.
@ CONSTANT_ADDRESS
Address space for constant memory (VTX2).
@ FLAT_ADDRESS
Address space for flat memory.
@ PRIVATE_ADDRESS
Address space for private memory.
constexpr char Align[]
Key for Kernel::Arg::Metadata::mAlign.
constexpr int64_t getNullPointerValue(unsigned AS)
Get the null pointer value for the given address space.
void copyMetadataForWidenedLoad(LoadInst &Dest, const LoadInst &Source)
constexpr std::underlying_type_t< E > Mask()
Get a bitmask with 1s in all places up to the high-order bit of E's largest value.
LLVM_ABI Function * getOrInsertDeclaration(Module *M, ID id, ArrayRef< Type * > OverloadTys={})
Look up the Function declaration of the intrinsic id in the Module M.
auto m_PosZeroFP()
Matches a floating-point positive zero.
AllOnesConstantMatch m_AllOnes()
OneUse_match< SubPat > m_OneUse(const SubPat &SP)
match_combine_or< Ty... > m_CombineOr(const Ty &...Ps)
Combine pattern matchers matching any of Ps patterns.
BinaryOp_match< LHS, RHS, Instruction::And > m_And(const LHS &L, const RHS &R)
CmpClass_match< LHS, RHS, FCmpInst > m_FCmp(CmpPredicate &Pred, const LHS &L, const RHS &R)
BinaryOp_match< LHS, RHS, Instruction::FSub > m_FSub(const LHS &L, const RHS &R)
BinaryOp_match< LHS, RHS, Instruction::FMul > m_FMul(const LHS &L, const RHS &R)
bool match(Val *V, const Pattern &P)
match_deferred< Value > m_Deferred(Value *const &V)
Like m_Specific(), but works if the specific value to match is determined as part of the same match()...
cstfp_pred_ty< is_any_zero_fp > m_AnyZeroFP()
Match a floating-point negative zero or positive zero.
specificval_ty m_Specific(const Value *V)
Match if we have a specific specified value.
ap_match< APFloat > m_APFloatAllowPoison(const APFloat *&Res)
Match APFloat while allowing poison in splat vector constants.
ThreeOps_match< Cond, LHS, RHS, Instruction::Select > m_Select(const Cond &C, const LHS &L, const RHS &R)
Matches SelectInst.
FMaxMin_match< LHS, RHS, ufmin_pred_ty > m_UnordFMin(const LHS &L, const RHS &R)
Match an 'unordered' floating point minimum function.
auto m_FMinimum(const Opnd0 &Op0, const Opnd1 &Op1)
auto m_Value()
Match an arbitrary value and ignore it.
BinaryOp_match< LHS, RHS, Instruction::Mul > m_Mul(const LHS &L, const RHS &R)
cstfp_pred_ty< is_nonnan > m_NonNaN()
Match a non-NaN FP constant.
CastInst_match< OpTy, ZExtInst > m_ZExt(const OpTy &Op)
Matches ZExt.
is_zero< true > m_Zero()
Match any null constant or a vector with all elements equal to 0.
auto m_FMinNum_or_FMinimumNum(const Opnd0 &Op0, const Opnd1 &Op1)
cstfp_pred_ty< is_signed_inf< false > > m_PosInf()
Match a positive infinity FP constant.
SpecificCmpClass_match< LHS, RHS, FCmpInst > m_SpecificFCmp(CmpPredicate MatchPred, const LHS &L, const RHS &R)
auto m_Intrinsic(const Ts &...Ops)
Match intrinsic calls like this: m_Intrinsic<Intrinsic::fabs>(m_Value(X))
auto m_FAbs(const Opnd0 &Op0)
BinaryOp_match< LHS, RHS, Instruction::Or > m_Or(const LHS &L, const RHS &R)
CastInst_match< OpTy, SExtInst > m_SExt(const OpTy &Op)
Matches SExt.
std::enable_if_t< detail::IsValidPointer< X, Y >::value, X * > extract(Y &&MD)
Extract a Value from Metadata.
Definition Metadata.h:680
constexpr double ln2
constexpr double ln10
unsigned getOpcode(const VPValue *V)
Return the instruction opcode for the recipe defining V or 0 for unsupported recipes and VPValues not...
This is an optimization pass for GlobalISel generic memory operations.
GenericUniformityInfo< SSAContext > UniformityInfo
LLVM_ABI KnownFPClass computeKnownFPClass(const Value *V, const APInt &DemandedElts, FPClassTest InterestedClasses, const SimplifyQuery &SQ, unsigned Depth=0)
Determine which floating-point classes are valid for V, and return them in KnownFPClass bit sets.
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1755
LLVM_ABI bool isKnownToBeAPowerOfTwo(const Value *V, bool OrZero, const SimplifyQuery &Q, unsigned Depth=0)
Return true if the given value is known to have exactly one bit set when defined.
LLVM_ABI bool RecursivelyDeleteTriviallyDeadInstructions(Value *V, const TargetLibraryInfo *TLI=nullptr, MemorySSAUpdater *MSSAU=nullptr, std::function< void(Value *)> AboutToDeleteCallback=std::function< void(Value *)>())
If the specified value is a trivially dead instruction, delete it.
Definition Local.cpp:523
RelativeUniformCounterPtr Values
Definition InstrProf.h:91
@ Known
Known to have no common set bits.
auto enumerate(FirstRange &&First, RestRanges &&...Rest)
Given two or more input ranges, returns a new range whose values are tuples (A, B,...
Definition STLExtras.h:2575
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
LLVM_ABI bool expandRemainderUpTo64Bits(BinaryOperator *Rem)
Generate code to calculate the remainder of two integers, replacing Rem with the generated code.
@ 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:649
LLVM_ABI void computeKnownBits(const Value *V, KnownBits &Known, const DataLayout &DL, AssumptionCache *AC=nullptr, const Instruction *CtxI=nullptr, const DominatorTree *DT=nullptr, bool UseInstrInfo=true, unsigned Depth=0)
Determine which bits of V are known to be either zero or one and return them in the KnownZero/KnownOn...
constexpr T alignDown(U Value, V Align, W Skew=0)
Returns the largest unsigned integer less than or equal to Value and is Skew mod Align.
Definition MathExtras.h:546
LLVM_ABI void ReplaceInstWithValue(BasicBlock::iterator &BI, Value *V)
Replace all uses of an instruction (specified by BI) with a value, then remove and delete the origina...
T bit_ceil(T Value)
Returns the smallest integral power of two no smaller than Value if Value is nonzero.
Definition bit.h:362
LLVM_ABI unsigned ComputeNumSignBits(const Value *Op, const DataLayout &DL, AssumptionCache *AC=nullptr, const Instruction *CtxI=nullptr, const DominatorTree *DT=nullptr, bool UseInstrInfo=true, unsigned Depth=0)
Return the number of times the sign bit of the register is replicated into the other bits.
LLVM_ABI unsigned ComputeMaxSignificantBits(const Value *Op, const DataLayout &DL, AssumptionCache *AC=nullptr, const Instruction *CtxI=nullptr, const DominatorTree *DT=nullptr, unsigned Depth=0)
Get the upper bound on bit size for this Value Op as a signed integer.
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Value
Definition InstrProf.h:143
auto dyn_cast_or_null(const Y &Val)
Definition Casting.h:753
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1762
LLVM_ABI bool isInstructionTriviallyDead(Instruction *I, const TargetLibraryInfo *TLI=nullptr)
Return true if the result produced by the instruction is not used, and the instruction will return.
Definition Local.cpp:409
FPOp
The floating-point operations supported by the folding helpers.
Definition FPFold.h:25
auto reverse(ContainerTy &&C)
Definition STLExtras.h:408
LLVM_ABI bool expandDivisionUpTo64Bits(BinaryOperator *Div)
Generate code to divide two integers, replacing Div with the generated code.
LLVM_ABI bool impliesPoison(const Value *ValAssumedPoison, const Value *V)
Return true if V is poison given that ValAssumedPoison is already poison.
FPClassTest
Floating-point class tests, supported by 'is_fpclass' intrinsic.
IRBuilder(LLVMContext &, FolderTy, InserterTy) -> IRBuilder< FolderTy, InserterTy >
constexpr uint64_t alignTo(uint64_t Size, Align A)
Returns a multiple of A needed to store Size bytes.
Definition Alignment.h:149
LLVM_ABI Constant * ConstantFoldCastOperand(unsigned Opcode, Constant *C, Type *DestTy, const DataLayout &DL)
Attempt to constant fold a cast with the specified operand.
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
LLVM_ABI CGPassBuilderOption getCGPassBuilderOption(const TargetMachine &TM)
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
Definition Casting.h:547
LLVM_ABI Constant * ConstantFoldBinaryOpOperands(unsigned Opcode, Constant *LHS, Constant *RHS, const DataLayout &DL)
Attempt to constant fold a binary operation with the specified operands.
TargetTransformInfo TTI
To bit_cast(const From &from) noexcept
Definition bit.h:90
DWARFExpression::Operation Op
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
LLVM_ABI bool isKnownNeverNaN(const Value *V, const SimplifyQuery &SQ, unsigned Depth=0)
Return true if the floating-point scalar value is not a NaN or if the floating-point vector value has...
unsigned Log2(Align A)
Returns the log2 of the alignment.
Definition Alignment.h:202
AnalysisManager< Function > FunctionAnalysisManager
Convenience typedef for the Function analysis manager.
@ End
Run the machine verifier once, at the end of the pipeline.
Definition CodeGen.h:320
LLVM_ABI void getUnderlyingObjects(const Value *V, SmallVectorImpl< const Value * > &Objects, const LoopInfo *LI=nullptr, unsigned MaxLookup=MaxLookupSearchDepth)
This method is similar to getUnderlyingObject except that it can look through phi and select instruct...
FunctionPass * createAMDGPUCodeGenPreparePass(bool ExpandDiv64InIR)
#define N
DenormalModeKind Input
Denormal treatment kind for floating point instruction inputs in the default floating-point environme...
constexpr bool inputsAreZero() const
Return true if input denormals must be implicitly treated as 0.
static constexpr DenormalMode getPreserveSign()
const DataLayout & DL
const DominatorTree * DT
SimplifyQuery getWithInstruction(const Instruction *I) const
AssumptionCache * AC