62#define DEBUG_TYPE "expand-ir-insts"
82 return Opcode == Instruction::SDiv || Opcode == Instruction::SRem;
95 "ShiftAmt out of range; callers should handle ShiftAmt == 0");
98 return Builder.CreateAdd(
X, Bias,
"adjusted");
114 bool IsDiv = (Opcode == Instruction::UDiv || Opcode == Instruction::SDiv);
117 bool IsExact = IsDiv && BO->
isExact();
120 "Expected power-of-2 constant divisor");
125 unsigned BitWidth = Ty->getIntegerBitWidth();
127 APInt DivisorVal =
C->getValue();
128 bool IsNegativeDivisor = IsSigned && DivisorVal.
isNegative();
141 Result = IsNegativeDivisor ? Builder.CreateNeg(
X) :
X;
143 Result = ConstantInt::get(Ty, 0);
144 }
else if (IsSigned) {
150 X = Builder.CreateFreeze(
X,
X->getName() +
".fr");
154 Value *Quotient = Builder.CreateAShr(
155 Dividend, ShiftAmt, IsDiv && IsNegativeDivisor ?
"pre.neg" :
"shifted",
158 Result = IsNegativeDivisor ? Builder.CreateNeg(Quotient) : Quotient;
162 Value *Truncated = Builder.CreateShl(Quotient, ShiftAmt,
"truncated");
163 Result = Builder.CreateSub(
X, Truncated);
167 Result = Builder.CreateLShr(
X, ShiftAmt,
"", IsExact);
170 Result = Builder.CreateAnd(
X, ConstantInt::get(Ty, Mask));
211 static constexpr std::array<MVT, 4> ExpandableTypes{MVT::f16, MVT::bf16,
215 static bool canExpandType(
Type *Ty) {
222 static bool shouldExpandFremType(
const TargetLowering &
TLI,
223 const LibcallLoweringInfo &Libcalls,
225 assert(!VT.
isVector() &&
"Cannot handle vector type; must scalarize first");
227 case TargetLowering::LegalizeAction::Expand:
229 case TargetLowering::LegalizeAction::LibCall:
239 static bool shouldExpandFremType(
const TargetLowering &
TLI,
240 const LibcallLoweringInfo &Libcalls,
245 return shouldExpandFremType(
TLI, Libcalls,
251 static bool shouldExpandAnyFremType(
const TargetLowering &
TLI,
252 const LibcallLoweringInfo &Libcalls) {
253 return any_of(ExpandableTypes, [&](MVT
V) {
254 return shouldExpandFremType(
TLI, Libcalls, EVT(
V));
259 assert(canExpandType(Ty) &&
"Expected supported floating point type");
263 Type *ComputeTy = Ty;
267 unsigned MaxIter = 2;
275 unsigned Precision = APFloat::semanticsPrecision(Ty->
getFltSemantics());
276 return FRemExpander{B, Ty, Precision / MaxIter, ComputeTy};
292 : B(B), FremTy(FremTy), ComputeFpTy(ComputeFpTy), ExTy(B.getInt32Ty()),
293 Bits(ConstantInt::
get(ExTy, Bits)), One(ConstantInt::
get(ExTy, 1)) {}
295 Value *createRcp(
Value *
V,
const Twine &Name)
const {
298 return B.CreateFDiv(ConstantFP::get(ComputeFpTy, 1.0),
V, Name);
310 Value *Q = B.CreateUnaryIntrinsic(Intrinsic::rint, B.CreateFMul(Ax, Ayinv),
312 Value *AxUpdate = B.CreateFMA(B.CreateFNeg(Q), Ay, Ax, {},
"ax");
315 Value *Axp = B.CreateFAdd(AxUpdate, Ay,
"axp");
316 return B.CreateSelect(Clt, Axp, AxUpdate,
"ax");
322 std::pair<Value *, Value *> buildExpAndPower(
Value *Src,
Value *NewExp,
324 const Twine &PowName)
const {
328 Type *Ty = Src->getType();
329 Type *ExTy = B.getInt32Ty();
330 Value *Frexp = B.CreateIntrinsic(Intrinsic::frexp, {Ty, ExTy}, Src);
331 Value *Mant = B.CreateExtractValue(Frexp, {0});
332 Value *
Exp = B.CreateExtractValue(Frexp, {1});
334 Exp = B.CreateSub(Exp, One, ExName);
335 Value *
Pow = B.CreateLdexp(Mant, NewExp, {}, PowName);
344 void buildRemainderComputation(
Value *AxInitial,
Value *AyInitial,
Value *
X,
345 PHINode *RetPhi, FastMathFlags FMF)
const {
346 IRBuilder<>::FastMathFlagGuard Guard(B);
347 B.setFastMathFlags(FMF);
354 auto [Ax, Ex] = buildExpAndPower(AxInitial, Bits,
"ex",
"ax");
355 auto [Ay, Ey] = buildExpAndPower(AyInitial, One,
"ey",
"ay");
360 Value *Nb = B.CreateSub(Ex, Ey,
"nb");
361 Value *Ayinv = createRcp(Ay,
"ayinv");
377 B.SetInsertPoint(LoopBB);
378 PHINode *NbIv = B.CreatePHI(Nb->
getType(), 2,
"nb_iv");
381 auto *AxPhi = B.CreatePHI(ComputeFpTy, 2,
"ax_loop_phi");
382 AxPhi->addIncoming(Ax, PreheaderBB);
384 Value *AxPhiUpdate = buildUpdateAx(AxPhi, Ay, Ayinv);
385 AxPhiUpdate = B.CreateLdexp(AxPhiUpdate, Bits, {},
"ax_update");
386 AxPhi->addIncoming(AxPhiUpdate, LoopBB);
387 NbIv->
addIncoming(B.CreateSub(NbIv, Bits,
"nb_update"), LoopBB);
394 B.SetInsertPoint(ExitBB);
396 auto *AxPhiExit = B.CreatePHI(ComputeFpTy, 2,
"ax_exit_phi");
397 AxPhiExit->addIncoming(Ax, PreheaderBB);
398 AxPhiExit->addIncoming(AxPhi, LoopBB);
399 auto *NbExitPhi = B.CreatePHI(Nb->
getType(), 2,
"nb_exit_phi");
400 NbExitPhi->addIncoming(NbIv, LoopBB);
401 NbExitPhi->addIncoming(Nb, PreheaderBB);
403 Value *AxFinal = B.CreateLdexp(
404 AxPhiExit, B.CreateAdd(B.CreateSub(NbExitPhi, Bits), One), {},
"ax");
405 AxFinal = buildUpdateAx(AxFinal, Ay, Ayinv);
410 AxFinal = B.CreateLdexp(AxFinal, Ey, {},
"ax");
411 if (ComputeFpTy != FremTy)
412 AxFinal = B.CreateFPTrunc(AxFinal, FremTy);
413 Value *Ret = B.CreateCopySign(AxFinal,
X);
422 void buildElseBranch(
Value *Ax,
Value *Ay,
Value *
X, PHINode *RetPhi)
const {
426 Value *Ret = B.CreateSelect(B.CreateFCmpOEQ(Ax, Ay), ZeroWithXSign,
X);
434 std::optional<SimplifyQuery> &SQ,
446 Ret = B.CreateSelect(XFinite, Ret, Nan);
454 IRBuilder<>::FastMathFlagGuard Guard(
B);
459 B.clearFastMathFlags();
462 Value *
Trunc =
B.CreateUnaryIntrinsic(Intrinsic::trunc, Quot, {});
465 return B.CreateFMA(Neg,
Y,
X);
469 std::optional<SimplifyQuery> &SQ)
const {
470 assert(
X->getType() == FremTy &&
Y->getType() == FremTy);
472 FastMathFlags FMF =
B.getFastMathFlags();
481 Value *Ax =
B.CreateFAbs(
X, {},
"ax");
482 Value *Ay =
B.CreateFAbs(
Y, {},
"ay");
483 if (ComputeFpTy !=
X->getType()) {
484 Ax =
B.CreateFPExt(Ax, ComputeFpTy,
"ax");
485 Ay =
B.CreateFPExt(Ay, ComputeFpTy,
"ay");
487 Value *AxAyCmp =
B.CreateFCmpOGT(Ax, Ay);
489 PHINode *RetPhi =
B.CreatePHI(FremTy, 2,
"ret");
495 Ret = handleInputCornerCases(Ret,
X,
Y, SQ, FMF.
noInfs());
502 auto SavedInsertPt =
B.GetInsertPoint();
510 FastMathFlags ComputeFMF = FMF;
514 B.SetInsertPoint(ThenBB);
515 buildRemainderComputation(Ax, Ay,
X, RetPhi, FMF);
519 B.SetInsertPoint(ElseBB);
520 buildElseBranch(Ax, Ay,
X, RetPhi);
523 B.SetInsertPoint(SavedInsertPt);
531 Type *Ty =
I.getType();
532 assert(FRemExpander::canExpandType(Ty) &&
533 "Expected supported floating point type");
541 B.setFastMathFlags(FMF);
542 B.SetCurrentDebugLocation(
I.getDebugLoc());
544 const FRemExpander Expander = FRemExpander::create(
B, Ty);
546 ? Expander.buildApproxFRem(
I.getOperand(0),
I.getOperand(1))
547 : Expander.buildFRem(
I.getOperand(0),
I.getOperand(1), SQ);
549 I.replaceAllUsesWith(Ret);
615 unsigned FPMantissaWidth = FloatVal->getType()->getFPMantissaWidth() - 1;
620 if (FloatVal->getType()->isHalfTy() &&
BitWidth >= 32 && !IsSaturating) {
621 if (FPToI->
getOpcode() == Instruction::FPToUI) {
622 Value *A0 = Builder.CreateFPToUI(FloatVal, Builder.getInt32Ty());
623 A1 = Builder.CreateZExt(A0, IntTy);
625 Value *A0 = Builder.CreateFPToSI(FloatVal, Builder.getInt32Ty());
626 A1 = Builder.CreateSExt(A0, IntTy);
636 FPMantissaWidth = FPMantissaWidth == 63 ? 112 : FPMantissaWidth;
637 unsigned FloatWidth =
638 PowerOf2Ceil(FloatVal->getType()->getScalarSizeInBits());
639 unsigned ExponentWidth = FloatWidth - FPMantissaWidth - 1;
640 unsigned ExponentBias = (1 << (ExponentWidth - 1)) - 1;
642 Value *ImplicitBit = ConstantInt::get(
644 Value *SignificandMask = ConstantInt::get(
649 Entry->setName(
Twine(Entry->getName(),
"fp-to-i-entry"));
652 Entry->splitBasicBlock(Builder.GetInsertPoint(),
"fp-to-i-cleanup");
655 "fp-to-i-if-check.saturate",
F,
End);
660 Builder.getContext(),
"fp-to-i-if-check.exp.size",
F,
End);
666 Entry->getTerminator()->eraseFromParent();
669 Builder.SetInsertPoint(Entry);
672 FloatVal = Builder.CreateFreeze(FloatVal);
675 if (FloatVal->getType()->isX86_FP80Ty())
678 Value *ARep = Builder.CreateBitCast(FloatVal, FloatIntTy);
683 Sign = Builder.CreateSelectWithUnknownProfile(
688 Builder.CreateLShr(ARep, Builder.getIntN(FloatWidth, FPMantissaWidth));
689 Value *BiasedExp = Builder.CreateAnd(
690 And, Builder.getIntN(FloatWidth, (1 << ExponentWidth) - 1),
"biased.exp");
691 Value *Abs = Builder.CreateAnd(ARep, SignificandMask);
692 Value *Significand = Builder.CreateOr(Abs, ImplicitBit,
"significand");
693 Value *ZeroResultCond = Builder.CreateICmpULT(
694 BiasedExp, Builder.getIntN(FloatWidth, ExponentBias),
"exp.is.negative");
696 Value *IsNaN = Builder.CreateFCmpUNO(FloatVal, FloatVal,
"is.nan");
697 ZeroResultCond = Builder.CreateOr(ZeroResultCond, IsNaN);
699 Value *IsNeg = Builder.CreateIsNeg(ARep);
700 ZeroResultCond = Builder.CreateOr(ZeroResultCond, IsNeg);
704 ZeroResultCond,
End, IsSaturating ? CheckSaturateBB : CheckExpSizeBB);
712 Builder.SetInsertPoint(CheckSaturateBB);
718 uint64_t MaxBiasedExp = (1ULL << ExponentWidth) - 1;
719 if (SaturatingBiasedExp > MaxBiasedExp)
720 SaturatingBiasedExp = MaxBiasedExp;
721 Value *Cmp3 = Builder.CreateICmpUGE(
722 BiasedExp, ConstantInt::get(FloatIntTy, SaturatingBiasedExp));
723 Value *CondBrSat = Builder.CreateCondBr(Cmp3, SaturateBB, CheckExpSizeBB);
727 LLVMContext::MD_prof,
732 Builder.SetInsertPoint(SaturateBB);
739 Saturated = Builder.CreateSelectWithUnknownProfile(
740 PosOrNeg, SignedMax, SignedMin,
"saturated");
744 Builder.CreateBr(
End);
748 Builder.SetInsertPoint(CheckExpSizeBB);
749 Value *ExpSmallerMantissaWidth = Builder.CreateICmpULT(
750 BiasedExp, Builder.getIntN(FloatWidth, ExponentBias + FPMantissaWidth),
751 "exp.smaller.mantissa.width");
755 Builder.CreateCondBr(ExpSmallerMantissaWidth, ExpSmallBB, ExpLargeBB);
761 Builder.SetInsertPoint(ExpSmallBB);
762 Value *Sub13 = Builder.CreateSub(
763 Builder.getIntN(FloatWidth, ExponentBias + FPMantissaWidth), BiasedExp);
765 Builder.CreateZExtOrTrunc(Builder.CreateLShr(Significand, Sub13), IntTy);
767 ExpSmallRes = Builder.CreateMul(ExpSmallRes,
Sign);
768 Builder.CreateBr(
End);
771 Builder.SetInsertPoint(ExpLargeBB);
772 Value *Sub15 = Builder.CreateAdd(
775 FloatIntTy, -
static_cast<int64_t
>(ExponentBias + FPMantissaWidth)));
776 Value *SignificandCast = Builder.CreateZExtOrTrunc(Significand, IntTy);
777 Value *ExpLargeRes = Builder.CreateShl(
778 SignificandCast, Builder.CreateZExtOrTrunc(Sub15, IntTy));
780 ExpLargeRes = Builder.CreateMul(ExpLargeRes,
Sign);
781 Builder.CreateBr(
End);
784 Builder.SetInsertPoint(
End->begin());
785 PHINode *Retval0 = Builder.CreatePHI(FPToI->
getType(), 3 + IsSaturating);
888 unsigned BitWidth = IntVal->getType()->getIntegerBitWidth();
892 FPMantissaWidth = FPMantissaWidth == 63 ? 112 : FPMantissaWidth;
895 FPMantissaWidth = FPMantissaWidth == 10 ? 23 : FPMantissaWidth;
896 FPMantissaWidth = FPMantissaWidth == 7 ? 23 : FPMantissaWidth;
898 bool IsSigned = IToFP->
getOpcode() == Instruction::SIToFP;
902 IntVal = Builder.CreateFreeze(IntVal);
908 IntTy = Builder.getIntNTy(
BitWidth);
909 IntVal = Builder.CreateIntCast(IntVal, IntTy, IsSigned);
913 Builder.CreateShl(Builder.getIntN(
BitWidth, 1),
914 Builder.getIntN(
BitWidth, FPMantissaWidth + 3));
918 Entry->setName(
Twine(Entry->getName(),
"itofp-entry"));
920 Entry->splitBasicBlock(Builder.GetInsertPoint(),
"itofp-return");
938 Entry->getTerminator()->eraseFromParent();
945 Builder.SetInsertPoint(Entry);
949 Value *CondBrEntry = Builder.CreateCondBr(Cmp,
End, IfEnd);
952 LLVMContext::MD_prof,
957 Builder.SetInsertPoint(IfEnd);
960 Value *
Xor = Builder.CreateXor(Shr, IntVal);
963 Value *Cast = Builder.CreateTrunc(
Call, Builder.getInt32Ty());
964 int BitWidthNew = FloatWidth == 128 ?
BitWidth : 32;
965 Value *Sub1 = Builder.CreateSub(Builder.getIntN(BitWidthNew,
BitWidth),
966 FloatWidth == 128 ?
Call : Cast);
967 Value *Sub2 = Builder.CreateSub(Builder.getIntN(BitWidthNew,
BitWidth - 1),
968 FloatWidth == 128 ?
Call : Cast);
969 Value *Cmp3 = Builder.CreateICmpSGT(
970 Sub1, Builder.getIntN(BitWidthNew, FPMantissaWidth + 1));
974 Value *CondBrIfEnd = Builder.CreateCondBr(Cmp3, IfThen4, IfElse);
977 LLVMContext::MD_prof,
982 Builder.SetInsertPoint(IfThen4);
984 SI->addCase(Builder.getIntN(BitWidthNew, FPMantissaWidth + 2), SwBB);
985 SI->addCase(Builder.getIntN(BitWidthNew, FPMantissaWidth + 3), SwEpilog);
992 LLVMContext::MD_prof,
995 llvm::MDBuilder::kUnlikelyBranchWeight,
996 llvm::MDBuilder::kUnlikelyBranchWeight}));
1000 Builder.SetInsertPoint(SwBB);
1002 Builder.CreateShl(IsSigned ?
Sub : IntVal, Builder.getIntN(
BitWidth, 1));
1003 Builder.CreateBr(SwEpilog);
1006 Builder.SetInsertPoint(SwDefault);
1007 Value *Sub5 = Builder.CreateSub(
1008 Builder.getIntN(BitWidthNew,
BitWidth - FPMantissaWidth - 3),
1009 FloatWidth == 128 ?
Call : Cast);
1010 Value *ShProm = Builder.CreateZExt(Sub5, IntTy);
1011 Value *Shr6 = Builder.CreateLShr(IsSigned ?
Sub : IntVal,
1012 FloatWidth == 128 ? Sub5 : ShProm);
1014 Builder.CreateAdd(FloatWidth == 128 ?
Call : Cast,
1015 Builder.getIntN(BitWidthNew, FPMantissaWidth + 3));
1016 Value *ShProm9 = Builder.CreateZExt(Sub8, IntTy);
1018 FloatWidth == 128 ? Sub8 : ShProm9);
1019 Value *
And = Builder.CreateAnd(Shr9, IsSigned ?
Sub : IntVal);
1021 Value *Conv11 = Builder.CreateZExt(Cmp10, IntTy);
1022 Value *
Or = Builder.CreateOr(Shr6, Conv11);
1023 Builder.CreateBr(SwEpilog);
1026 Builder.SetInsertPoint(SwEpilog);
1027 PHINode *AAddr0 = Builder.CreatePHI(IntTy, 3);
1031 Value *A0 = Builder.CreateTrunc(AAddr0, Builder.getInt32Ty());
1032 Value *A1 = Builder.CreateLShr(A0, Builder.getInt32(2));
1033 Value *A2 = Builder.CreateAnd(A1, Builder.getInt32(1));
1034 Value *Conv16 = Builder.CreateZExt(A2, IntTy);
1035 Value *Or17 = Builder.CreateOr(AAddr0, Conv16);
1036 Value *Inc = Builder.CreateAdd(Or17, Builder.getIntN(
BitWidth, 1));
1037 Value *Shr18 =
nullptr;
1039 Shr18 = Builder.CreateAShr(Inc, Builder.getIntN(
BitWidth, 2));
1041 Shr18 = Builder.CreateLShr(Inc, Builder.getIntN(
BitWidth, 2));
1042 Value *A3 = Builder.CreateAnd(Inc, Temp1,
"a3");
1043 Value *PosOrNeg = Builder.CreateICmpEQ(A3, Builder.getIntN(
BitWidth, 0));
1044 Value *ExtractT60 = Builder.CreateTrunc(Shr18, Builder.getIntNTy(FloatWidth));
1045 Value *Extract63 = Builder.CreateLShr(Shr18, Builder.getIntN(
BitWidth, 32));
1046 Value *ExtractT64 =
nullptr;
1047 if (FloatWidth > 80)
1048 ExtractT64 = Builder.CreateTrunc(Sub2, Builder.getInt64Ty());
1050 ExtractT64 = Builder.CreateTrunc(Extract63, Builder.getInt32Ty());
1053 Value *CondBrSwEpilog = Builder.CreateCondBr(PosOrNeg, IfEnd26, IfThen20);
1056 LLVMContext::MD_prof,
1061 Builder.SetInsertPoint(IfThen20);
1062 Value *Shr21 =
nullptr;
1064 Shr21 = Builder.CreateAShr(Inc, Builder.getIntN(
BitWidth, 3));
1066 Shr21 = Builder.CreateLShr(Inc, Builder.getIntN(
BitWidth, 3));
1067 Value *ExtractT = Builder.CreateTrunc(Shr21, Builder.getIntNTy(FloatWidth));
1068 Value *Extract = Builder.CreateLShr(Shr21, Builder.getIntN(
BitWidth, 32));
1069 Value *ExtractT62 =
nullptr;
1070 if (FloatWidth > 80)
1071 ExtractT62 = Builder.CreateTrunc(Sub1, Builder.getInt64Ty());
1073 ExtractT62 = Builder.CreateTrunc(Extract, Builder.getInt32Ty());
1074 Builder.CreateBr(IfEnd26);
1077 Builder.SetInsertPoint(IfElse);
1078 Value *Sub24 = Builder.CreateAdd(
1079 FloatWidth == 128 ?
Call : Cast,
1081 -(
int)(
BitWidth - FPMantissaWidth - 1)));
1082 Value *ShProm25 = Builder.CreateZExt(Sub24, IntTy);
1083 Value *Shl26 = Builder.CreateShl(IsSigned ?
Sub : IntVal,
1084 FloatWidth == 128 ? Sub24 : ShProm25);
1085 Value *ExtractT61 = Builder.CreateTrunc(Shl26, Builder.getIntNTy(FloatWidth));
1086 Value *Extract65 = Builder.CreateLShr(Shl26, Builder.getIntN(
BitWidth, 32));
1087 Value *ExtractT66 =
nullptr;
1088 if (FloatWidth > 80)
1089 ExtractT66 = Builder.CreateTrunc(Sub2, Builder.getInt64Ty());
1091 ExtractT66 = Builder.CreateTrunc(Extract65, Builder.getInt32Ty());
1092 Builder.CreateBr(IfEnd26);
1095 Builder.SetInsertPoint(IfEnd26);
1096 PHINode *AAddr1Off0 = Builder.CreatePHI(Builder.getIntNTy(FloatWidth), 3);
1100 PHINode *AAddr1Off32 =
nullptr;
1101 if (FloatWidth > 32) {
1103 Builder.CreatePHI(Builder.getIntNTy(FloatWidth > 80 ? 64 : 32), 3);
1109 if (FloatWidth <= 80) {
1110 E0 = Builder.CreatePHI(Builder.getIntNTy(BitWidthNew), 3);
1111 E0->addIncoming(Sub1, IfThen20);
1112 E0->addIncoming(Sub2, SwEpilog);
1113 E0->addIncoming(Sub2, IfElse);
1115 Value *And29 =
nullptr;
1116 if (FloatWidth > 80) {
1117 Value *Temp2 = Builder.CreateShl(Builder.getIntN(
BitWidth, 1),
1119 And29 = Builder.CreateAnd(Shr, Temp2,
"and29");
1121 Value *Conv28 = Builder.CreateTrunc(Shr, Builder.getInt32Ty());
1122 And29 = Builder.CreateAnd(
1125 unsigned TempMod = FPMantissaWidth % 32;
1126 Value *And34 =
nullptr;
1127 Value *Shl30 =
nullptr;
1128 if (FloatWidth > 80) {
1130 Value *
Add = Builder.CreateShl(AAddr1Off32, Builder.getInt64(TempMod));
1131 Shl30 = Builder.CreateAdd(
1132 Add, Builder.getInt64(((1ull << (62ull - TempMod)) - 1ull) << TempMod));
1133 And34 = Builder.CreateZExt(Shl30, Builder.getInt128Ty());
1135 Value *
Add = Builder.CreateShl(E0, Builder.getInt32(TempMod));
1136 Shl30 = Builder.CreateAdd(
1137 Add, Builder.getInt32(((1 << (30 - TempMod)) - 1) << TempMod));
1138 And34 = Builder.CreateAnd(FloatWidth > 32 ? AAddr1Off32 : AAddr1Off0,
1139 Builder.getInt32((1 << TempMod) - 1));
1141 Value *Or35 =
nullptr;
1142 if (FloatWidth > 80) {
1143 Value *And29Trunc = Builder.CreateTrunc(And29, Builder.getInt128Ty());
1144 Value *Or31 = Builder.CreateOr(And29Trunc, And34);
1145 Value *Or34 = Builder.CreateShl(Or31, Builder.getIntN(128, 64));
1146 Value *Temp3 = Builder.CreateShl(Builder.getIntN(128, 1),
1147 Builder.getIntN(128, FPMantissaWidth));
1148 Value *Temp4 = Builder.CreateSub(Temp3, Builder.getIntN(128, 1));
1149 Value *A6 = Builder.CreateAnd(AAddr1Off0, Temp4);
1150 Or35 = Builder.CreateOr(Or34, A6);
1152 Value *Or31 = Builder.CreateOr(And34, And29);
1153 Or35 = Builder.CreateOr(IsSigned ? Or31 : And34, Shl30);
1155 Value *A4 =
nullptr;
1157 Value *ZExt1 = Builder.CreateZExt(Or35, Builder.getIntNTy(FloatWidth));
1158 Value *Shl1 = Builder.CreateShl(ZExt1, Builder.getIntN(FloatWidth, 32));
1160 Builder.CreateAnd(AAddr1Off0, Builder.getIntN(FloatWidth, 0xFFFFFFFF));
1161 Value *Or1 = Builder.CreateOr(Shl1, And1);
1162 A4 = Builder.CreateBitCast(Or1, IToFP->
getType());
1166 A4 = Builder.CreateFPTrunc(A40, IToFP->
getType());
1172 A4 = Builder.CreateFPTrunc(A40, IToFP->
getType());
1174 A4 = Builder.CreateBitCast(Or35, IToFP->
getType());
1184 unsigned ExponentWidth = FloatWidth - FPMantissaWidth - 1;
1185 uint64_t MinInfExp = 1ULL << (ExponentWidth - 1);
1187 Value *MinInfExpVal = Builder.getIntN(BitWidthNew, MinInfExp);
1188 Value *Overflow = Builder.CreateICmpUGE(Sub2, MinInfExpVal);
1195 Inf = Builder.CreateSelectWithUnknownProfile(IsNeg, NegInf, Inf,
1198 A4 = Builder.CreateSelect(Overflow, Inf, A4);
1202 LLVMContext::MD_prof,
1206 Builder.CreateBr(
End);
1209 Builder.SetInsertPoint(
End->begin());
1225 unsigned NumElements = VTy->getElementCount().getFixedValue();
1227 for (
unsigned Idx = 0; Idx < NumElements; ++Idx) {
1228 Value *Ext = Builder.CreateExtractElement(
I->getOperand(0), Idx);
1230 Value *NewOp =
nullptr;
1232 NewOp = Builder.CreateBinOp(
1233 BinOp->getOpcode(), Ext,
1234 Builder.CreateExtractElement(
I->getOperand(1), Idx));
1236 NewOp = Builder.CreateCast(CastI->getOpcode(), Ext,
1237 I->getType()->getScalarType());
1239 assert(
II->getIntrinsicID() == Intrinsic::fptoui_sat ||
1240 II->getIntrinsicID() == Intrinsic::fptosi_sat);
1241 NewOp = Builder.CreateIntrinsic(
I->getType()->getScalarType(),
1242 II->getIntrinsicID(), {Ext});
1246 Result = Builder.CreateInsertElement(Result, NewOp, Idx);
1248 ScalarizedI->copyIRFlags(
I,
true);
1253 I->replaceAllUsesWith(Result);
1254 I->dropAllReferences();
1255 I->eraseFromParent();
1260 if (
I.getOperand(0)->getType()->isVectorTy())
1271 unsigned MaxLegalFpConvertBitWidth = Opts.expand_fp_convert_bits.value_or(
1272 TLI.getMaxLargeFPConvertBitWidthSupported());
1273 unsigned MaxLegalDivRemBitWidth =
1274 Opts.expand_div_rem_bits.value_or(
TLI.getMaxDivRemBitWidthSupported());
1276 bool DisableExpandLargeFp =
1278 bool DisableExpandLargeDivRem =
1280 bool DisableFrem = !FRemExpander::shouldExpandAnyFremType(
TLI, Libcalls);
1282 if (DisableExpandLargeFp && DisableFrem && DisableExpandLargeDivRem)
1286 Type *Ty =
I.getType();
1288 if (Ty->isScalableTy())
1291 switch (
I.getOpcode()) {
1292 case Instruction::FRem:
1293 return !DisableFrem &&
1294 FRemExpander::shouldExpandFremType(
TLI, Libcalls, Ty);
1295 case Instruction::FPToUI:
1296 case Instruction::FPToSI:
1297 return !DisableExpandLargeFp &&
1299 MaxLegalFpConvertBitWidth;
1300 case Instruction::UIToFP:
1301 case Instruction::SIToFP:
1302 return !DisableExpandLargeFp &&
1304 ->getIntegerBitWidth() > MaxLegalFpConvertBitWidth;
1305 case Instruction::UDiv:
1306 case Instruction::SDiv:
1307 case Instruction::URem:
1308 case Instruction::SRem:
1313 return !DisableExpandLargeDivRem &&
1315 MaxLegalDivRemBitWidth;
1316 case Instruction::Call: {
1318 if (
II && (
II->getIntrinsicID() == Intrinsic::fptoui_sat ||
1319 II->getIntrinsicID() == Intrinsic::fptosi_sat)) {
1320 return !DisableExpandLargeFp &&
1322 MaxLegalFpConvertBitWidth;
1334 if (!ShouldHandleInst(
I))
1341 while (!Worklist.
empty()) {
1344 switch (
I->getOpcode()) {
1345 case Instruction::FRem: {
1346 auto SQ = [&]() -> std::optional<SimplifyQuery> {
1348 auto Res = std::make_optional<SimplifyQuery>(
I->getDataLayout(),
I);
1359 case Instruction::FPToUI:
1362 case Instruction::FPToSI:
1366 case Instruction::UIToFP:
1367 case Instruction::SIToFP:
1371 case Instruction::UDiv:
1372 case Instruction::SDiv:
1373 case Instruction::URem:
1374 case Instruction::SRem: {
1381 unsigned Opc = BO->getOpcode();
1382 if (
Opc == Instruction::UDiv ||
Opc == Instruction::SDiv)
1389 case Instruction::Call: {
1391 assert(
II->getIntrinsicID() == Intrinsic::fptoui_sat ||
1392 II->getIntrinsicID() == Intrinsic::fptosi_sat);
1394 II->getIntrinsicID() == Intrinsic::fptosi_sat);
1404class ExpandIRInstsLegacyPass :
public FunctionPass {
1411 : FunctionPass(
ID), OptLevel(OptLevel) {}
1416 auto *TM = &getAnalysis<TargetPassConfig>().getTM<TargetMachine>();
1417 const TargetSubtargetInfo *
Subtarget = TM->getSubtargetImpl(
F);
1419 AssumptionCache *AC =
nullptr;
1421 const LibcallLoweringInfo &Libcalls =
1422 getAnalysis<LibcallLoweringInfoWrapper>().getLibcallLowering(
1425 if (OptLevel != CodeGenOptLevel::None && !
F.hasOptNone())
1426 AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(
F);
1430 void getAnalysisUsage(AnalysisUsage &AU)
const override {
1433 if (OptLevel != CodeGenOptLevel::None)
1444 : TM(&TM), OptLevel(OptLevel) {}
1448 static_cast<PassInfoMixin<ExpandIRInstsPass> *
>(
this)->
printPipeline(
1449 OS, MapClassName2PassName);
1451 OS <<
"O" << (int)OptLevel;
1468 if (!LibcallLowering) {
1470 "' analysis required");
1481char ExpandIRInstsLegacyPass::ID = 0;
1483 "Expand certain fp instructions",
false,
false)
1489 return new ExpandIRInstsLegacyPass(OptLevel);
const AArch64Subtarget & Subtarget
const TargetLowering & TLI
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
static bool runImpl(MachineFunction &MF)
static bool runOnFunction(Function &F, bool PostInlining)
static bool expandFRem(BinaryOperator &I, std::optional< SimplifyQuery > &SQ)
static void expandIToFP(Instruction *IToFP)
Generate code to convert a fp number to integer, replacing S(U)IToFP with the generated code.
static void expandPow2DivRem(BinaryOperator *BO)
Expand division or remainder by a power-of-2 constant.
static bool isSigned(unsigned Opcode)
static void addToWorklist(Instruction &I, SmallVector< Instruction *, 4 > &Worklist)
static Value * addSignedBias(IRBuilder<> &Builder, Value *X, unsigned BitWidth, unsigned ShiftAmt)
For signed div/rem by a power of 2, compute the bias-adjusted dividend: Sign = ashr X,...
static void expandFPToI(Instruction *FPToI, bool IsSaturating, bool IsSigned)
Generate code to convert a fp number to integer, replacing FPToS(U)I with the generated code.
static bool isConstantPowerOfTwo(Value *V, bool SignedOp)
static void scalarize(Instruction *I, SmallVectorImpl< Instruction * > &Worklist)
This is the interface for a simple mod/ref and alias analysis over globals.
Module.h This file contains the declarations for the Module class.
This header defines various interfaces for pass management in LLVM.
uint64_t IntrinsicInst * II
FunctionAnalysisManager FAM
#define INITIALIZE_PASS_DEPENDENCY(depName)
#define INITIALIZE_PASS_END(passName, arg, name, cfg, analysis)
#define INITIALIZE_PASS_BEGIN(passName, arg, name, cfg, analysis)
This file contains the declarations for profiling metadata utility functions.
This file defines the SmallVector class.
static TableGen::Emitter::Opt Y("gen-skeleton-entry", EmitSkeleton, "Generate example skeleton entry")
This file describes how to lower LLVM code to machine code.
Target-Independent Code Generator Pass Configuration Options pass.
const AArch64TargetLowering * getTargetLowering() const override
Class for arbitrary precision integers.
static APInt getSignMask(unsigned BitWidth)
Get the SignMask for a specific bit width.
static APInt getSignedMaxValue(unsigned numBits)
Gets maximum signed value of APInt for a specific bit width.
bool isNegative() const
Determine sign of this APInt.
unsigned countr_zero() const
Count the number of trailing zero bits.
static APInt getSignedMinValue(unsigned numBits)
Gets minimum signed value of APInt for a specific bit width.
bool isPowerOf2() const
Check if this APInt's value is a power of two greater than zero.
static APInt getLowBitsSet(unsigned numBits, unsigned loBitsSet)
Constructs an APInt value that has the bottom loBitsSet bits set.
static APInt getOneBitSet(unsigned numBits, unsigned BitNo)
Return an APInt with exactly one bit set in the result.
AnalysisUsage & addRequired()
AnalysisUsage & addPreserved()
Add the specified Pass class to the set of analyses preserved by this pass.
A function analysis which provides an AssumptionCache.
A cache of @llvm.assume calls within a function.
LLVM Basic Block Representation.
const Function * getParent() const
Return the enclosing method, or null if none.
static BasicBlock * Create(LLVMContext &Context, const Twine &Name="", Function *Parent=nullptr, BasicBlock *InsertBefore=nullptr)
Creates a new BasicBlock.
BinaryOps getOpcode() const
@ FCMP_OLT
0 1 0 0 True if ordered and less than
@ ICMP_SGT
signed greater than
static LLVM_ABI ConstantFP * getZero(Type *Ty, bool Negative=false)
static LLVM_ABI ConstantFP * getQNaN(Type *Ty, bool Negative=false, APInt *Payload=nullptr)
static LLVM_ABI ConstantFP * getInfinity(Type *Ty, bool Negative=false)
This is the shared class of boolean and integer constants.
static ConstantInt * getSigned(IntegerType *Ty, int64_t V, bool ImplicitTrunc=false)
Return a ConstantInt with the specified value for the specified type.
static LLVM_ABI Constant * getAllOnesValue(Type *Ty)
static LLVM_ABI Constant * getNullValue(Type *Ty)
Constructor to create a '0' constant of arbitrary type.
LLVM_ABI ExpandIRInstsPass(const TargetMachine &TM, CodeGenOptLevel OptLevel)
LLVM_ABI PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM)
LLVM_ABI void printPipeline(raw_ostream &OS, function_ref< StringRef(StringRef)> MapClassName2PassName)
Convenience struct for specifying and reasoning about fast-math flags.
void setAllowContract(bool B=true)
void setAllowReciprocal(bool B=true)
void setNoNaNs(bool B=true)
void setNoInfs(bool B=true)
FunctionPass class - This class is used to implement most global optimizations.
Module * getParent()
Get the module that this global value is contained inside of...
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
LLVM_ABI InstListType::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
LLVM_ABI bool isExact() const LLVM_READONLY
Determine whether the exact flag is set.
LLVM_ABI void setMetadata(unsigned KindID, MDNode *Node)
Set the metadata of the specified kind to the specified node.
unsigned getOpcode() const
Returns a member of one of the enums like Instruction::Add.
Class to represent integer types.
@ MAX_INT_BITS
Maximum number of bits that can be specified.
Tracks which library functions to use for a particular subtarget or function.
RTLIB::LibcallImpl getLibcallImpl(RTLIB::Libcall Call) const
Return the lowering's selection of implementation call for Call.
LLVM_ABI MDNode * createBranchWeights(uint32_t TrueWeight, uint32_t FalseWeight, bool IsExpected=false)
Return metadata containing two branch weights.
LLVM_ABI MDNode * createLikelyBranchWeights()
Return metadata containing two branch weights, with significant bias towards true destination.
LLVM_ABI MDNode * createUnlikelyBranchWeights()
Return metadata containing two branch weights, with significant bias towards false destination.
Records a mapping from an opaque lowering context to its LibcallLoweringInfo.
void addIncoming(Value *V, BasicBlock *BB)
Add an incoming value to the end of the PHI list.
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.
static PreservedAnalyses none()
Convenience factory function for the empty preserved set.
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
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.
LegalizeAction getOperationAction(unsigned Op, EVT VT) const
Return how this operation should be treated: either it is legal, needs to be promoted to a larger siz...
This class defines information used to lower LLVM code to legal SelectionDAG operators that the targe...
Primary interface to the complete machine description for the target machine.
TargetSubtargetInfo - Generic base class for all target subtargets.
virtual const TargetLowering * getTargetLowering() const
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
The instances of the Type class are immutable: once they are created, they are never changed.
LLVM_ABI unsigned getIntegerBitWidth() const
bool isX86_FP80Ty() const
Return true if this is x86 long double.
bool isBFloatTy() const
Return true if this is 'bfloat', a 16-bit bfloat type.
static LLVM_ABI Type * getFP128Ty(LLVMContext &C)
bool is16bitFPTy() const
Return true if this is a 16-bit float type.
Type * getScalarType() const
If this is a vector type, return the element type, otherwise return 'this'.
bool isHalfTy() const
Return true if this is 'half', a 16-bit IEEE fp type.
bool isDoubleTy() const
Return true if this is 'double', a 64-bit IEEE fp type.
static LLVM_ABI IntegerType * getIntNTy(LLVMContext &C, unsigned N)
static LLVM_ABI Type * getFloatTy(LLVMContext &C)
LLVM_ABI int getFPMantissaWidth() const
Return the width of the mantissa of this type.
LLVM_ABI const fltSemantics & getFltSemantics() const
void dropAllReferences()
Drop all references to operands.
Value * getOperand(unsigned i) const
LLVM Value Representation.
Type * getType() const
All values are typed, get the type of this value.
LLVM_ABI void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
LLVMContext & getContext() const
All values hold a context through their type.
LLVM_ABI void takeName(Value *V)
Transfer the name from V to this value.
An efficient, type-erasing, non-owning reference to a callable.
const ParentTy * getParent() const
This class implements an extremely fast bulk output stream that can only output to a stream.
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
@ BasicBlock
Various leaf nodes.
LLVM_ABI Function * getOrInsertDeclaration(Module *M, ID id, ArrayRef< Type * > OverloadTys={})
Look up the Function declaration of the intrinsic id in the Module M.
This is an optimization pass for GlobalISel generic memory operations.
LLVM_ABI bool expandDivision(BinaryOperator *Div)
Generate code to divide two integers, replacing Div with the generated code.
LLVM_ABI cl::opt< bool > ProfcheckDisableMetadataFixes
LLVM_ABI bool isKnownNeverInfinity(const Value *V, const SimplifyQuery &SQ, unsigned Depth=0)
Return true if the floating-point scalar value is not an infinity or if the floating-point vector val...
LLVM_ABI void setExplicitlyUnknownBranchWeightsIfProfiled(Instruction &I, StringRef PassName, const Function *F=nullptr)
Like setExplicitlyUnknownBranchWeights(...), but only sets unknown branch weights in the new instruct...
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
OuterAnalysisManagerProxy< ModuleAnalysisManager, Function > ModuleAnalysisManagerFunctionProxy
Provide the ModuleAnalysisManager to Function proxy.
LLVM_ABI void applyProfMetadataIfEnabled(Value *V, llvm::function_ref< void(Instruction *)> setMetadataCallback)
inst_iterator inst_begin(Function *F)
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Value
uint64_t PowerOf2Ceil(uint64_t A)
Returns the power of two which is greater than or equal to the given value.
LLVM_ABI FunctionPass * createExpandIRInstsPass(CodeGenOptLevel)
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly.
LLVM_ABI const LibcallLoweringInfo & getLibcallLowering(const ModuleLibcallLoweringInfo &ModuleInfo, const TargetSubtargetInfo &Subtarget)
Resolve the LibcallLoweringInfo for Subtarget from the module-level ModuleInfo, applying the subtarge...
decltype(auto) get(const PointerIntPair< PointerTy, IntBits, IntType, PtrTraits, Info > &Pair)
LLVM_ABI void SplitBlockAndInsertIfThenElse(Value *Cond, BasicBlock::iterator SplitBefore, Instruction **ThenTerm, Instruction **ElseTerm, MDNode *BranchWeights=nullptr, DomTreeUpdater *DTU=nullptr, LoopInfo *LI=nullptr)
SplitBlockAndInsertIfThenElse is similar to SplitBlockAndInsertIfThen, but also creates the ElseBlock...
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
IRBuilder(LLVMContext &, FolderTy, InserterTy) -> IRBuilder< FolderTy, InserterTy >
CodeGenOptLevel
Code generation optimization level.
inst_iterator inst_end(Function *F)
@ Xor
Bitwise or logical XOR of integers.
@ Sub
Subtraction of integers.
LLVM_ABI bool isGuaranteedNotToBeUndefOrPoison(const Value *V, AssumptionCache *AC=nullptr, const Instruction *CtxI=nullptr, const DominatorTree *DT=nullptr, unsigned Depth=0)
Return true if this function can prove that V does not have undef bits and is never poison.
constexpr unsigned BitWidth
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
bool is_contained(R &&Range, const E &Element)
Returns true if Element is found in Range.
LLVM_ABI bool expandRemainder(BinaryOperator *Rem)
Generate code to calculate the remainder of two integers, replacing Rem with the generated code.
AnalysisManager< Function > FunctionAnalysisManager
Convenience typedef for the Function analysis manager.
@ End
Run the machine verifier once, at the end of the pipeline.
const CodeGenOptions & getCodeGenOptions(const LLVMContext &C)
bool isSimple() const
Test if the given EVT is simple (as opposed to being extended).
static LLVM_ABI EVT getEVT(Type *Ty, bool HandleUnknown=false)
Return the value type corresponding to the specified type.
MVT getSimpleVT() const
Return the SimpleValueType held in the specified simple EVT.
bool isVector() const
Return true if this is a vector value type.